repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/download_models.rs
src/download_models.rs
use hf_hub::api::tokio::Api; use std::path::{Path, PathBuf}; use tokio::fs; use tracing::info; pub enum Model { Model(String), AllRtDetr2, AllYolo5, AllRfDetr, All, } pub const RT_DETR2_MODELS: (&str, &[&str]) = ( "xnorpx/rt-detr2-onnx", &[ "rt-detrv2-s.onnx", "rt-detrv2-s.yaml", "rt-detrv2-ms.onnx", "rt-detrv2-ms.yaml", "rt-detrv2-m.onnx", "rt-detrv2-m.yaml", "rt-detrv2-l.onnx", "rt-detrv2-l.yaml", "rt-detrv2-x.onnx", "rt-detrv2-x.yaml", ], ); pub const YOLO5_MODELS: (&str, &[&str]) = ( "xnorpx/blue-onyx-yolo5", &[ "delivery.onnx", "delivery.yaml", "IPcam-animal.onnx", "IPcam-animal.yaml", "ipcam-bird.onnx", "ipcam-bird.yaml", "IPcam-combined.onnx", "IPcam-combined.yaml", "IPcam-dark.onnx", "IPcam-dark.yaml", "IPcam-general.onnx", "IPcam-general.yaml", "package.onnx", "package.yaml", ], ); pub const RF_DETR_MODELS: (&str, &[&str]) = ( "xnorpx/rf-detr", &[ "rf-detr-n.onnx", "rf-detr-n.yaml", "rf-detr-s.onnx", "rf-detr-s.yaml", "rf-detr-m.onnx", "rf-detr-m.yaml", ], ); pub fn get_all_models() -> [(&'static str, &'static [&'static str]); 3] { [RT_DETR2_MODELS, YOLO5_MODELS, RF_DETR_MODELS] } pub fn get_all_model_names() -> Vec<String> { let all_models = get_all_models(); let mut models = Vec::new(); for model_set in all_models.iter() { for file in model_set.1.iter() { if file.ends_with(".onnx") { models.push(file.to_string()); } } } models } pub fn list_models() { let model_names = get_all_model_names(); for model_name in model_names { info!("{}", model_name); } } /// Download models based on the Model enum pub async fn download_model(model_path: PathBuf, model: Model) -> anyhow::Result<()> { if !model_path.exists() { fs::create_dir_all(model_path.clone()).await?; } let mut downloaded_models: Vec<String> = Vec::new(); match model { Model::Model(model_name) => { // Download specific model and its yaml download_file_to_dir(&model_name, &model_path).await?; downloaded_models.push(model_name.clone()); let yaml_name = model_name.replace(".onnx", ".yaml"); match download_file_to_dir(&yaml_name, &model_path).await { Ok(_) => { downloaded_models.push(yaml_name); } Err(e) => { info!("Warning: Failed to download YAML file {}: {}", yaml_name, e); info!("The model will still work but may use default object classes"); } } } Model::AllRtDetr2 => { download_repository_files(RT_DETR2_MODELS, &model_path, &mut downloaded_models).await?; } Model::AllYolo5 => { download_repository_files(YOLO5_MODELS, &model_path, &mut downloaded_models).await?; } Model::AllRfDetr => { download_repository_files(RF_DETR_MODELS, &model_path, &mut downloaded_models).await?; } Model::All => { let all_models = get_all_models(); for model_repo in all_models.iter() { download_repository_files(*model_repo, &model_path, &mut downloaded_models).await?; } } } info!("Successfully downloaded models: {:?}", downloaded_models); Ok(()) } /// Download all files from a specific repository async fn download_repository_files( models: (&str, &[&str]), target_dir: &Path, downloaded_models: &mut Vec<String>, ) -> anyhow::Result<()> { let (repo_name, files) = models; let api = Api::new()?; let api_repo = api.model(repo_name.to_string()); let mut errors = Vec::new(); for filename in files.iter() { match api_repo.get(filename).await { Ok(cached_file) => { let target_path = target_dir.join(filename); match fs::copy(&cached_file, &target_path).await { Ok(_) => { info!("Downloaded {} to {}", filename, target_path.display()); downloaded_models.push(filename.to_string()); } Err(e) => { let error_msg = format!( "Failed to copy {} to {}: {}", filename, target_path.display(), e ); info!("Warning: {}", error_msg); errors.push(error_msg); } } } Err(e) => { let error_msg = format!("Failed to download {filename} from {repo_name}: {e}"); info!("Warning: {}", error_msg); errors.push(error_msg); } } } if errors.is_empty() { Ok(()) } else { info!("Some files failed to download but continuing: {:?}", errors); Ok(()) // Don't fail the entire operation for missing individual files } } /// Download a specific file from any of the available repositories pub async fn download_file_to_dir(filename: &str, target_dir: &Path) -> anyhow::Result<()> { let all_models = get_all_models(); for (repo_name, files) in all_models.iter() { if files.contains(&filename) { info!("Found {} in repository {}", filename, repo_name); // Check if target directory exists if !target_dir.exists() { fs::create_dir_all(target_dir).await?; } let api = Api::new()?; let api_repo = api.model(repo_name.to_string()); // Download the file let cached_file = api_repo.get(filename).await?; let target_path = target_dir.join(filename); fs::copy(&cached_file, &target_path).await?; info!("Downloaded {} to {}", filename, target_path.display()); return Ok(()); } } Err(anyhow::anyhow!( "File {} not found in any repository", filename )) }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/lib.rs
src/lib.rs
use clap::ValueEnum; use cli::Cli; use detector::OnnxConfig; use serde::Deserialize; use server::run_server; use startup_coordinator::spawn_detector_initialization; use std::{future::Future, path::PathBuf}; use tokio_util::sync::CancellationToken; use tracing::{Level, info}; pub mod api; pub mod cli; pub mod detector; pub mod download_models; pub mod image; pub mod server; pub mod startup_coordinator; pub mod system_info; pub mod worker; pub static DOG_BIKE_CAR_BYTES: &[u8] = include_bytes!("../assets/dog_bike_car.jpg"); pub static NANO_RF_DETR_MODEL_FILE_NAME: &str = "rf-detr-n.onnx"; pub static COCO_CLASSES_STR: &str = include_str!("../assets/coco_classes.yaml"); #[allow(non_snake_case)] #[derive(Debug, Deserialize)] struct CocoClasses { NAMES: Vec<String>, } /// Type alias for the service result containing restart flag and optional worker thread handle pub type ServiceResult = anyhow::Result<(bool, Option<std::thread::JoinHandle<()>>)>; pub fn blue_onyx_service( args: Cli, ) -> anyhow::Result<( impl Future<Output = ServiceResult>, CancellationToken, CancellationToken, // Add restart token )> { // Get the config path for the server let config_path = args.get_current_config_path()?; let detector_config = detector::DetectorConfig { object_detection_onnx_config: OnnxConfig { force_cpu: args.force_cpu, gpu_index: args.gpu_index, intra_threads: args.intra_threads, inter_threads: args.inter_threads, model: args.model, }, object_classes: args.object_classes, object_filter: args.object_filter, confidence_threshold: args.confidence_threshold, save_image_path: args.save_image_path, save_ref_image: args.save_ref_image, timeout: args.request_timeout, object_detection_model: args.object_detection_model_type, }; // Log available GPU information log_available_gpus(); // Start the detector initialization in the background let detector_init_receiver = spawn_detector_initialization(detector_config, args.worker_queue_size); // Create placeholder metrics (will be updated when detector is ready) let metrics = server::Metrics::new("Initializing...".to_string(), "Initializing...".to_string()); let cancel_token = CancellationToken::new(); let restart_token = CancellationToken::new(); let server_future = run_server( args.port, cancel_token.clone(), restart_token.clone(), detector_init_receiver, metrics, config_path, ); Ok((server_future, cancel_token, restart_token)) } pub fn get_object_classes(yaml_file: Option<PathBuf>) -> anyhow::Result<Vec<String>> { let yaml_data = match yaml_file { Some(yaml_file) => std::fs::read_to_string(yaml_file)?, None => COCO_CLASSES_STR.to_string(), }; Ok(serde_yaml::from_str::<CocoClasses>(&yaml_data)?.NAMES) } pub fn direct_ml_available() -> bool { #[cfg(not(windows))] { false } #[cfg(windows)] { let Ok(exe_path) = std::env::current_exe() else { return false; }; let Some(exe_dir) = exe_path.parent() else { return false; }; exe_dir.join("DirectML.dll").exists() } } /// Log information about available GPU devices pub fn log_available_gpus() { #[cfg(windows)] if direct_ml_available() { info!("DirectML is available for GPU inference"); } else { info!("DirectML is not available - only CPU inference will be supported"); } #[cfg(not(windows))] info!("GPU acceleration not available on this platform - only CPU inference will be supported"); // Log available GPU devices match system_info::gpu_info(true) { Ok(_) => { // gpu_info already logs the available GPUs when log_info is true } Err(e) => { tracing::warn!("Failed to enumerate GPU devices: {}", e); } } } use std::sync::OnceLock; // Global reload handle for regular blue_onyx binary static REGULAR_LOG_RELOAD_HANDLE: OnceLock< tracing_subscriber::reload::Handle<tracing_subscriber::EnvFilter, tracing_subscriber::Registry>, > = OnceLock::new(); #[cfg(target_os = "windows")] // Global reload handle for service binary static SERVICE_LOG_RELOAD_HANDLE: OnceLock< tracing_subscriber::reload::Handle<tracing_subscriber::EnvFilter, tracing_subscriber::Registry>, > = OnceLock::new(); pub fn init_logging( log_level: LogLevel, log_path: &mut Option<PathBuf>, ) -> anyhow::Result<Option<tracing_appender::non_blocking::WorkerGuard>> { use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::{EnvFilter, reload}; setup_ansi_support(); // Create a reloadable env filter let env_filter = EnvFilter::try_from_default_env() .unwrap_or_else(|_| EnvFilter::new(level_to_filter_string(log_level))); let (env_filter, reload_handle) = reload::Layer::new(env_filter); // Store the reload handle globally for later use REGULAR_LOG_RELOAD_HANDLE .set(reload_handle) .map_err(|_| anyhow::anyhow!("Failed to set log reload handle"))?; let guard = if let Some(path) = log_path.clone() { let log_directory = if path.starts_with(".") { let stripped = path.strip_prefix(".").unwrap_or(&path).to_path_buf(); std::env::current_exe() .ok() .and_then(|exe| exe.parent().map(|p| p.join(stripped.clone()))) .unwrap_or(stripped) } else { path }; *log_path = Some(log_directory.clone()); let log_file = log_directory.join("blue_onyx.log"); println!("Starting Blue Onyx, logging into: {}", log_file.display()); let file_appender = tracing_appender::rolling::daily(&log_directory, "blue_onyx.log"); let (non_blocking, guard) = tracing_appender::non_blocking(file_appender); let file_layer = tracing_subscriber::fmt::layer() .with_writer(non_blocking) .with_ansi(false); tracing_subscriber::registry() .with(env_filter) .with(file_layer) .try_init() .map_err(|_| anyhow::anyhow!("Logging already initialized"))?; Some(guard) } else { tracing_subscriber::registry() .with(env_filter) .with(tracing_subscriber::fmt::layer()) .try_init() .map_err(|_| anyhow::anyhow!("Logging already initialized"))?; None }; info!( ?log_level, "Logging initialized with dynamic filtering support" ); Ok(guard) } pub fn update_log_level(new_log_level: LogLevel) -> anyhow::Result<()> { use tracing_subscriber::EnvFilter; if let Some(reload_handle) = REGULAR_LOG_RELOAD_HANDLE.get() { let new_filter = EnvFilter::new(level_to_filter_string(new_log_level)); reload_handle .reload(new_filter) .map_err(|e| anyhow::anyhow!("Failed to reload log filter: {}", e))?; info!(?new_log_level, "Log level updated dynamically"); Ok(()) } else { Err(anyhow::anyhow!("Log reload handle not available")) } } #[cfg(target_os = "windows")] pub fn init_service_logging(log_level: LogLevel) -> anyhow::Result<()> { use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::{EnvFilter, reload}; // Create a reloadable env filter let env_filter = EnvFilter::try_from_default_env() .unwrap_or_else(|_| EnvFilter::new(level_to_filter_string(log_level))); let (env_filter, reload_handle) = reload::Layer::new(env_filter); // Store the reload handle globally for later use SERVICE_LOG_RELOAD_HANDLE .set(reload_handle) .map_err(|_| anyhow::anyhow!("Failed to set log reload handle"))?; // Create Windows Event Log layer only - no file or stdout logging let eventlog_layer = tracing_layer_win_eventlog::EventLogLayer::new("Blue Onyx Service") .map_err(|e| anyhow::anyhow!("Failed to create Windows Event Log layer: {}", e))?; // Try to initialize with Event Log and reloadable filter tracing_subscriber::registry() .with(env_filter) .with(eventlog_layer) .try_init() .map_err(|_| anyhow::anyhow!("Logging already initialized"))?; info!( ?log_level, "Service logging initialized with Windows Event Log and dynamic filtering" ); Ok(()) } #[cfg(target_os = "windows")] pub fn update_service_log_level(new_log_level: LogLevel) -> anyhow::Result<()> { use tracing_subscriber::EnvFilter; if let Some(reload_handle) = SERVICE_LOG_RELOAD_HANDLE.get() { let new_filter = EnvFilter::new(level_to_filter_string(new_log_level)); reload_handle .reload(new_filter) .map_err(|e| anyhow::anyhow!("Failed to reload log filter: {}", e))?; info!(?new_log_level, "Log level updated dynamically"); Ok(()) } else { Err(anyhow::anyhow!("Log reload handle not available")) } } fn level_to_filter_string(log_level: LogLevel) -> String { match log_level { LogLevel::Trace => "trace", LogLevel::Debug => "debug", LogLevel::Info => "info", LogLevel::Warn => "warn", LogLevel::Error => "error", } .to_string() } fn setup_ansi_support() { #[cfg(target_os = "windows")] if let Err(e) = ansi_term::enable_ansi_support() { eprintln!("Failed to enable ANSI support: {e}"); } } #[derive( Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug, serde::Serialize, serde::Deserialize, )] pub enum LogLevel { Trace, Debug, Info, Warn, Error, } impl From<LogLevel> for Level { fn from(value: LogLevel) -> Self { match value { LogLevel::Trace => Level::TRACE, LogLevel::Debug => Level::DEBUG, LogLevel::Info => Level::INFO, LogLevel::Warn => Level::WARN, LogLevel::Error => Level::ERROR, } } } /// Ensures model and yaml files exist, downloading them if needed /// Returns the paths to the model and yaml files pub fn ensure_model_files(model_name: Option<String>) -> anyhow::Result<(PathBuf, PathBuf)> { // Use default model if none provided let model_filename = model_name.unwrap_or_else(|| NANO_RF_DETR_MODEL_FILE_NAME.to_string()); // Get the directory where models are stored (next to the executable) let exe_path = std::env::current_exe()?; let models_dir = exe_path .parent() .ok_or_else(|| anyhow::anyhow!("Failed to get parent directory of executable"))?; let model_path = models_dir.join(&model_filename); let yaml_filename = model_filename.replace(".onnx", ".yaml"); let yaml_path = models_dir.join(&yaml_filename); // Check if model exists, download if not if !model_path.exists() { info!("Model {} not found, downloading...", model_filename); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; rt.block_on(async { download_models::download_file_to_dir(&model_filename, models_dir).await })?; } // Verify model file exists after download if !model_path.exists() { return Err(anyhow::anyhow!( "Model file {} is required but could not be found or downloaded", model_filename )); } // Check if yaml exists, download if not (MANDATORY) if !yaml_path.exists() { info!("Yaml file {} not found, downloading...", yaml_filename); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; rt.block_on(async { download_models::download_file_to_dir(&yaml_filename, models_dir).await })?; } // Verify yaml file exists after download if !yaml_path.exists() { return Err(anyhow::anyhow!( "YAML file {} is required but could not be found or downloaded", yaml_filename )); } info!( "Model and YAML files ready: {} and {}", model_path.display(), yaml_path.display() ); Ok((model_path, yaml_path)) }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/image.rs
src/image.rs
use crate::api::Prediction; use ab_glyph::{FontArc, PxScale}; use anyhow::bail; use bytes::Bytes; use image::{DynamicImage, ImageBuffer}; use jpeg_encoder::{ColorType, Encoder}; use std::{fmt, path::Path, time::Instant}; use tracing::{debug, info}; use zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions}; use zune_jpeg::JpegDecoder; pub struct Image { pub name: Option<String>, pub width: usize, pub height: usize, pub pixels: Vec<u8>, } impl Image { pub fn resize(&mut self, size: usize) { self.pixels.resize(size, 0); } } impl fmt::Display for Image { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{:?}, Resolution: {}x{}", self.name, self.width, self.height ) } } impl Default for Image { fn default() -> Self { Self { width: 0, height: 0, pixels: Vec::with_capacity(99_532_800), name: None, } } } pub fn decode_jpeg(name: Option<String>, jpeg: Bytes, image: &mut Image) -> anyhow::Result<()> { let options = DecoderOptions::default() .set_strict_mode(true) .set_use_unsafe(true) .jpeg_set_out_colorspace(ColorSpace::RGB); let cursor = ZCursor::new(jpeg.to_vec()); let mut decoder = JpegDecoder::new_with_options(cursor, options); // We need to decode the headers first to get the output buffer size decoder.decode_headers()?; let output_buffer_size = decoder .output_buffer_size() .ok_or_else(|| anyhow::anyhow!("Failed to get decoder output buffer size"))?; // Resize the output buffer to the required size image.resize(output_buffer_size); // Decode the image into the output buffer decoder.decode_into(&mut image.pixels)?; let (width, height) = decoder .dimensions() .ok_or_else(|| anyhow::anyhow!("Failed to get image dimensions"))?; image.width = width; image.height = height; image.name = name; Ok(()) } pub fn load_image(jpeg_file: &Path) -> anyhow::Result<Bytes> { let path_str = jpeg_file .to_str() .ok_or_else(|| anyhow::anyhow!("Failed to get image path"))?; if !is_jpeg(path_str) { bail!("Image is not a JPEG file") } Ok(Bytes::from(std::fs::read(jpeg_file)?)) } pub fn encode_maybe_draw_boundary_boxes_and_save_jpeg( image: &Image, jpeg_file: &String, predictions: Option<&[Prediction]>, base_width: u32, base_height: u32, ) -> anyhow::Result<()> { let encode_image_start_time = Instant::now(); let image = create_dynamic_image_maybe_with_boundary_box(predictions, image, base_width, base_height)?; let encoder = Encoder::new_file(jpeg_file, 100)?; encoder.encode( image .as_rgb8() .ok_or_else(|| anyhow::anyhow!("Failed to convert image to RGB8"))?, image.width() as u16, image.height() as u16, ColorType::Rgb, )?; let encode_image_time = Instant::now().duration_since(encode_image_start_time); debug!(?encode_image_time, "Encode image time"); info!(?jpeg_file, "Image saved"); Ok(()) } pub fn is_jpeg(image_name: &str) -> bool { image_name.to_lowercase().ends_with(".jpg") || image_name.to_lowercase().ends_with(".jpeg") } pub fn create_random_jpeg_name() -> String { format!("image_{}.jpg", uuid::Uuid::new_v4()) } pub fn create_od_image_name(image_name: &str, strip_path: bool) -> anyhow::Result<String> { if !is_jpeg(image_name) { bail!("Image is not a JPEG file"); } let image_name = if strip_path { if let Some(file_name) = Path::new(image_name).file_name() && let Some(name_str) = file_name.to_str() { name_str.to_string() } else { return Err(anyhow::anyhow!( "Failed to strip path from image name or convert to string" )); } } else { image_name.to_string() }; let (mut od_image_name, ext) = if let Some(pos) = image_name.rfind('.') { if pos + 1 >= image_name.len() { bail!("Failed to get image extension"); } ( image_name[..pos].to_string(), image_name[(pos + 1)..].to_string(), ) } else { bail!("Failed to get image extension"); }; od_image_name.push_str("_od."); od_image_name.push_str(&ext); Ok(od_image_name) } pub fn create_dynamic_image_maybe_with_boundary_box( predictions: Option<&[Prediction]>, decoded_image: &Image, base_width: u32, base_height: u32, ) -> anyhow::Result<DynamicImage> { let (thickness, legend_size) = boundary_box_config( decoded_image.width as u32, decoded_image.height as u32, base_width, base_height, ); let mut img = ImageBuffer::from_vec( decoded_image.width as u32, decoded_image.height as u32, decoded_image.pixels.clone(), ) .ok_or_else(|| anyhow::anyhow!("Failed to create image buffer"))?; let font = if legend_size > 0 { Some(FontArc::try_from_slice(include_bytes!( "./../assets/roboto-mono-stripped.ttf" ))?) } else { None }; if let Some(predictions) = predictions { for prediction in predictions { let dx = prediction.x_max - prediction.x_min; let dy = prediction.y_max - prediction.y_min; if dx > 0 && dy > 0 { for t in 0..thickness { let x_min = prediction.x_min + t; let y_min = prediction.y_min + t; let rect_width = dx - 2 * t; let rect_height = dy - 2 * t; imageproc::drawing::draw_hollow_rect_mut( &mut img, imageproc::rect::Rect::at(x_min as i32, y_min as i32) .of_size(rect_width as u32, rect_height as u32), image::Rgb([255, 0, 0]), ); } } if let Some(font) = font.as_ref() { imageproc::drawing::draw_filled_rect_mut( &mut img, imageproc::rect::Rect::at(prediction.x_min as i32, prediction.y_min as i32) .of_size(dx as u32, legend_size as u32), image::Rgb([170, 0, 0]), ); let legend = format!( "{} {:.0}%", prediction.label, prediction.confidence * 100_f32 ); imageproc::drawing::draw_text_mut( &mut img, image::Rgb([255, 255, 255]), prediction.x_min as i32, prediction.y_min as i32, PxScale::from(legend_size as f32 - 1.), font, &legend, ) } } } Ok(DynamicImage::ImageRgb8(img)) } fn boundary_box_config(width: u32, height: u32, base_width: u32, base_height: u32) -> (usize, u64) { // Use dynamic scaling based on the ratio between original image and model input size let scale_width = width as f32 / base_width as f32; let scale_height = height as f32 / base_height as f32; let scale = scale_width.max(scale_height).max(0.5); // Minimum scale of 0.5 let base_thickness = 1.0; let base_fontsize = 16.0; let thickness = (base_thickness * scale).ceil() as usize; let fontsize = (base_fontsize * scale).ceil() as u64; (thickness.max(1), fontsize.max(12)) } pub struct Resizer { resizer: fast_image_resize::Resizer, target_width: usize, target_height: usize, } impl Resizer { pub fn new(target_width: usize, target_height: usize) -> anyhow::Result<Self> { let resizer = fast_image_resize::Resizer::new(); Ok(Self { resizer, target_width, target_height, }) } pub fn resize_image( &mut self, original_image: &mut Image, resized_image: &mut Image, ) -> anyhow::Result<()> { debug!( "Resizing image from {}x{} to {}x{}", original_image.width, original_image.height, self.target_width, self.target_height ); let src_image = fast_image_resize::images::Image::from_slice_u8( original_image.width as u32, original_image.height as u32, &mut original_image.pixels, fast_image_resize::PixelType::U8x3, )?; if resized_image.height != self.target_height { resized_image.height = self.target_height } if resized_image.width != self.target_width { resized_image.width = self.target_width } resized_image.resize(self.target_width * self.target_height * 3); let mut dst_image = fast_image_resize::images::Image::from_slice_u8( resized_image.width as u32, resized_image.height as u32, &mut resized_image.pixels, fast_image_resize::PixelType::U8x3, )?; self.resizer.resize(&src_image, &mut dst_image, None)?; Ok(()) } } pub fn draw_boundary_boxes_on_encoded_image( data: Bytes, predictions: &[Prediction], base_width: u32, base_height: u32, ) -> anyhow::Result<Bytes> { let mut image = Image::default(); decode_jpeg(None, data, &mut image)?; let dynamic_image_with_boundary_box = create_dynamic_image_maybe_with_boundary_box( Some(predictions), &image, base_width, base_height, )?; let mut encoded_image = Vec::new(); let encoder = Encoder::new(&mut encoded_image, 100); encoder.encode( dynamic_image_with_boundary_box .as_rgb8() .ok_or_else(|| anyhow::anyhow!("Failed to convert image to RGB8"))?, dynamic_image_with_boundary_box.width() as u16, dynamic_image_with_boundary_box.height() as u16, ColorType::Rgb, )?; Ok(Bytes::from(encoded_image)) }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/detector.rs
src/detector.rs
#[cfg(windows)] use crate::direct_ml_available; use crate::{ api::Prediction, get_object_classes, image::{ Image, Resizer, create_od_image_name, decode_jpeg, encode_maybe_draw_boundary_boxes_and_save_jpeg, }, }; use anyhow::{anyhow, bail}; use bytes::Bytes; use ndarray::{Array, ArrayView, Axis, s}; #[cfg(windows)] use ort::execution_providers::DirectMLExecutionProvider; use ort::{ inputs, session::{Session, SessionInputs, SessionOutputs}, value::Value, }; use smallvec::SmallVec; use std::{ fmt::Debug, path::PathBuf, time::{Duration, Instant}, }; use tracing::{debug, info, warn}; pub struct DetectResult { pub predictions: SmallVec<[Prediction; 10]>, pub processing_time: std::time::Duration, pub decode_image_time: std::time::Duration, pub resize_image_time: std::time::Duration, pub pre_processing_time: std::time::Duration, pub inference_time: std::time::Duration, pub post_processing_time: std::time::Duration, pub device_type: DeviceType, pub endpoint_provider: EndpointProvider, } impl Debug for DetectResult { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("DetectResult") .field("# predictions", &self.predictions) .field("processing_time", &self.processing_time) .field("decode_image_time", &self.decode_image_time) .field("resize_image_time", &self.resize_image_time) .field("pre_processing_time", &self.pre_processing_time) .field("inference_time", &self.inference_time) .field("post_processing_time", &self.post_processing_time) .field("device_type", &self.device_type) .finish() } } pub struct Detector { session: Session, resizer: Resizer, decoded_image: Image, resized_image: Image, object_classes: Vec<String>, object_filter: Option<Vec<bool>>, input: ndarray::ArrayBase<ndarray::OwnedRepr<f32>, ndarray::Dim<[usize; 4]>>, confidence_threshold: f32, device_type: DeviceType, endpoint_provider: EndpointProvider, save_image_path: Option<PathBuf>, save_ref_image: bool, model_name: String, object_detection_model: ObjectDetectionModel, input_width: usize, input_height: usize, } #[derive(Debug, Clone)] pub struct OnnxConfig { pub intra_threads: usize, pub inter_threads: usize, pub gpu_index: i32, pub force_cpu: bool, pub model: Option<PathBuf>, } #[derive(Debug, Clone)] pub struct PostProcessParams<'a> { pub confidence_threshold: f32, pub resize_factor_x: f32, pub resize_factor_y: f32, pub object_filter: &'a Option<Vec<bool>>, pub object_classes: &'a [String], pub input_width: u32, pub input_height: u32, } #[derive( Debug, Clone, Default, PartialEq, clap::ValueEnum, serde::Serialize, serde::Deserialize, )] pub enum ObjectDetectionModel { RtDetrv2, #[default] RfDetr, Yolo5, } impl std::fmt::Display for ObjectDetectionModel { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ObjectDetectionModel::RtDetrv2 => write!(f, "rt-detrv2"), ObjectDetectionModel::RfDetr => write!(f, "rf-detr"), ObjectDetectionModel::Yolo5 => write!(f, "yolo5"), } } } impl ObjectDetectionModel { pub fn pre_process<'a>( &self, input: &'a mut Array<f32, ndarray::Dim<[usize; 4]>>, orig_size: &'a Array<i64, ndarray::Dim<[usize; 2]>>, ) -> anyhow::Result<SessionInputs<'a, 'a>> { match self { Self::RtDetrv2 => rt_detrv2_pre_process(input, orig_size), Self::RfDetr => rf_detr_pre_process(input, orig_size), Self::Yolo5 => yolo5_pre_process(input), } } pub fn post_process( &self, outputs: SessionOutputs<'_>, params: &PostProcessParams, ) -> anyhow::Result<SmallVec<[Prediction; 10]>> { match self { Self::RtDetrv2 => rt_detrv2_post_process( outputs, params.confidence_threshold, params.resize_factor_x, params.resize_factor_y, params.object_filter, params.object_classes, ), Self::RfDetr => rf_detr_post_process(outputs, params), Self::Yolo5 => yolo5_post_process( outputs, params.confidence_threshold, params.resize_factor_x, params.resize_factor_y, params.object_filter, params.object_classes, ), } } } fn rt_detrv2_pre_process<'a>( input: &'a mut Array<f32, ndarray::Dim<[usize; 4]>>, orig_size: &'a Array<i64, ndarray::Dim<[usize; 2]>>, ) -> anyhow::Result<SessionInputs<'a, 'a>> { Ok(inputs![ "images" => Value::from_array(input.clone())?, "orig_target_sizes" => Value::from_array(orig_size.clone())?, ] .into()) } fn rf_detr_pre_process<'a>( input: &'a mut Array<f32, ndarray::Dim<[usize; 4]>>, _orig_size: &'a Array<i64, ndarray::Dim<[usize; 2]>>, ) -> anyhow::Result<SessionInputs<'a, 'a>> { Ok(inputs![ "input" => Value::from_array(input.clone())?, ] .into()) } fn yolo5_pre_process<'a>( input: &'a mut Array<f32, ndarray::Dim<[usize; 4]>>, ) -> anyhow::Result<SessionInputs<'a, 'a>> { Ok(inputs![ "images" => Value::from_array(input.clone())?, ] .into()) } fn rt_detrv2_post_process( outputs: SessionOutputs<'_>, confidence_threshold: f32, resize_factor_x: f32, resize_factor_y: f32, object_filter: &Option<Vec<bool>>, object_classes: &[String], ) -> anyhow::Result<SmallVec<[Prediction; 10]>> { let (labels_shape, labels_data) = outputs["labels"].try_extract_tensor::<i64>()?; let (bboxes_shape, bboxes_data) = outputs["boxes"].try_extract_tensor::<f32>()?; let (scores_shape, scores_data) = outputs["scores"].try_extract_tensor::<f32>()?; // Convert shapes to ndarray dimensions let labels_dims: Vec<usize> = labels_shape.iter().map(|&dim| dim as usize).collect(); let labels = ArrayView::from_shape(labels_dims.as_slice(), labels_data) .map_err(|e| anyhow!("Failed to create labels array view: {}", e))?; let bboxes_dims: Vec<usize> = bboxes_shape.iter().map(|&dim| dim as usize).collect(); let bboxes = ArrayView::from_shape(bboxes_dims.as_slice(), bboxes_data) .map_err(|e| anyhow!("Failed to create bboxes array view: {}", e))?; let scores_dims: Vec<usize> = scores_shape.iter().map(|&dim| dim as usize).collect(); let scores = ArrayView::from_shape(scores_dims.as_slice(), scores_data) .map_err(|e| anyhow!("Failed to create scores array view: {}", e))?; // Get the first batch (assuming batch size is 1) let labels = labels.index_axis(Axis(0), 0); let bboxes = bboxes.index_axis(Axis(0), 0); let scores = scores.index_axis(Axis(0), 0); let mut predictions = SmallVec::<[Prediction; 10]>::new(); for (i, bbox) in bboxes.outer_iter().enumerate() { if scores[i] > confidence_threshold { // If object filter is set, skip objects that are not in the filter if let Some(object_filter) = object_filter.as_ref() && !object_filter[labels[i] as usize] { continue; } let prediction = Prediction { x_min: (bbox[0] * resize_factor_x) as usize, x_max: (bbox[2] * resize_factor_x) as usize, y_min: (bbox[1] * resize_factor_y) as usize, y_max: (bbox[3] * resize_factor_y) as usize, confidence: scores[i], label: object_classes[labels[i] as usize].clone(), }; debug!("Prediction - {}: {:?}", predictions.len() + 1, prediction); predictions.push(prediction); } } Ok(predictions) } fn rf_detr_post_process( outputs: SessionOutputs<'_>, params: &PostProcessParams, ) -> anyhow::Result<SmallVec<[Prediction; 10]>> { let (dets_shape, dets_data) = outputs["dets"].try_extract_tensor::<f32>()?; let (labels_shape, labels_data) = outputs["labels"].try_extract_tensor::<f32>()?; // Convert shapes to ndarray dimensions let dets_dims: Vec<usize> = dets_shape.iter().map(|&dim| dim as usize).collect(); let dets = ArrayView::from_shape(dets_dims.as_slice(), dets_data) .map_err(|e| anyhow!("Failed to create dets array view: {}", e))?; let labels_dims: Vec<usize> = labels_shape.iter().map(|&dim| dim as usize).collect(); let labels = ArrayView::from_shape(labels_dims.as_slice(), labels_data) .map_err(|e| anyhow!("Failed to create labels array view: {}", e))?; // Get the first batch (assuming batch size is 1) let dets = dets.index_axis(Axis(0), 0); // Shape: [num_queries, 4] - boxes in cxcywh format let labels = labels.index_axis(Axis(0), 0); // Shape: [num_queries, num_classes] - logits // Apply sigmoid and flatten to find top-k predictions across all queries and classes let num_queries = labels.shape()[0]; let num_classes = labels.shape()[1]; let total_predictions = num_queries * num_classes; // Apply sigmoid to convert logits to probabilities and collect all scores let mut all_scores = Vec::with_capacity(total_predictions); for query_idx in 0..num_queries { for class_idx in 0..num_classes { let logit = labels[[query_idx, class_idx]]; let prob = 1.0 / (1.0 + (-logit).exp()); // sigmoid all_scores.push((prob, query_idx, class_idx)); } } // Sort by score (descending) and take top predictions all_scores.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); let mut predictions = SmallVec::<[Prediction; 10]>::new(); // Process top predictions above confidence threshold for (score, query_idx, class_idx) in all_scores.iter().take(300) { if *score <= params.confidence_threshold { break; } // If object filter is set, skip objects that are not in the filter if let Some(object_filter) = params.object_filter.as_ref() && *class_idx < object_filter.len() && !object_filter[*class_idx] { continue; } // Extract bounding box coordinates in cxcywh format (normalized 0-1) let det = dets.index_axis(Axis(0), *query_idx); // RF-DETR outputs normalized coordinates (0-1), scale to original image dimensions let orig_img_width = params.resize_factor_x * params.input_width as f32; let orig_img_height = params.resize_factor_y * params.input_height as f32; let center_x = det[0] * orig_img_width; let center_y = det[1] * orig_img_height; let width = det[2] * orig_img_width; let height = det[3] * orig_img_height; // Convert from center_x, center_y, width, height to x_min, y_min, x_max, y_max let x_min = (center_x - width / 2.0).max(0.0); let x_max = center_x + width / 2.0; let y_min = (center_y - height / 2.0).max(0.0); let y_max = center_y + height / 2.0; let prediction = Prediction { x_min: x_min.round() as usize, x_max: x_max.round() as usize, y_min: y_min.round() as usize, y_max: y_max.round() as usize, confidence: *score, label: if *class_idx < params.object_classes.len() { params.object_classes[*class_idx].clone() } else { format!("class_{class_idx}") }, }; debug!( "RF-DETR Detection - {}: {:?}", predictions.len() + 1, prediction ); debug!( " Query {}, Class {}: {:.4} -> {:.4} (COCO ID {})", query_idx, class_idx, labels[[*query_idx, *class_idx]], score, class_idx ); debug!( " Raw bbox: center=({:.4}, {:.4}), size=({:.4}, {:.4})", det[0], det[1], det[2], det[3] ); debug!( " Model input: {}x{}, Original image: {:.0}x{:.0}", params.input_width, params.input_height, orig_img_width, orig_img_height ); debug!( " Scaled bbox: center=({:.2}, {:.2}), size=({:.2}, {:.2})", center_x, center_y, width, height ); debug!( " Float coords: ({:.2}, {:.2}) to ({:.2}, {:.2})", x_min, y_min, x_max, y_max ); debug!( " Final coords: ({}, {}) to ({}, {})", prediction.x_min, prediction.y_min, prediction.x_max, prediction.y_max ); predictions.push(prediction); } Ok(predictions) } fn yolo5_post_process( outputs: SessionOutputs<'_>, confidence_threshold: f32, resize_factor_x: f32, resize_factor_y: f32, object_filter: &Option<Vec<bool>>, object_classes: &[String], ) -> anyhow::Result<SmallVec<[Prediction; 10]>> { let output = outputs.values().next().ok_or(anyhow!("No outputs"))?; let (shape, data) = output.try_extract_tensor::<f32>()?; let shape_dims: Vec<usize> = shape.iter().map(|&dim| dim as usize).collect(); let yolo_output = ArrayView::from_shape(shape_dims.as_slice(), data) .map_err(|e| anyhow!("Failed to create output array view: {}", e))?; // Debug: Print the actual tensor shape debug!("YOLO output tensor shape: {:?}", yolo_output.shape()); debug!("Expected classes + 5: {}", 5 + object_classes.len()); // The YOLO5 output is typically [batch_size, num_detections, num_classes + 5] // So we need to check the last dimension, not the second dimension let expected_features = 5 + object_classes.len(); let actual_shape = yolo_output.shape(); if actual_shape.len() == 3 && actual_shape[2] == expected_features { // Shape is [batch_size, num_detections, features] - this is correct debug!( "Tensor shape is correct: [batch_size={}, num_detections={}, features={}]", actual_shape[0], actual_shape[1], actual_shape[2] ); } else if actual_shape.len() == 2 && actual_shape[1] == expected_features { // Shape is [num_detections, features] - also valid debug!( "Tensor shape is 2D: [num_detections={}, features={}]", actual_shape[0], actual_shape[1] ); } else { bail!( "Unexpected YOLO output shape: {:?}. Expected last dimension to be {} (5 + {} classes). This probably means that your classes YAML file does not match the model.", actual_shape, expected_features, object_classes.len() ); } let mut predictions = SmallVec::<[Prediction; 10]>::new(); // Handle different tensor shapes let detections_view = if yolo_output.shape().len() == 3 { // Shape is [batch_size, num_detections, features] - get the first batch yolo_output.index_axis(Axis(0), 0) } else { // Shape is [num_detections, features] - use directly yolo_output.view() }; for iter in detections_view.outer_iter() { if iter[4] > confidence_threshold { let class_idx = iter .slice(s![5..]) .iter() .enumerate() .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal)) .map(|(idx, _)| idx) .unwrap_or(0); if let Some(object_filter) = object_filter && !object_filter[class_idx] { continue; } let x_center = iter[0] * resize_factor_x; let y_center = iter[1] * resize_factor_y; let width = iter[2] * resize_factor_x; let height = iter[3] * resize_factor_y; let prediction = Prediction { x_min: (x_center - width / 2.0) as usize, y_min: (y_center - height / 2.0) as usize, x_max: (x_center + width / 2.0) as usize, y_max: (y_center + height / 2.0) as usize, confidence: iter[4], label: object_classes[class_idx].clone(), }; predictions.push(prediction); } } // Apply non-maximum suppression (aka remove overlapping boxes) let predictions = non_maximum_suppression(predictions, 0.5)?; for (i, prediction) in predictions.iter().enumerate() { debug!("Prediction - {}: {:?}", i + 1, prediction); } Ok(predictions) } fn non_maximum_suppression( mut predictions: SmallVec<[Prediction; 10]>, iou_threshold: f32, ) -> anyhow::Result<SmallVec<[Prediction; 10]>> { let mut filtered_predictions = SmallVec::new(); predictions.sort_by(|a, b| { a.label.cmp(&b.label).then( b.confidence .partial_cmp(&a.confidence) .unwrap_or(std::cmp::Ordering::Equal), ) }); let mut current_class = None; let mut kept: SmallVec<[Prediction; 10]> = SmallVec::new(); for pred in predictions.iter() { if Some(&pred.label) != current_class { for kept_pred in kept.iter() { filtered_predictions.push(kept_pred.clone()); } kept.clear(); current_class = Some(&pred.label); } let mut should_keep = true; for kept_pred in kept.iter() { if calculate_iou(pred, kept_pred) >= iou_threshold { should_keep = false; break; } } if should_keep { kept.push(pred.clone()); } } for kept_pred in kept.iter() { filtered_predictions.push(kept_pred.clone()); } Ok(filtered_predictions) } fn calculate_iou(a: &Prediction, b: &Prediction) -> f32 { let x_min = a.x_min.max(b.x_min) as f32; let y_min = a.y_min.max(b.y_min) as f32; let x_max = a.x_max.min(b.x_max) as f32; let y_max = a.y_max.min(b.y_max) as f32; let intersection = (x_max - x_min).max(0.0) * (y_max - y_min).max(0.0); let area_a = (a.x_max - a.x_min) as f32 * (a.y_max - a.y_min) as f32; let area_b = (b.x_max - b.x_min) as f32 * (b.y_max - b.y_min) as f32; let union = area_a + area_b - intersection; if union == 0.0 { 0.0 } else { intersection / union } } fn query_image_input_size(session: &Session) -> anyhow::Result<(usize, usize)> { let inputs = &session.inputs; info!("Model inputs:"); for (i, input) in inputs.iter().enumerate() { info!( " Input {}: name='{}', type={:?}", i, input.name, input.input_type ); } // Try to extract dimensions from the input type information for input in inputs.iter() { // Look for image input (typically named "input" or "images") if input.name == "input" || input.name == "images" { // Parse the input type string to extract dimensions let type_str = format!("{:?}", input.input_type); // Look for shape pattern like "shape: [1, 3, 384, 384]" if let Some(shape_start) = type_str.find("shape: [") { let shape_part = &type_str[shape_start + 8..]; if let Some(shape_end) = shape_part.find(']') { let shape_str = &shape_part[..shape_end]; let dims: Vec<&str> = shape_str.split(',').map(|s| s.trim()).collect(); // Expect format [batch_size, channels, height, width] if dims.len() == 4 && let (Ok(height), Ok(width)) = (dims[2].parse::<usize>(), dims[3].parse::<usize>()) { info!( "Extracted input size from model '{}': {}x{}", input.name, width, height ); return Ok((width, height)); } } } // Fallback: use heuristic based on input name if input.name == "input" { info!("Could not parse dimensions, using RF-DETR default: 384x384"); return Ok((384, 384)); } else if input.name == "images" { info!("Could not parse dimensions, using RT-DETR/YOLO default: 640x640"); return Ok((640, 640)); } } } // Fallback to 640x640 if we can't detect the size warn!("Could not detect input size from model, falling back to 640x640"); Ok((640, 640)) } #[derive(Debug, Clone)] pub struct DetectorConfig { pub object_classes: Option<PathBuf>, pub object_filter: Vec<String>, pub confidence_threshold: f32, pub save_image_path: Option<PathBuf>, pub save_ref_image: bool, pub timeout: Duration, pub object_detection_onnx_config: OnnxConfig, pub object_detection_model: ObjectDetectionModel, } impl Detector { pub fn new(detector_config: DetectorConfig) -> anyhow::Result<Self> { let (device_type, model_name, session, endpoint_provider, model_yaml_path, (width, height)) = initialize_onnx(&detector_config.object_detection_onnx_config)?; // Prioritize the YAML file that comes with the model over the configured one let yaml_path_to_use = model_yaml_path.or(detector_config.object_classes); let object_classes = if let Some(yaml_path) = &yaml_path_to_use { info!("Using object classes from model YAML: {:?}", yaml_path); get_object_classes(Some(yaml_path.clone()))? } else { bail!( "No YAML file found with model. A YAML file containing object classes is required for the model." ); }; let mut object_filter = None; if !detector_config.object_filter.is_empty() { let mut object_filter_vector = vec![false; object_classes.len()]; for object in detector_config.object_filter.iter() { if let Some(index) = object_classes .iter() .position(|x| x.to_lowercase() == object.to_lowercase()) { object_filter_vector[index] = true; } } object_filter = Some(object_filter_vector); } let mut detector = Self { model_name, endpoint_provider, session, resizer: Resizer::new(width, height)?, decoded_image: Image::default(), resized_image: Image::default(), input: Array::zeros((1, 3, height, width)), object_classes, object_filter, confidence_threshold: detector_config.confidence_threshold, device_type, save_image_path: detector_config.save_image_path, save_ref_image: detector_config.save_ref_image, object_detection_model: detector_config.object_detection_model, input_width: width, input_height: height, }; // Warmup info!("Warming up the detector"); let detector_warmup_start_time = Instant::now(); detector.detect(Bytes::from(crate::DOG_BIKE_CAR_BYTES), None, None)?; info!( "Detector warmed up in: {:?}", detector_warmup_start_time.elapsed() ); Ok(detector) } pub fn detect( &mut self, image_bytes: Bytes, image_name: Option<String>, min_confidence: Option<f32>, ) -> anyhow::Result<DetectResult> { // Save the image if save_ref_image is set if let Some(ref image_name_str) = image_name { debug!("Detecting objects in image: {}", image_name_str); if let Some(ref save_image_path) = self.save_image_path && self.save_ref_image { let save_image_path = save_image_path.to_path_buf(); let image_path_buf = PathBuf::from(image_name_str); let image_name_ref = image_path_buf .file_name() .ok_or_else(|| anyhow::anyhow!("Failed to get file name from path"))?; let save_image_path = save_image_path.join(image_name_ref); std::fs::write(save_image_path, &image_bytes)?; } } // Process from here let processing_time_start = Instant::now(); decode_jpeg(image_name.clone(), image_bytes, &mut self.decoded_image)?; let decode_image_time = processing_time_start.elapsed(); debug!( "Decode image time: {:?}, resolution {}x{}", decode_image_time, self.decoded_image.width, self.decoded_image.height ); let resize_factor_x = self.decoded_image.width as f32 / self.input_width as f32; let resize_factor_y = self.decoded_image.height as f32 / self.input_height as f32; debug!( "Image resize factors: width_factor={:.3} ({}->{}), height_factor={:.3} ({}->{})", resize_factor_x, self.input_width, self.decoded_image.width, resize_factor_y, self.input_height, self.decoded_image.height ); let orig_size = Array::from_shape_vec( (1, 2), vec![self.input_height as i64, self.input_width as i64], )?; let resize_image_start_time = Instant::now(); self.resizer .resize_image(&mut self.decoded_image, &mut self.resized_image)?; let resize_image_time = resize_image_start_time.elapsed(); debug!("Resize image time: {:#?}", resize_image_time); // Ensure resized image dimensions match input tensor dimensions if self.resized_image.width != self.input_width || self.resized_image.height != self.input_height { bail!( "Resized image dimensions ({}x{}) don't match input tensor dimensions ({}x{})", self.resized_image.width, self.resized_image.height, self.input_width, self.input_height ); } debug!( "Resized image dimensions: {}x{}, Input tensor dimensions: {}x{}", self.resized_image.width, self.resized_image.height, self.input_width, self.input_height ); let copy_pixels_to_input_start = Instant::now(); let expected_pixels = self.input_width * self.input_height; let actual_pixels = self.resized_image.pixels.len() / 3; // RGB channels debug!( "Expected pixels: {}, Actual pixels: {}", expected_pixels, actual_pixels ); debug!( "Input tensor shape: [1, 3, {}, {}]", self.input_height, self.input_width ); if actual_pixels != expected_pixels { bail!( "Pixel count mismatch: expected {} pixels but got {} pixels", expected_pixels, actual_pixels ); } for (index, chunk) in self.resized_image.pixels.chunks_exact(3).enumerate() { let y = index / self.input_width; let x = index % self.input_width; // Check bounds before accessing if y >= self.input_height || x >= self.input_width { bail!( "Index out of bounds: trying to access ({}, {}) but tensor is {}x{}", x, y, self.input_width, self.input_height ); } self.input[[0, 0, y, x]] = chunk[0] as f32 / 255.0; self.input[[0, 1, y, x]] = chunk[1] as f32 / 255.0; self.input[[0, 2, y, x]] = chunk[2] as f32 / 255.0; } debug!( "Copy pixels to input time: {:?}", copy_pixels_to_input_start.elapsed() ); let pre_process_model_input_start = Instant::now(); let session_inputs = self .object_detection_model .pre_process(&mut self.input, &orig_size)?; debug!( "Pre-process model input time: {:?}", pre_process_model_input_start.elapsed() ); let pre_processing_time = processing_time_start.elapsed(); debug!("Pre-process time: {:?}", pre_processing_time); let start_inference_time = std::time::Instant::now(); let outputs: SessionOutputs = self.session.run(session_inputs)?; let inference_time = start_inference_time.elapsed(); debug!("Inference time: {:?}", inference_time); let post_processing_time_start = Instant::now(); let confidence_threshold = min_confidence.unwrap_or(self.confidence_threshold); let params = PostProcessParams { confidence_threshold, resize_factor_x, resize_factor_y, object_filter: &self.object_filter, object_classes: &self.object_classes, input_width: self.input_width as u32, input_height: self.input_height as u32, }; let predictions = self.object_detection_model.post_process(outputs, &params)?; let now = Instant::now(); let post_processing_time = now.duration_since(post_processing_time_start); debug!("Post-processing time: {:?}", post_processing_time); let processing_time = now.duration_since(processing_time_start); // Processing time is mainly composed of: // 1. Image decoding time // 2. Image resizing time // 3. Inference time debug!("Processing time: {:?}", processing_time); if let Some(ref image_name) = image_name && let Some(ref save_image_path) = self.save_image_path { info!( "Saving detection result with {} predictions to disk", predictions.len() ); let save_image_start_time = Instant::now(); let save_image_path = save_image_path.to_path_buf(); let image_name_od = create_od_image_name(image_name, true)?; let output_path = save_image_path .join(&image_name_od) .to_string_lossy() .to_string(); info!("Output path: {}", output_path); encode_maybe_draw_boundary_boxes_and_save_jpeg( &self.decoded_image, &output_path, Some(predictions.as_slice()), self.input_width as u32, self.input_height as u32, )?; debug!("Save image time: {:?}", save_image_start_time.elapsed()); } else { if image_name.is_none() { debug!("No image name provided, skipping image save"); } if self.save_image_path.is_none() { debug!("No save path configured, skipping image save"); } } Ok(DetectResult { predictions, processing_time, decode_image_time, resize_image_time, pre_processing_time, inference_time, post_processing_time, device_type: self.device_type, endpoint_provider: self.endpoint_provider, }) } pub fn get_min_processing_time(&mut self) -> anyhow::Result<Duration> { const TUNE_RUNS: usize = 10; info!("Running detector {TUNE_RUNS} times to get min processing time"); let mut min_processing_time = Duration::MAX; for _ in 0..TUNE_RUNS { let detector_warmup_start_time = Instant::now(); self.detect(Bytes::from(crate::DOG_BIKE_CAR_BYTES), None, None)?; let processing_time = detector_warmup_start_time.elapsed(); min_processing_time = min_processing_time.min(processing_time); } info!( ?min_processing_time, "Done running detector {TUNE_RUNS} times" ); Ok(min_processing_time) } pub fn get_model_name(&self) -> &String { &self.model_name } pub fn get_endpoint_provider_name(&self) -> String { self.endpoint_provider.to_string() } pub fn is_using_gpu(&self) -> bool { self.device_type == DeviceType::GPU } pub fn get_input_size(&self) -> (usize, usize) {
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
true
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/cli.rs
src/cli.rs
use crate::{LogLevel, detector::ObjectDetectionModel, download_models::Model, init_logging}; use clap::Parser; use serde::{Deserialize, Serialize}; use std::{path::PathBuf, time::Duration}; #[derive(Parser, Serialize, Deserialize, Clone)] #[command(author = "Marcus Asteborg", version=env!("CARGO_PKG_VERSION"), about = "TODO")] #[serde(default)] pub struct Cli { /// Path to configuration file (JSON format) #[arg(long)] #[serde(skip)] pub config: Option<PathBuf>, /// The port on which the server will listen for HTTP requests. /// Default is 32168. Example usage: --port 1337 #[arg(long, default_value_t = 32168)] pub port: u16, /// Duration to wait for a response from the detection worker. /// Ideally, this should be similar to the client's timeout setting. #[arg(long, default_value = "15", value_parser = parse_duration)] #[serde(with = "duration_serde")] pub request_timeout: Duration, /// Worker queue size. /// The number of requests that can be queued before the server starts rejecting them. /// If not set, the server will estimate the queue size based on the timeout and the /// inference performance. /// This estimation is based on the timeout and the expected number of requests per second. #[arg(long)] pub worker_queue_size: Option<usize>, /// Path to the ONNX model file. /// If not specified, the default rt-detrv2 small model will be used /// provided it is available in the directory. #[clap(long)] pub model: Option<PathBuf>, /// Type of model type to use. /// Default: rt-detrv2 #[clap(long, default_value_t = ObjectDetectionModel::RfDetr)] pub object_detection_model_type: ObjectDetectionModel, /// Path to the object classes yaml file /// Default: coco_classes.yaml which is the 80 standard COCO classes #[clap(long)] pub object_classes: Option<PathBuf>, /// Filters the results to include only the specified labels. Provide labels separated by ','. /// Example: --object_filter "person,cup" #[arg(long, value_delimiter = ',', num_args = 1..)] pub object_filter: Vec<String>, /// Sets the level of logging #[clap(long, value_enum, default_value_t = LogLevel::Info)] pub log_level: LogLevel, /// If log_path is set, then stdout logging will be disabled and it will log to file #[clap(long)] pub log_path: Option<PathBuf>, /// Confidence threshold for object detection #[clap(long, default_value_t = 0.5)] pub confidence_threshold: f32, /// Force using CPU for inference #[clap(long, default_value_t = false)] pub force_cpu: bool, /// Intra thread parallelism max is CPU cores - 1. /// On Windows, you can use high thread counts, but if you use too high /// thread count on Linux, you will get a BIG performance hit. /// So default is 1, then you can increase it if you want to test the /// performance. #[cfg(target_os = "windows")] #[clap(long, default_value_t = 16)] pub intra_threads: usize, #[cfg(not(target_os = "windows"))] #[clap(long, default_value_t = 2)] pub intra_threads: usize, /// Inter thread parallelism max is CPU cores - 1. /// On Windows, you can use high thread counts, but if you use too high /// thread count on Linux, you will get a BIG performance hit. /// So default is 2, then you can increase it if you want to test the /// performance. #[cfg(target_os = "windows")] #[clap(long, default_value_t = 16)] pub inter_threads: usize, #[cfg(not(target_os = "windows"))] #[clap(long, default_value_t = 2)] pub inter_threads: usize, /// Optional path to save the processed images #[clap(long)] pub save_image_path: Option<PathBuf>, /// Save the reference image (only if save_image_path is provided) #[clap(long, default_value_t = false)] pub save_ref_image: bool, /// GPU Index, best effort to select the correct one if multiple GPUs exist. /// Default is 0. The list and actual GPU index might differ. /// If the wrong GPU is selected, try changing this value. /// Verify through GPU usage to ensure the correct GPU is selected. #[clap(long, default_value_t = 0)] pub gpu_index: i32, /// Save inference stats to file #[clap(long)] pub save_stats_path: Option<PathBuf>, /// Path to download all models to /// This command will download models to the specified path and then exit. /// Use --download-rt-detr2 or --download-yolo5 to download specific model types, /// otherwise all models will be downloaded. #[clap(long)] #[serde(skip)] pub download_model_path: Option<PathBuf>, /// Download only RT-DETR v2 models (use with --download-model-path) /// RT-DETR v2 models include: rt-detrv2-s, rt-detrv2-ms, rt-detrv2-m, rt-detrv2-l, rt-detrv2-x #[clap(long)] #[serde(skip)] pub download_rt_detr2: bool, /// Download only YOLO5 models (use with --download-model-path) /// YOLO5 models include specialized models for delivery, animals, birds, etc. #[clap(long)] #[serde(skip)] pub download_yolo5: bool, /// Download all models of all types (use with --download-model-path) /// This will download both RT-DETR v2 and YOLO5 models #[clap(long)] #[serde(skip)] pub download_all_models: bool, /// List all available models that can be downloaded #[clap(long)] #[serde(skip)] pub list_models: bool, } impl Default for Cli { fn default() -> Self { Self { config: None, port: 32168, request_timeout: Duration::from_secs(15), worker_queue_size: None, model: None, object_detection_model_type: ObjectDetectionModel::default(), object_classes: None, object_filter: vec![], log_level: LogLevel::Info, log_path: None, confidence_threshold: 0.5, force_cpu: false, #[cfg(target_os = "windows")] intra_threads: 16, #[cfg(not(target_os = "windows"))] intra_threads: 2, #[cfg(target_os = "windows")] inter_threads: 16, #[cfg(not(target_os = "windows"))] inter_threads: 2, save_image_path: None, save_ref_image: false, gpu_index: 0, save_stats_path: None, download_model_path: None, download_rt_detr2: false, download_yolo5: false, download_all_models: false, list_models: false, } } } impl Cli { /// Create a new Cli from a combination of config file and command line arguments /// CLI arguments always override config file values pub fn from_config_and_args() -> anyhow::Result<Option<Self>> { // First parse CLI to get the config file path and all CLI arguments let mut args = Self::parse(); if args.list_models { let _guard = init_logging(args.log_level, &mut args.log_path)?; crate::download_models::list_models(); return Ok(None); } // Check if any download flags are set if args.download_all_models || args.download_rt_detr2 || args.download_yolo5 { let _guard = init_logging(args.log_level, &mut args.log_path)?; // Use specified path or default to current directory let download_path = args.download_model_path.unwrap_or_else(|| { if let Ok(exe) = std::env::current_exe() && let Some(parent) = exe.parent() { parent.to_path_buf() } else { std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")) } }); // Determine what to download based on flags let model_type = match ( args.download_all_models, args.download_rt_detr2, args.download_yolo5, ) { (true, _, _) => Model::All, (false, true, true) => Model::All, (false, true, false) => Model::AllRtDetr2, (false, false, true) => Model::AllYolo5, (false, false, false) => unreachable!("No download flags set"), }; // Create async runtime for download operation let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; rt.block_on(async { crate::download_models::download_model(download_path, model_type).await })?; return Ok(None); } // Run the tokio runtime on the main thread if let Some(config_path) = args.config.clone() { let config_file = Self::load_config(&config_path)?; Ok(Some(Self::merge_config_with_cli_args( config_file, args, config_path, ))) } else { // No config file specified, check if default config exists let default_config_path = Self::get_default_config_path()?; if default_config_path.exists() { // Load existing default config file and merge with CLI args tracing::info!( "Loading existing config file and merging with CLI arguments: {}", default_config_path.display() ); let config_file = Self::load_config(&default_config_path)?; Ok(Some(Self::merge_config_with_cli_args( config_file, args, default_config_path, ))) } else { // Create new config file from CLI arguments args.save_config(&default_config_path)?; tracing::info!( "Created config file from CLI arguments: {}", default_config_path.display() ); // Now load it back with the config path set let mut config = args; config.config = Some(default_config_path); Ok(Some(config)) } } } /// Create a Cli from provided arguments with config file support /// CLI arguments always override config file values pub fn from_args_with_config(args: Vec<std::ffi::OsString>) -> anyhow::Result<Self> { let cli_args = Self::try_parse_from(args)?; if let Some(config_path) = cli_args.config.clone() { // If config file is specified, load it and merge with CLI args let config_file = Self::load_config(&config_path)?; Ok(Self::merge_config_with_cli_args( config_file, cli_args, config_path, )) } else { // No config file specified, check if default config exists let default_config_path = Self::get_default_config_path()?; if default_config_path.exists() { // Load existing default config file and merge with CLI args tracing::info!( "Loading existing config file and merging with CLI arguments: {}", default_config_path.display() ); let config_file = Self::load_config(&default_config_path)?; Ok(Self::merge_config_with_cli_args( config_file, cli_args, default_config_path, )) } else { // Create new config file from CLI arguments cli_args.save_config(&default_config_path)?; tracing::info!( "Created config file from CLI arguments: {}", default_config_path.display() ); // Now load it back with the config path set let mut config = cli_args; config.config = Some(default_config_path); Ok(config) } } } /// Load configuration from a JSON file pub fn load_config(path: &PathBuf) -> anyhow::Result<Self> { let content = std::fs::read_to_string(path) .map_err(|e| anyhow::anyhow!("Failed to read config file {}: {}", path.display(), e))?; let config: Self = serde_json::from_str(&content).map_err(|e| { anyhow::anyhow!("Failed to parse config file {}: {}", path.display(), e) })?; Ok(config) } /// Save current configuration to a JSON file pub fn save_config(&self, path: &PathBuf) -> anyhow::Result<()> { let content = serde_json::to_string_pretty(self) .map_err(|e| anyhow::anyhow!("Failed to serialize config: {}", e))?; std::fs::write(path, content).map_err(|e| { anyhow::anyhow!("Failed to write config file {}: {}", path.display(), e) })?; Ok(()) } /// Get the default config file path next to the executable pub fn get_default_config_path() -> anyhow::Result<PathBuf> { let exe_path = std::env::current_exe() .map_err(|e| anyhow::anyhow!("Failed to get executable path: {}", e))?; let exe_dir = exe_path .parent() .ok_or_else(|| anyhow::anyhow!("Failed to get executable directory"))?; Ok(exe_dir.join("blue_onyx_config.json")) } /// Get the current config file path (either specified or default) pub fn get_current_config_path(&self) -> anyhow::Result<PathBuf> { if let Some(config_path) = &self.config { Ok(config_path.clone()) } else { Self::get_default_config_path() } } /// Auto-save current configuration if no config file was used pub fn auto_save_if_no_config(&self) -> anyhow::Result<()> { // Only auto-save if no config file was specified if self.config.is_none() { let config_path = Self::get_default_config_path()?; // Don't overwrite if the file already exists (user might have customized it) if !config_path.exists() { self.save_config(&config_path)?; tracing::info!("Saved current configuration to: {}", config_path.display()); } } Ok(()) } /// Load configuration for service - uses blue_onyx_config_service.json /// Creates default config if file doesn't exist pub fn for_service() -> anyhow::Result<Self> { let exe_dir = std::env::current_exe()? .parent() .ok_or_else(|| anyhow::anyhow!("Could not determine executable directory"))? .to_path_buf(); let config_path = exe_dir.join("blue_onyx_config_service.json"); if config_path.exists() { let mut config = Self::load_config(&config_path)?; config.config = Some(config_path); Ok(config) } else { // Create default config for service with Debug log level let default_config = Self { log_level: LogLevel::Debug, ..Default::default() }; default_config.save_config(&config_path)?; tracing::info!( "Created default service config at: {}", config_path.display() ); let mut config = default_config; config.config = Some(config_path); Ok(config) } } /// Print the current configuration in a human-readable format pub fn print_config(&self) { tracing::info!("=== Blue Onyx Configuration ==="); tracing::info!("Server Configuration:"); tracing::info!(" Port: {}", self.port); tracing::info!( " Request timeout: {} seconds", self.request_timeout.as_secs() ); if let Some(queue_size) = self.worker_queue_size { tracing::info!(" Worker queue size: {}", queue_size); } else { tracing::info!(" Worker queue size: auto-determined"); } tracing::info!("Model Configuration:"); tracing::info!( " Detection model type: {}", self.object_detection_model_type ); if let Some(model_path) = &self.model { tracing::info!(" Custom model path: {}", model_path.display()); } else { tracing::info!(" Model: default (rf-detr-n.onnx)"); } if let Some(classes_path) = &self.object_classes { tracing::info!(" Object classes: {}", classes_path.display()); } else { tracing::info!(" Object classes: default (coco_classes.yaml)"); } tracing::info!("Detection Configuration:"); tracing::info!(" Confidence threshold: {:.2}", self.confidence_threshold); if !self.object_filter.is_empty() { tracing::info!(" Object filter: [{}]", self.object_filter.join(", ")); } else { tracing::info!(" Object filter: none (all objects)"); } tracing::info!("Performance Configuration:"); tracing::info!(" Force CPU: {}", if self.force_cpu { "yes" } else { "no" }); tracing::info!(" GPU index: {}", self.gpu_index); tracing::info!(" Intra threads: {}", self.intra_threads); tracing::info!(" Inter threads: {}", self.inter_threads); tracing::info!("Logging Configuration:"); tracing::info!(" Log level: {:?}", self.log_level); if let Some(log_path) = &self.log_path { tracing::info!(" Log path: {}", log_path.display()); } else { tracing::info!(" Log path: stdout"); } tracing::info!("Output Configuration:"); if let Some(save_path) = &self.save_image_path { tracing::info!(" Save processed images: {}", save_path.display()); tracing::info!( " Save reference images: {}", if self.save_ref_image { "yes" } else { "no" } ); } else { tracing::info!(" Save processed images: disabled"); } if let Some(stats_path) = &self.save_stats_path { tracing::info!(" Save statistics: {}", stats_path.display()); } else { tracing::info!(" Save statistics: disabled"); } if let Some(download_path) = &self.download_model_path { tracing::info!(" Download models to: {}", download_path.display()); } tracing::info!("=== Configuration Complete ==="); } /// Merge config file values with CLI arguments, where CLI arguments take precedence /// CLI arguments override config file values when they are explicitly provided fn merge_config_with_cli_args( mut config_file: Self, cli_args: Self, config_path: PathBuf, ) -> Self { // Use clap's built-in logic to determine which values were explicitly set // We'll create default CLI args and compare with the parsed CLI args let defaults = Self::default(); // Override config file values with CLI arguments when they differ from defaults // This approach assumes that if a CLI arg differs from its default, it was explicitly set if cli_args.port != defaults.port { config_file.port = cli_args.port; } if cli_args.request_timeout != defaults.request_timeout { config_file.request_timeout = cli_args.request_timeout; } if cli_args.worker_queue_size != defaults.worker_queue_size { config_file.worker_queue_size = cli_args.worker_queue_size; } if cli_args.model != defaults.model { config_file.model = cli_args.model; } if cli_args.object_detection_model_type != defaults.object_detection_model_type { config_file.object_detection_model_type = cli_args.object_detection_model_type; } if cli_args.object_classes != defaults.object_classes { config_file.object_classes = cli_args.object_classes; } if cli_args.object_filter != defaults.object_filter { config_file.object_filter = cli_args.object_filter; } if cli_args.log_level != defaults.log_level { config_file.log_level = cli_args.log_level; } if cli_args.log_path != defaults.log_path { config_file.log_path = cli_args.log_path; } if cli_args.confidence_threshold != defaults.confidence_threshold { config_file.confidence_threshold = cli_args.confidence_threshold; } if cli_args.save_image_path != defaults.save_image_path { config_file.save_image_path = cli_args.save_image_path; } if cli_args.save_ref_image != defaults.save_ref_image { config_file.save_ref_image = cli_args.save_ref_image; } if cli_args.save_stats_path != defaults.save_stats_path { config_file.save_stats_path = cli_args.save_stats_path; } if cli_args.force_cpu != defaults.force_cpu { config_file.force_cpu = cli_args.force_cpu; } if cli_args.gpu_index != defaults.gpu_index { config_file.gpu_index = cli_args.gpu_index; } if cli_args.intra_threads != defaults.intra_threads { config_file.intra_threads = cli_args.intra_threads; } if cli_args.inter_threads != defaults.inter_threads { config_file.inter_threads = cli_args.inter_threads; } // Set the config path config_file.config = Some(config_path.clone()); // Save the merged configuration back to the config file if let Err(e) = config_file.save_config(&config_path) { tracing::warn!("Failed to save merged configuration: {}", e); } else { tracing::info!("Saved merged configuration to: {}", config_path.display()); } config_file } } // Custom serde functions for Duration mod duration_serde { use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::time::Duration; pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { duration.as_secs().serialize(serializer) } pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error> where D: Deserializer<'de>, { let secs = u64::deserialize(deserializer)?; Ok(Duration::from_secs(secs)) } } fn parse_duration(s: &str) -> anyhow::Result<Duration> { let secs: u64 = s.parse()?; Ok(Duration::from_secs(secs)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_default_thread_values_are_capped() { let cli = Cli::default(); // Test that default values are reasonable #[cfg(target_os = "windows")] { assert_eq!( cli.intra_threads, 16, "Windows intra_threads default should be 16" ); assert_eq!( cli.inter_threads, 16, "Windows inter_threads default should be 16" ); } #[cfg(not(target_os = "windows"))] { assert_eq!( cli.intra_threads, 2, "Non-Windows intra_threads default should be 2" ); assert_eq!( cli.inter_threads, 2, "Non-Windows inter_threads default should be 2" ); } // Ensure values are within reasonable bounds assert!( cli.intra_threads <= 16, "intra_threads should not exceed 16" ); assert!( cli.inter_threads <= 16, "inter_threads should not exceed 16" ); } }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/api.rs
src/api.rs
use anyhow::{Context, anyhow}; use axum::body::Bytes; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; use std::fmt::Debug; #[derive(Default)] pub struct VisionDetectionRequest { pub min_confidence: f32, pub image_data: Bytes, pub image_name: String, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Default, Debug)] #[serde(rename_all = "camelCase", default)] pub struct VisionDetectionResponse { /// True if successful. pub success: bool, /// A summary of the inference operation. pub message: String, /// An description of the error if success was false. pub error: Option<String>, /// An array of objects with the x_max, x_min, max, y_min, label and confidence. pub predictions: Vec<Prediction>, /// The number of objects found. pub count: i32, /// The command that was sent as part of this request. Can be detect, list, status. pub command: String, /// The Id of the module that processed this request. pub moduleId: String, /// The name of the device or package handling the inference. eg CPU, GPU pub executionProvider: String, /// True if this module can use the current GPU if one is present. pub canUseGPU: bool, // The time (ms) to perform the AI inference. pub inferenceMs: i32, // The time (ms) to process the image (includes inference and image manipulation operations). pub processMs: i32, // The time (ms) for the round trip to the analysis module and back. pub analysisRoundTripMs: i32, } #[derive(Serialize, Deserialize, Clone, PartialEq)] pub struct Prediction { pub x_max: usize, pub x_min: usize, pub y_max: usize, pub y_min: usize, pub confidence: f32, pub label: String, } impl Debug for Prediction { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Prediction") .field("label", &self.label) .field("confidence", &self.confidence) .finish() } } #[allow(non_snake_case)] #[derive(Serialize, Default, Debug)] #[serde(rename_all = "camelCase")] pub struct VisionCustomListResponse { pub success: bool, pub models: Vec<String>, pub moduleId: String, pub moduleName: String, pub command: String, pub statusData: Option<String>, pub inferenceDevice: String, pub analysisRoundTripMs: i32, pub processedBy: String, pub timestampUTC: String, } #[allow(non_snake_case)] #[derive(Serialize, Default, Debug)] #[serde(rename_all = "camelCase")] pub struct StatusUpdateResponse { pub success: bool, pub message: String, pub version: Option<VersionInfo>, // Deprecated field pub current: VersionInfo, pub latest: VersionInfo, pub updateAvailable: bool, } #[allow(non_snake_case)] #[derive(Serialize, Default, Debug)] #[serde(rename_all = "camelCase")] pub struct VersionInfo { pub major: u8, pub minor: u8, pub patch: u8, pub preRelease: Option<String>, pub securityUpdate: bool, pub build: u32, pub file: String, pub releaseNotes: String, } impl VersionInfo { pub fn parse(version_str: &str, release_notes: Option<String>) -> anyhow::Result<Self> { let parts: Vec<_> = version_str.trim().split('.').collect(); let major: u8 = parts .first() .ok_or_else(|| anyhow!("Missing major version segment"))? .parse() .context("Failed to parse major version")?; let minor: u8 = parts .get(1) .ok_or_else(|| anyhow!("Missing minor version segment"))? .parse() .context("Failed to parse minor version")?; let patch: u8 = parts .get(2) .ok_or_else(|| anyhow!("Missing patch version segment"))? .parse() .context("Failed to parse patch version")?; Ok(Self { major, minor, patch, releaseNotes: release_notes.unwrap_or_default(), ..Default::default() }) } } impl PartialEq for VersionInfo { fn eq(&self, other: &Self) -> bool { self.major == other.major && self.minor == other.minor && self.patch == other.patch } } impl Eq for VersionInfo {} impl PartialOrd for VersionInfo { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for VersionInfo { fn cmp(&self, other: &Self) -> Ordering { match self.major.cmp(&other.major) { Ordering::Equal => match self.minor.cmp(&other.minor) { Ordering::Equal => self.patch.cmp(&other.patch), other_order => other_order, }, other_order => other_order, } } } #[cfg(test)] mod tests { use super::VersionInfo; use std::cmp::Ordering; #[test] fn test_eq_and_ne() { let v1 = VersionInfo { major: 1, minor: 2, patch: 3, ..Default::default() }; let v2 = VersionInfo { major: 1, minor: 2, patch: 3, ..Default::default() }; let v3 = VersionInfo { major: 1, minor: 3, patch: 3, ..Default::default() }; assert_eq!(v1, v2); assert_ne!(v1, v3); assert!(v3 > v2); assert!(v2 <= v1); } #[test] fn test_partial_ord_and_ord() { let v1 = VersionInfo { major: 1, minor: 2, patch: 3, ..Default::default() }; let v2 = VersionInfo { major: 1, minor: 2, patch: 4, ..Default::default() }; let v3 = VersionInfo { major: 2, minor: 0, patch: 0, ..Default::default() }; // Check ordering with v1 and v2 assert_eq!(v1.cmp(&v2), Ordering::Less); assert!(v1 < v2); // Check ordering with v3 and v2 assert_eq!(v3.cmp(&v2), Ordering::Greater); assert!(v3 > v2); } }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/worker.rs
src/worker.rs
use crate::{ api::{VisionDetectionRequest, VisionDetectionResponse}, detector::{Detector, DetectorConfig, DeviceType}, image::create_random_jpeg_name, }; use crossbeam::channel::{Receiver, Sender}; use std::time::{Duration, Instant}; use tokio::sync::oneshot; use tracing::{debug, info, warn}; pub struct DetectorWorker { receiver: Receiver<( VisionDetectionRequest, oneshot::Sender<VisionDetectionResponse>, Instant, )>, detector: Detector, request_timeout: Duration, } #[allow(clippy::type_complexity)] impl DetectorWorker { pub fn new( detector_config: DetectorConfig, worker_queue_size: Option<usize>, ) -> anyhow::Result<( Sender<( VisionDetectionRequest, oneshot::Sender<VisionDetectionResponse>, Instant, )>, Self, )> { let request_timeout = detector_config.timeout; let mut detector = Detector::new(detector_config)?; let worker_queue_size = match worker_queue_size { Some(size) => { info!(?size, "User set worker queue size"); size } None => { let min_processing_time = detector.get_min_processing_time()?; // Estimate queue size based on timeout and min processing time. // If min processing time is 100ms and timeout is 1000ms, we can // process 10 images in 1000ms, so queue size should be 10. // A queue size of 1000 makes no sense if we can only process 10 // images in 1000ms. This allows us to drop requests at the // service level instead of the worker level. let estimated_queue_size = (request_timeout.as_millis() / min_processing_time.as_millis()) as usize; info!( ?estimated_queue_size, ?request_timeout, ?min_processing_time, "Estimated worker queue" ); estimated_queue_size } }; let (sender, receiver) = crossbeam::channel::bounded(worker_queue_size); Ok(( sender, DetectorWorker { receiver, detector, request_timeout, }, )) } pub fn get_detector(&self) -> &Detector { &self.detector } pub fn run(&mut self) { info!("Detector worker thread: Starting detector worker loop"); while let Ok((vision_request, response_sender, start_request_time)) = self.receiver.recv() { let queue_time = start_request_time.elapsed(); debug!( ?queue_time, "Received request from worker time spent in queue" ); let VisionDetectionRequest { image_data, image_name, min_confidence, .. } = vision_request; let image_name = if image_name == "image.jpg" { Some(create_random_jpeg_name()) } else { Some(image_name) }; let min_confidence = (min_confidence > 0.01).then_some(min_confidence); let detect_result = self.detector.detect(image_data, image_name, min_confidence); let detect_response = match detect_result { Ok(detect_result) => VisionDetectionResponse { success: true, message: "".into(), error: None, predictions: detect_result.predictions.to_vec(), count: detect_result.predictions.len() as i32, command: "detect".into(), moduleId: self.detector.get_model_name().clone(), executionProvider: detect_result.endpoint_provider.to_string(), canUseGPU: detect_result.device_type == DeviceType::GPU, inferenceMs: detect_result.inference_time.as_millis() as i32, processMs: detect_result.processing_time.as_millis() as i32, analysisRoundTripMs: 0_i32, }, Err(err) => VisionDetectionResponse { success: false, message: "Failboat".into(), error: Some(err.to_string()), predictions: vec![], count: 0, command: "detect".into(), moduleId: self.detector.get_model_name().clone(), executionProvider: "CPU".into(), canUseGPU: false, inferenceMs: 0_i32, processMs: 0_i32, analysisRoundTripMs: 0_i32, }, }; let request_time = start_request_time.elapsed(); if request_time > self.request_timeout { warn!(?detect_response, ?request_time, ?self.request_timeout, "Request timed out, this means that the server is overloaded and we will drop this response."); warn!( "If you see this message spamming you should reduce the number of requests or upgrade your service to be faster." ); } if let Err(err) = response_sender.send(detect_response) { warn!(?err, ?request_time, ?self.request_timeout, "Failed to send response from worker, the client request has most likely timed out so receiver is gone."); warn!( "If you see this message spamming you should reduce the number of requests or upgrade your service to be faster." ); } } info!("Detector worker thread: Completed and exiting"); } /// Spawns the detector worker thread with optimized settings pub fn spawn_worker_thread(mut self) -> std::thread::JoinHandle<()> { std::thread::spawn(move || { #[cfg(windows)] unsafe { use windows::Win32::System::Threading::{ GetCurrentProcessorNumber, GetCurrentThread, SetThreadAffinityMask, SetThreadPriority, THREAD_PRIORITY_TIME_CRITICAL, }; let thread_handle = GetCurrentThread(); if let Err(err) = SetThreadPriority(thread_handle, THREAD_PRIORITY_TIME_CRITICAL) { tracing::error!(?err, "Failed to set thread priority to time critical"); } let processor_number = GetCurrentProcessorNumber(); let core_mask = 1usize << processor_number; let previous_mask = SetThreadAffinityMask(thread_handle, core_mask); if previous_mask == 0 { tracing::error!("Failed to set thread affinity."); } } self.run(); }) } }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/server.rs
src/server.rs
use crate::{ api::{ StatusUpdateResponse, VersionInfo, VisionCustomListResponse, VisionDetectionRequest, VisionDetectionResponse, }, detector::ExecutionProvider, startup_coordinator::{DetectorInfo, InitResult}, }; use askama::Template; use axum::{ Json, Router, body::{self, Body}, extract::{DefaultBodyLimit, Multipart, State}, http::{Request, StatusCode, header::CACHE_CONTROL}, response::{IntoResponse, Response}, routing::{get, post}, }; use base64::{Engine as _, engine::general_purpose}; use bytes::Bytes; use chrono::Utc; use crossbeam::channel::Sender; use mime::IMAGE_JPEG; use reqwest; use serde::Deserialize; use std::{ net::{Ipv4Addr, SocketAddr}, path::{Path, PathBuf}, sync::Arc, time::Instant, }; use tokio::{ sync::{Mutex, oneshot}, time::{Duration, timeout}, }; use tokio_util::sync::CancellationToken; use tracing::{debug, error, info, warn}; const MEGABYTE: usize = 1024 * 1024; // 1 MB = 1024 * 1024 bytes const THIRTY_MEGABYTES: usize = 30 * MEGABYTE; // 30 MB in bytes enum DetectorReady { NotReady, Ready { sender: Sender<( VisionDetectionRequest, oneshot::Sender<VisionDetectionResponse>, Instant, )>, #[allow(dead_code)] detector_info: DetectorInfo, worker_thread_handle: Option<std::thread::JoinHandle<()>>, }, Failed(String), } struct ServerState { detector_ready: Mutex<DetectorReady>, metrics: Mutex<Metrics>, restart_token: CancellationToken, config_path: PathBuf, } pub async fn run_server( port: u16, cancellation_token: CancellationToken, restart_token: CancellationToken, detector_init_receiver: tokio::sync::oneshot::Receiver<InitResult>, metrics: Metrics, config_path: PathBuf, ) -> anyhow::Result<(bool, Option<std::thread::JoinHandle<()>>)> { // Return bool to indicate if restart was requested let server_state = Arc::new(ServerState { detector_ready: Mutex::new(DetectorReady::NotReady), metrics: Mutex::new(metrics), restart_token: restart_token.clone(), config_path, }); // Spawn a task to wait for detector initialization and update the server state let state_clone = server_state.clone(); tokio::spawn(async move { match detector_init_receiver.await { Ok(InitResult::Success { sender, detector_info, worker_thread_handle, }) => { info!( model_name = %detector_info.model_name, execution_provider = ?detector_info.execution_provider, "Detector ready - server can now handle requests" ); // Update metrics with real detector info { let mut metrics = state_clone.metrics.lock().await; metrics.update_detector_info(&detector_info); } // Update detector ready state { let mut detector_ready = state_clone.detector_ready.lock().await; *detector_ready = DetectorReady::Ready { sender, detector_info, worker_thread_handle: Some(worker_thread_handle), }; } } Ok(InitResult::Failed(error)) => { error!(error = %error, "Detector initialization failed"); let mut detector_ready = state_clone.detector_ready.lock().await; *detector_ready = DetectorReady::Failed(error); } Err(_) => { error!("Detector initialization channel was dropped"); let mut detector_ready = state_clone.detector_ready.lock().await; *detector_ready = DetectorReady::Failed("Initialization channel dropped".to_string()); } } }); let blue_onyx = Router::new() .route("/", get(welcome_handler)) .route( "/v1/status/updateavailable", get(v1_status_update_available), ) .route("/v1/vision/detection", post(v1_vision_detection)) .route("/v1/vision/custom/list", post(v1_vision_custom_list)) .route("/stats", get(stats_handler)) .route("/test", get(show_form).post(handle_upload)) .route("/config", get(config_get_handler).post(config_post_handler)) .route("/config/restart", post(config_restart_handler)) .route("/config/loglevel", post(config_loglevel_handler)) .route("/favicon.ico", get(favicon_handler)) .route( "/static/css/bootstrap-icons.css", get(bootstrap_icons_css_handler), ) .fallback(fallback_handler) .with_state(server_state.clone()) .layer(DefaultBodyLimit::max(THIRTY_MEGABYTES)); let addr = SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), port); info!("Starting server, listening on {}", addr); info!("Welcome page, http://127.0.0.1:{}", port); let listener = match tokio::net::TcpListener::bind(addr).await { Ok(listener) => listener, Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => { error!( "Looks like {port} is already in use either by Blue Onyx, CPAI or another application, please turn off the other application or pick another port with --port" ); return Err(e.into()); } Err(e) => return Err(e.into()), }; let restart_check = restart_token.clone(); axum::serve(listener, blue_onyx.into_make_service()) .with_graceful_shutdown(async move { tokio::select! { _ = cancellation_token.cancelled() => {}, _ = restart_check.cancelled() => {}, } }) .await?; // Return true if restart was requested, false if normal shutdown // Also return the worker thread handle if available for clean shutdown let worker_handle = server_state.take_worker_thread_handle().await; Ok((restart_token.is_cancelled(), worker_handle)) } #[derive(Template)] #[template(path = "welcome.html")] struct WelcomeTemplate { logo_data: String, metrics: Metrics, } async fn welcome_handler(State(server_state): State<Arc<ServerState>>) -> impl IntoResponse { const LOGO: &[u8] = include_bytes!("../assets/logo_large.png"); let encoded_logo = general_purpose::STANDARD.encode(LOGO); let logo_data = format!("data:image/png;base64,{encoded_logo}"); let metrics = { let metrics_guard = server_state.metrics.lock().await; metrics_guard.clone() }; let template = WelcomeTemplate { logo_data, metrics }; match template.render() { Ok(body) => ( [ (CACHE_CONTROL, "no-store, no-cache, must-revalidate"), (axum::http::header::CONTENT_TYPE, "text/html; charset=utf-8"), ], body, ) .into_response(), Err(e) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("Template error: {e}"), ) .into_response(), } } async fn v1_vision_detection( State(server_state): State<Arc<ServerState>>, mut multipart: Multipart, // Note multipart needs to be last ) -> Result<Json<VisionDetectionResponse>, BlueOnyxError> { let request_start_time = Instant::now(); let mut vision_request = VisionDetectionRequest::default(); while let Some(field) = multipart.next_field().await? { match field.name() { Some("min_confidence") => { vision_request.min_confidence = field.text().await?.parse::<f32>()?; } Some("image") => { if let Some(image_name) = field.file_name().map(|s| s.to_string()) { vision_request.image_name = image_name; } vision_request.image_data = field.bytes().await?; } Some(&_) => {} None => {} } } // Check detector state first let detector_ready = server_state.detector_ready.lock().await; match &*detector_ready { DetectorReady::NotReady => { // Detector is still initializing, return not ready Err(BlueOnyxError(anyhow::anyhow!( "Server not ready yet, detector is still initializing" ))) } DetectorReady::Failed(error_msg) => { // Detector initialization failed Err(BlueOnyxError(anyhow::anyhow!( "Detector initialization failed: {}", error_msg ))) } DetectorReady::Ready { sender, detector_info: _, worker_thread_handle: _, } => { // Detector is ready, proceed with request let (response_sender, receiver) = tokio::sync::oneshot::channel(); if sender.is_full() { warn!("Worker queue is full server is overloaded, rejecting request"); drop(detector_ready); // Release the lock update_dropped_requests(server_state).await; return Err(BlueOnyxError(anyhow::anyhow!("Worker queue is full"))); } if let Err(err) = sender.send((vision_request, response_sender, request_start_time)) { warn!(?err, "Failed to send request to detection worker"); drop(detector_ready); // Release the lock update_dropped_requests(server_state).await; return Err(BlueOnyxError(anyhow::anyhow!("Worker queue is full"))); } drop(detector_ready); // Release the lock before waiting let result = timeout(Duration::from_secs(30), receiver).await; let mut vision_response = match result { Ok(Ok(response)) => response, Ok(Err(err)) => { warn!("Failed to receive vision detection response: {:?}", err); update_dropped_requests(server_state).await; return Err(BlueOnyxError::from(err)); } Err(_) => { warn!("Timeout while waiting for vision detection response"); update_dropped_requests(server_state).await; return Err(BlueOnyxError::from(anyhow::anyhow!("Operation timed out"))); } }; vision_response.analysisRoundTripMs = request_start_time.elapsed().as_millis() as i32; { let mut metrics = server_state.metrics.lock().await; metrics.update_metrics(&vision_response); } Ok(Json(vision_response)) } } } async fn v1_status_update_available() -> Result<Json<StatusUpdateResponse>, BlueOnyxError> { let (latest_release_version_str, release_notes_url) = get_latest_release_info().await?; let latest = VersionInfo::parse(latest_release_version_str.as_str(), Some(release_notes_url))?; let current = VersionInfo::parse(env!("CARGO_PKG_VERSION"), None)?; let updates_available = latest > current; let response = StatusUpdateResponse { success: true, message: "".to_string(), version: None, // Deprecated field current, latest, updateAvailable: updates_available, }; Ok(Json(response)) } async fn v1_vision_custom_list() -> Result<Json<VisionCustomListResponse>, BlueOnyxError> { let response = VisionCustomListResponse { success: true, models: vec![], moduleId: "".to_string(), moduleName: "".to_string(), command: "list".to_string(), statusData: None, inferenceDevice: "CPU".to_string(), analysisRoundTripMs: 0, processedBy: "BlueOnyx".to_string(), timestampUTC: Utc::now().to_rfc3339(), }; Ok(Json(response)) } #[derive(Template)] #[template(path = "stats.html")] struct StatsTemplate { metrics: Metrics, } async fn stats_handler(State(server_state): State<Arc<ServerState>>) -> impl IntoResponse { let metrics = { let metrics_guard = server_state.metrics.lock().await; metrics_guard.clone() }; let template = StatsTemplate { metrics }; match template.render() { Ok(body) => ( [ (CACHE_CONTROL, "no-store, no-cache, must-revalidate"), (axum::http::header::CONTENT_TYPE, "text/html; charset=utf-8"), ], body, ) .into_response(), Err(e) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("Template error: {e}"), ) .into_response(), } } async fn show_form() -> impl IntoResponse { let template = TestTemplate; match template.render() { Ok(body) => ( [ (CACHE_CONTROL, "no-store, no-cache, must-revalidate"), (axum::http::header::CONTENT_TYPE, "text/html; charset=utf-8"), ], body, ) .into_response(), Err(e) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("Template error: {e}"), ) .into_response(), } } async fn favicon_handler() -> impl IntoResponse { const FAVICON: &[u8] = include_bytes!("../assets/favicon.ico"); ( [(axum::http::header::CONTENT_TYPE, "image/x-icon")], FAVICON, ) .into_response() } #[derive(Template)] #[template(path = "config.html")] struct ConfigTemplate { logo_data: String, config: ConfigTemplateData, config_path: String, success_message: String, error_message: String, } #[derive(Debug)] struct ConfigTemplateData { port: u16, request_timeout: u64, worker_queue_size: String, model_selection_type: String, builtin_model: String, custom_model_path: String, custom_model_type: String, custom_object_classes: String, object_filter_str: String, confidence_threshold: f32, log_level: String, log_path: String, force_cpu: bool, gpu_index: i32, intra_threads: usize, inter_threads: usize, save_image_path: String, save_ref_image: bool, save_stats_path: String, is_windows: bool, } async fn config_get_handler(State(state): State<Arc<ServerState>>) -> impl IntoResponse { show_config_form("".to_string(), "".to_string(), &state.config_path).await } async fn config_post_handler( State(state): State<Arc<ServerState>>, mut multipart: Multipart, ) -> impl IntoResponse + use<> { // Parse form data let mut form_data = std::collections::HashMap::new(); while let Some(field) = multipart.next_field().await.unwrap_or(None) { if let Some(name) = field.name() { let name = name.to_string(); // Clone the name first if let Ok(value) = field.text().await { form_data.insert(name, value); } } } // Use the config path from server state let current_config_path = &state.config_path; let mut config = crate::cli::Cli::load_config(current_config_path).unwrap_or_default(); // Update configuration from form data update_config_from_form_data(&mut config, &form_data); // Save the updated configuration match config.save_config(current_config_path) { Ok(()) => { show_config_form( "Configuration saved successfully!".to_string(), "".to_string(), current_config_path, ) .await } Err(e) => { show_config_form( "".to_string(), format!("Failed to save configuration: {e}"), current_config_path, ) .await } } } async fn config_restart_handler( State(state): State<Arc<ServerState>>, mut multipart: Multipart, ) -> impl IntoResponse { // First, save the configuration (same logic as config_post_handler) let mut form_data = std::collections::HashMap::new(); while let Some(field) = multipart.next_field().await.unwrap_or(None) { if let Some(name) = field.name() { let name = name.to_string(); if let Ok(value) = field.text().await { form_data.insert(name, value); } } } // Load and update configuration let current_config_path = &state.config_path; let mut config = crate::cli::Cli::load_config(current_config_path).unwrap_or_default(); // Apply all form updates (complete parsing logic from config_post_handler) update_config_from_form_data(&mut config, &form_data); // Save configuration match config.save_config(current_config_path) { Ok(()) => { info!("Configuration saved, triggering server restart..."); // Check if detector is ready before restarting let detector_ready = state.detector_ready.lock().await; match &*detector_ready { DetectorReady::Ready { .. } => { // Detector is ready, we can restart immediately drop(detector_ready); // Release the lock state.restart_token.cancel(); ( StatusCode::OK, Json(serde_json::json!({ "success": true, "message": "Configuration saved and server restart initiated. Please wait...", })), ).into_response() } DetectorReady::NotReady => { // Detector is still initializing, wait for it to complete then restart drop(detector_ready); // Release the lock // Spawn a task to wait for detector initialization and then restart let restart_token = state.restart_token.clone(); let state_clone = state.clone(); tokio::spawn(async move { info!( "Detector still initializing, waiting for completion before restart..." ); // Poll until detector is ready loop { tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; let detector_ready = state_clone.detector_ready.lock().await; match &*detector_ready { DetectorReady::Ready { .. } | DetectorReady::Failed(_) => { // Detector initialization completed (success or failure) drop(detector_ready); info!( "Detector initialization completed, triggering restart now" ); restart_token.cancel(); break; } DetectorReady::NotReady => { // Still not ready, continue waiting continue; } } } }); ( StatusCode::OK, Json(serde_json::json!({ "success": true, "message": "Configuration saved. Waiting for detector initialization to complete before restart...", })), ).into_response() } DetectorReady::Failed(_) => { // Detector failed, restart immediately to try again drop(detector_ready); state.restart_token.cancel(); ( StatusCode::OK, Json(serde_json::json!({ "success": true, "message": "Configuration saved and server restart initiated (detector failed)...", })), ).into_response() } } } Err(e) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to save configuration: {e}"), ) .into_response(), } } #[derive(Deserialize)] struct LogLevelRequest { log_level: crate::LogLevel, } async fn config_loglevel_handler(Json(payload): Json<LogLevelRequest>) -> impl IntoResponse { match crate::update_log_level(payload.log_level) { Ok(()) => { info!(?payload.log_level, "Log level updated successfully via API"); ( StatusCode::OK, Json(serde_json::json!({ "success": true, "message": format!("Log level updated to {:?}", payload.log_level), "new_level": format!("{:?}", payload.log_level) })), ) .into_response() } Err(e) => { error!("Failed to update log level: {}", e); ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({ "success": false, "message": format!("Failed to update log level: {}", e) })), ) .into_response() } } } async fn show_config_form( success_message: String, error_message: String, config_path: &Path, ) -> impl IntoResponse + use<> { const LOGO: &[u8] = include_bytes!("../assets/logo_large.png"); let encoded_logo = general_purpose::STANDARD.encode(LOGO); let logo_data = format!("data:image/png;base64,{encoded_logo}"); // Use the provided config path instead of trying to get the default let current_config_path = config_path.to_path_buf(); let config = crate::cli::Cli::load_config(&current_config_path).unwrap_or_default(); // Determine if using builtin or custom model let ( model_selection_type, builtin_model, custom_model_path, custom_model_type, custom_object_classes, ) = if let Some(model_path) = &config.model { if let Some(model_filename) = model_path.file_name().and_then(|name| name.to_str()) { // Check if this is a builtin model (just filename, no path, and matches known models) let is_builtin = !model_filename.contains('\\') && !model_filename.contains('/') && (model_filename.starts_with("rt-detr") || model_filename.starts_with("rf-detr") || model_filename == "delivery.onnx" || model_filename.starts_with("IPcam-") || model_filename.starts_with("ipcam-") || model_filename == "package.onnx"); if is_builtin { ( "builtin".to_string(), model_filename.to_string(), String::new(), String::new(), String::new(), ) } else { ( "custom".to_string(), String::new(), model_path.to_string_lossy().to_string(), config.object_detection_model_type.to_string(), config .object_classes .as_ref() .map(|p| p.to_string_lossy().to_string()) .unwrap_or_default(), ) } } else { // Invalid filename, default to builtin ( "builtin".to_string(), "rt-detrv2-s.onnx".to_string(), String::new(), String::new(), String::new(), ) } } else { // No model specified, default to builtin with rt-detrv2-s.onnx ( "builtin".to_string(), "rt-detrv2-s.onnx".to_string(), String::new(), String::new(), String::new(), ) }; let config_data = ConfigTemplateData { port: config.port, request_timeout: config.request_timeout.as_secs(), worker_queue_size: config .worker_queue_size .map(|v| v.to_string()) .unwrap_or_default(), model_selection_type, builtin_model, custom_model_path, custom_model_type, custom_object_classes, object_filter_str: config.object_filter.join(", "), confidence_threshold: config.confidence_threshold, log_level: format!("{:?}", config.log_level), log_path: config .log_path .as_ref() .map(|p| p.to_string_lossy().to_string()) .unwrap_or_default(), force_cpu: config.force_cpu, gpu_index: config.gpu_index, intra_threads: config.intra_threads, inter_threads: config.inter_threads, save_image_path: config .save_image_path .as_ref() .map(|p| p.to_string_lossy().to_string()) .unwrap_or_default(), save_ref_image: config.save_ref_image, save_stats_path: config .save_stats_path .as_ref() .map(|p| p.to_string_lossy().to_string()) .unwrap_or_default(), is_windows: cfg!(target_os = "windows"), }; let template = ConfigTemplate { logo_data, config: config_data, config_path: current_config_path.to_string_lossy().to_string(), success_message, error_message, }; render_config_template(template) } fn render_config_template(template: ConfigTemplate) -> impl IntoResponse { match template.render() { Ok(body) => ( [ (CACHE_CONTROL, "no-store, no-cache, must-revalidate"), (axum::http::header::CONTENT_TYPE, "text/html; charset=utf-8"), ], body, ) .into_response(), Err(e) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("Template error: {e}"), ) .into_response(), } } async fn fallback_handler(req: Request<Body>) -> impl IntoResponse { let method = req.method().clone(); let uri = req.uri().clone(); let headers = req.headers().clone(); let body_bytes = body::to_bytes(req.into_body(), usize::MAX) .await .unwrap_or_else(|_| body::Bytes::new()); debug!( "Unimplemented endpoint called: Method: {}, URI: {}, Headers: {:?}, Body: {:?}", method, uri, headers, body_bytes ); (StatusCode::NOT_FOUND, "Endpoint not implemented") } #[allow(unused)] #[derive(Debug, Deserialize)] struct VersionJson { version: String, windows: String, windows_sha256: String, } pub async fn get_latest_release_info() -> anyhow::Result<(String, String)> { let response = reqwest::get("https://github.com/xnorpx/blue-onyx/releases/latest/download/version.json") .await?; let version_info: VersionJson = response.json().await?; let latest_release_version_str = version_info.version; let release_notes_url = format!("https://github.com/xnorpx/blue-onyx/releases/{latest_release_version_str}"); Ok((latest_release_version_str, release_notes_url)) } #[derive(Debug, Clone)] pub struct Metrics { version: String, start_time: Instant, model_name: String, execution_provider_name: String, number_of_requests: u128, dropped_requests: u128, total_inference_ms: u128, min_inference_ms: i32, max_inference_ms: i32, total_processing_ms: u128, min_processing_ms: i32, max_processing_ms: i32, total_analysis_round_trip_ms: u128, min_analysis_round_trip_ms: i32, max_analysis_round_trip_ms: i32, } impl Metrics { pub fn new(model_name: String, execution_provider: String) -> Self { Self { version: env!("CARGO_PKG_VERSION").to_string(), start_time: Instant::now(), model_name, execution_provider_name: execution_provider, number_of_requests: 0, dropped_requests: 0, total_inference_ms: 0, min_inference_ms: i32::MAX, max_inference_ms: i32::MIN, total_processing_ms: 0, min_processing_ms: i32::MAX, max_processing_ms: i32::MIN, total_analysis_round_trip_ms: 0, min_analysis_round_trip_ms: i32::MAX, max_analysis_round_trip_ms: i32::MIN, } } fn uptime(&self) -> String { let elapsed = self.start_time.elapsed(); let days = elapsed.as_secs() / 86400; let hours = (elapsed.as_secs() % 86400) / 3600; let minutes = (elapsed.as_secs() % 3600) / 60; format!("{days} days, {hours} hours and {minutes} minutes") } fn update_metrics(&mut self, response: &VisionDetectionResponse) { self.number_of_requests = self.number_of_requests.wrapping_add(1); self.total_inference_ms = self .total_inference_ms .wrapping_add(response.inferenceMs as u128); self.min_inference_ms = self.min_inference_ms.min(response.inferenceMs); self.max_inference_ms = self.max_inference_ms.max(response.inferenceMs); self.total_processing_ms = self .total_processing_ms .wrapping_add(response.processMs as u128); self.min_processing_ms = self.min_processing_ms.min(response.processMs); self.max_processing_ms = self.max_processing_ms.max(response.processMs); self.total_analysis_round_trip_ms = self .total_analysis_round_trip_ms .wrapping_add(response.analysisRoundTripMs as u128); self.min_analysis_round_trip_ms = self .min_analysis_round_trip_ms .min(response.analysisRoundTripMs); self.max_analysis_round_trip_ms = self .max_analysis_round_trip_ms .max(response.analysisRoundTripMs); } fn update_dropped_requests(&mut self) { self.dropped_requests = self.dropped_requests.wrapping_add(1); } fn avg_ms(&self, total_ms: u128) -> i32 { if self.number_of_requests == 0 { 0 } else { (total_ms as f64 / self.number_of_requests as f64).round() as i32 } } fn avg_inference_ms(&self) -> i32 { self.avg_ms(self.total_inference_ms) } fn avg_processing_ms(&self) -> i32 { self.avg_ms(self.total_processing_ms) } fn avg_analysis_round_trip_ms(&self) -> i32 { self.avg_ms(self.total_analysis_round_trip_ms) } pub fn update_detector_info(&mut self, detector_info: &DetectorInfo) { self.model_name = detector_info.model_name.clone(); self.execution_provider_name = match &detector_info.execution_provider { ExecutionProvider::CPU => "CPU".to_string(), #[cfg(windows)] ExecutionProvider::DirectML(index) => format!("DirectML(GPU {index})"), }; } } impl ServerState { /// Extract the worker thread handle for clean shutdown /// Returns the handle if the detector is ready, None otherwise pub async fn take_worker_thread_handle(&self) -> Option<std::thread::JoinHandle<()>> { let mut detector_ready = self.detector_ready.lock().await; match &mut *detector_ready { DetectorReady::Ready { worker_thread_handle, .. } => worker_thread_handle.take(), _ => None, } } } async fn update_dropped_requests(server_state: Arc<ServerState>) { warn!( "If you see this message spamming you should reduce the number of requests or upgrade your service to be faster." ); let mut metrics = server_state.metrics.lock().await; metrics.update_dropped_requests(); } #[derive(Template)] #[template(path = "test.html")] struct TestTemplate; async fn handle_upload( State(server_state): State<Arc<ServerState>>, mut multipart: Multipart, ) -> impl IntoResponse { let request_start_time = Instant::now(); loop { let field_result = multipart.next_field().await;
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
true
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/system_info.rs
src/system_info.rs
use tracing::info; pub fn system_info() -> anyhow::Result<()> { info!("System Information:"); cpu_info()?; gpu_info(true)?; Ok(()) } pub fn cpu_model() -> String { use raw_cpuid::CpuId; let cpuid = CpuId::new(); match cpuid.get_processor_brand_string() { Some(cpu_brand) => cpu_brand.as_str().to_owned(), None => "Unknown".to_owned(), } } pub fn gpu_model(index: usize) -> String { let gpu_names = gpu_info(false).unwrap_or_default(); gpu_names .get(index) .cloned() .unwrap_or_else(|| "Unknown".to_owned()) } pub fn cpu_info() -> anyhow::Result<()> { use raw_cpuid::CpuId; let cpuid = CpuId::new(); let cpu_vendor_info = match cpuid.get_vendor_info() { Some(vendor_info) => vendor_info.as_str().to_owned(), None => "Unknown".to_owned(), }; let cpu_brand = match cpuid.get_processor_brand_string() { Some(cpu_brand) => cpu_brand.as_str().to_owned(), None => "Unknown".to_owned(), }; info!( "CPU | {} | {} | {} Cores | {} Logical Cores", cpu_vendor_info, cpu_brand, num_cpus::get_physical(), num_cpus::get() ); Ok(()) } #[cfg(not(windows))] pub fn gpu_info(_log_info: bool) -> anyhow::Result<Vec<String>> { Ok(vec![]) // TODO: Do something for Linux } #[cfg(windows)] pub fn gpu_info(log_info: bool) -> anyhow::Result<Vec<String>> { use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, DXGI_ADAPTER_DESC1, IDXGIFactory1}; let factory: IDXGIFactory1 = unsafe { CreateDXGIFactory1().map_err(|e| anyhow::anyhow!(e))? }; let mut adapter_index = 0; let mut gpu_names = Vec::new(); while let Ok(adapter) = unsafe { factory.EnumAdapters1(adapter_index) } { let desc: DXGI_ADAPTER_DESC1 = unsafe { adapter.GetDesc1().map_err(|e| anyhow::anyhow!(e))? }; let device_name = String::from_utf16_lossy(&desc.Description); if !device_name.contains("Microsoft") { let mut device_name = String::from_utf16_lossy(&desc.Description); device_name = device_name.replace('\0', ""); device_name = device_name.trim().to_string(); device_name = device_name.split_whitespace().collect::<Vec<_>>().join(" "); if !gpu_names.contains(&device_name) { gpu_names.push(device_name.clone()); } } adapter_index += 1; } gpu_names.sort(); if log_info { for device_name in &gpu_names { info!("GPU: {}", device_name); } } Ok(gpu_names) } #[cfg(test)] mod tests { use super::*; #[test] fn print_cuda_gpu_info() { gpu_info(true).unwrap(); } #[test] fn print_cpu_info() { cpu_info().unwrap() } }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/startup_coordinator.rs
src/startup_coordinator.rs
use crate::{ api::VisionDetectionRequest, api::VisionDetectionResponse, detector::DetectorConfig, detector::ExecutionProvider, worker::DetectorWorker, }; use crossbeam::channel::Sender; use std::time::Instant; use tokio::sync::oneshot; use tracing::{error, info}; /// Information about the initialized detector #[derive(Debug, Clone)] pub struct DetectorInfo { pub model_name: String, pub execution_provider: ExecutionProvider, } /// Result of detector initialization pub enum InitResult { Success { sender: Sender<( VisionDetectionRequest, oneshot::Sender<VisionDetectionResponse>, Instant, )>, detector_info: DetectorInfo, worker_thread_handle: std::thread::JoinHandle<()>, }, Failed(String), } /// Creates a startup worker thread that initializes the detector and returns /// a receiver that will get the sender once initialization is complete pub fn spawn_detector_initialization( detector_config: DetectorConfig, worker_queue_size: Option<usize>, ) -> tokio::sync::oneshot::Receiver<InitResult> { let (init_sender, init_receiver) = tokio::sync::oneshot::channel(); // Spawn background thread to initialize detector std::thread::spawn(move || { startup_worker_thread(init_sender, detector_config, worker_queue_size); }); init_receiver } /// The background worker thread that initializes the detector /// This function runs in a separate thread and sends the result via the channel fn startup_worker_thread( init_sender: tokio::sync::oneshot::Sender<InitResult>, detector_config: DetectorConfig, worker_queue_size: Option<usize>, ) { info!("Startup worker thread: Beginning detector initialization..."); // Initialize the detector worker in this background thread let init_result = DetectorWorker::new(detector_config.clone(), worker_queue_size); match init_result { Ok((sender, detector_worker)) => { // Get detector information before transferring ownership let detector = detector_worker.get_detector(); let execution_provider = if detector_config.object_detection_onnx_config.force_cpu || !detector.is_using_gpu() { ExecutionProvider::CPU } else { #[cfg(windows)] { ExecutionProvider::DirectML( detector_config.object_detection_onnx_config.gpu_index as usize, ) } #[cfg(not(windows))] { ExecutionProvider::CPU } }; let detector_info = DetectorInfo { model_name: detector.get_model_name().clone(), execution_provider: execution_provider.clone(), }; info!( model_name = %detector_info.model_name, execution_provider = ?detector_info.execution_provider, "Startup worker thread: Detector initialization complete, starting worker thread" ); // Start the detector worker in a separate thread (this will continue running) let worker_thread_handle = detector_worker.spawn_worker_thread(); // Hand over the sender to the server let result = InitResult::Success { sender, detector_info, worker_thread_handle, }; if init_sender.send(result).is_err() { error!("Startup worker thread: Failed to send initialization result to server"); } else { info!( "Startup worker thread: Handover complete, detector is now available to server" ); } info!( "Startup worker thread: Completed successfully (worker thread continues in background)" ); // The startup thread exits here, but the worker thread continues running // The server now owns the sender and can communicate with the detector } Err(e) => { error!(error = %e, "Startup worker thread: Detector initialization failed"); let result = InitResult::Failed(e.to_string()); if init_sender.send(result).is_err() { error!("Startup worker thread: Failed to send failure result to server"); } info!("Startup worker thread: Completed due to initialization failure"); } } }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/bin/test_blue_onyx.rs
src/bin/test_blue_onyx.rs
use blue_onyx::{DOG_BIKE_CAR_BYTES, api::VisionDetectionResponse}; use clap::Parser; use indicatif::{ProgressBar, ProgressStyle}; use reqwest::{Body, Client, multipart}; use std::time::{Duration, Instant}; use tokio::fs::File; use tokio_util::codec::{BytesCodec, FramedRead}; // Simple test client to send multiple requests to blue onyx service for testing #[derive(Parser)] #[command(author = "Marcus Asteborg", version=env!("CARGO_PKG_VERSION"), about = "TODO")] struct Args { /// Origin for the requests #[clap(short, long, default_value = "http://127.0.0.1:32168")] origin: String, /// Min confidence #[arg(long, default_value_t = 0.60)] pub min_confidence: f32, /// Optional image input path #[clap(short, long)] image: Option<String>, /// Number of requests to make #[clap(short, long, default_value_t = 1)] number_of_requests: u32, /// Interval in milliseconds for making requests #[clap(long, default_value_t = 1000)] interval: u64, } #[tokio::main(flavor = "current_thread")] async fn main() -> anyhow::Result<()> { let args = Args::parse(); let mut futures = Vec::with_capacity(args.number_of_requests as usize); let pb = ProgressBar::new(args.number_of_requests as u64); pb.set_style( ProgressStyle::default_bar() .template( "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta})", ) .unwrap() .progress_chars("#>-"), ); println!( "Calling {}, {} times with {} ms interval", args.origin, args.number_of_requests, args.interval ); let start_time = Instant::now(); for i in 0..args.number_of_requests { let image = args.image.clone(); let origin = args.origin.clone(); let min_confidence = args.min_confidence; futures.push(tokio::task::spawn(send_vision_detection_request( origin, image, min_confidence, ))); pb.inc(1); if i < args.number_of_requests - 1 { tokio::time::sleep(std::time::Duration::from_millis(args.interval)).await; } } let results = futures::future::join_all(futures).await; pb.finish_with_message("All requests completed!"); let runtime_duration = Instant::now().duration_since(start_time); let mut request_times: Vec<Duration> = Vec::with_capacity(args.number_of_requests as usize); let mut inference_times: Vec<i32> = Vec::with_capacity(args.number_of_requests as usize); let mut processing_times: Vec<i32> = Vec::with_capacity(args.number_of_requests as usize); let mut vision_detection_response = VisionDetectionResponse::default(); results.into_iter().for_each(|result| { if let Ok(Ok(result)) = result { vision_detection_response = result.0; inference_times.push(vision_detection_response.inferenceMs); processing_times.push(vision_detection_response.processMs); request_times.push(result.1); } }); assert!(inference_times.len() == args.number_of_requests as usize); println!("{vision_detection_response:#?}"); println!("Runtime duration: {runtime_duration:?}"); if !request_times.is_empty() { let min_duration = request_times.iter().min().unwrap(); let max_duration = request_times.iter().max().unwrap(); let avg_duration = request_times.iter().sum::<Duration>() / request_times.len() as u32; println!( "Request times -- min: {min_duration:?}, avg: {avg_duration:?}, max: {max_duration:?}" ); } else { println!("No request times to summarize"); } if !inference_times.is_empty() { let min_inference = inference_times.iter().min().unwrap(); let max_inference = inference_times.iter().max().unwrap(); let avg_inference = inference_times.iter().sum::<i32>() / inference_times.len() as i32; println!( "Inference times -- min: {min_inference}, avg: {avg_inference}, max: {max_inference}" ); } else { println!("No inference times to summarize"); } if !processing_times.is_empty() { let min_processing = processing_times.iter().min().unwrap(); let max_processing = processing_times.iter().max().unwrap(); let avg_processing = processing_times.iter().sum::<i32>() / processing_times.len() as i32; println!( "Processing times -- min: {min_processing}, avg: {avg_processing}, max: {max_processing}" ); } else { println!("No processing times to summarize"); } Ok(()) } async fn send_vision_detection_request( origin: String, image: Option<String>, min_confidence: f32, ) -> anyhow::Result<(VisionDetectionResponse, Duration)> { let url = reqwest::Url::parse(&origin)?.join("v1/vision/detection")?; let client = Client::new(); let image_part = if let Some(image) = image { let file = File::open(image).await?; let stream = FramedRead::new(file, BytesCodec::new()); let body = Body::wrap_stream(stream); multipart::Part::stream(body).file_name("image.jpg") } else { multipart::Part::bytes(DOG_BIKE_CAR_BYTES.to_vec()).file_name("image.jpg") }; let form = multipart::Form::new() .text("min_confidence", min_confidence.to_string()) .part("image", image_part); let request_start_time = Instant::now(); let response = match client.post(url).multipart(form).send().await { Ok(resp) => resp, Err(e) => { eprintln!("Request send error: {e}"); return Err(anyhow::anyhow!(e)); } }; if !response.status().is_success() { let status = response.status(); let body = match response.text().await { Ok(text) => text, Err(e) => { eprintln!("Failed to read response body: {e}"); return Err(anyhow::anyhow!(e)); } }; eprintln!("Error: Status: {status}, Body: {body}"); return Err(anyhow::anyhow!("Request failed with status {}", status)); } let response = match response.json::<VisionDetectionResponse>().await { Ok(json) => json, Err(e) => { eprintln!("Failed to parse JSON: {e}"); return Err(anyhow::anyhow!(e)); } }; Ok((response, Instant::now().duration_since(request_start_time))) }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/bin/blue_onyx_service.rs
src/bin/blue_onyx_service.rs
//! Blue Onyx service. //! //! This service loads configuration from blue_onyx_config_service.json //! If the config file doesn't exist, it creates one with default values. //! //! Install the service with proper GPU access: //! //! Increase service timeout to 10 minutes for model loading: //! `reg add "HKLM\SYSTEM\CurrentControlSet\Control" /v ServicesPipeTimeout /t REG_DWORD /d 600000 /f` //! //! First, create the event log source (run as Administrator): //! `New-EventLog -LogName Application -Source BlueOnyxService` //! //! Then install the service with LocalSystem for full access: //! `sc.exe create BlueOnyxService binPath= "<path>\blue_onyx_service.exe" start= auto displayname= "Blue Onyx Service" obj= LocalSystem` //! `sc.exe config BlueOnyxService type= own` //! //! Start the service: `net start BlueOnyxService` //! //! Stop the service: `net stop BlueOnyxService` //! //! Uninstall the service: `sc.exe delete BlueOnyxService` //! //! Configuration is managed via the blue_onyx_config_service.json file in the same directory as the executable. #[cfg(windows)] fn main() -> windows_service::Result<()> { blue_onyx_service::run() } #[cfg(not(windows))] fn main() { panic!("This program is only intended to run on Windows."); } #[cfg(windows)] mod blue_onyx_service { use blue_onyx::{ ServiceResult, blue_onyx_service, cli::Cli, init_service_logging, update_service_log_level, }; use std::{ffi::OsString, future::Future, time::Duration}; use tokio_util::sync::CancellationToken; use tracing::{error, info, warn}; use windows_service::{ Result, define_windows_service, service::{ ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType, }, service_control_handler::{self, ServiceControlHandlerResult}, service_dispatcher, }; const SERVICE_NAME: &str = "BlueOnyxService"; const SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS; pub fn run() -> Result<()> { service_dispatcher::start(SERVICE_NAME, ffi_service_main) } define_windows_service!(ffi_service_main, my_service_main); pub fn my_service_main(service_name: Vec<OsString>) { // Load initial configuration from service config file let mut current_args = match Cli::for_service() { Ok(args) => args, Err(err) => { eprintln!("Failed to load service configuration: {err}"); return; } }; // Initialize service logging once if let Err(e) = init_service_logging(current_args.log_level) { eprintln!("Failed to initialize logging: {e}"); return; } // Preload required DLLs for faster startup preload_service_dlls(); // Validate GPU environment for DirectML only if not forcing CPU if !current_args.force_cpu { validate_gpu_environment(); } else { info!("GPU validation skipped - force_cpu mode is enabled"); } info!( "Starting {} service with config from blue_onyx_config_service.json", service_name.join(&OsString::from(" ")).to_string_lossy() ); // Print the initial configuration being used current_args.print_config(); // Main service loop with restart support loop { // Reload configuration on each restart to pick up changes if let Ok(updated_args) = Cli::for_service() { if updated_args.log_level != current_args.log_level { info!( old_level = ?current_args.log_level, new_level = ?updated_args.log_level, "Log level change detected, applying dynamically" ); // Apply the new log level dynamically if let Err(e) = update_service_log_level(updated_args.log_level) { error!("Failed to update log level dynamically: {}", e); } } current_args = updated_args; current_args.print_config(); } else { info!("Using previous configuration (failed to reload config)"); } let (blue_onyx_service, cancellation_token, restart_token) = match blue_onyx_service(current_args.clone()) { Ok(v) => v, Err(err) => { error!( ?err, "Failed to init blue onyx service, will retry after delay" ); std::thread::sleep(Duration::from_secs(5)); continue; } }; let (should_restart, status_handle) = match run_service(blue_onyx_service, cancellation_token, restart_token.clone()) { Ok((restart, handle)) => (restart, Some(handle)), Err(err) => { error!(?err, "Blue onyx service failed, will retry after delay"); std::thread::sleep(Duration::from_secs(5)); (true, None) // Force restart after error } }; if should_restart { info!("Restarting Blue Onyx service..."); // Small delay before restart to avoid rapid restart loops std::thread::sleep(Duration::from_secs(1)); } else { info!("Blue Onyx service stopped normally"); // Set final service status to stopped if let Some(handle) = status_handle { let _ = handle.set_service_status(ServiceStatus { service_type: SERVICE_TYPE, current_state: ServiceState::Stopped, controls_accepted: ServiceControlAccept::empty(), exit_code: ServiceExitCode::Win32(0), checkpoint: 0, wait_hint: Duration::default(), process_id: None, }); } break; } } } pub fn run_service( blue_onyx_service: impl Future<Output = ServiceResult>, cancellation_token: CancellationToken, restart_token: CancellationToken, ) -> anyhow::Result<( bool, windows_service::service_control_handler::ServiceStatusHandle, )> { let restart_token_clone = restart_token.clone(); let event_handler = move |control_event| -> ServiceControlHandlerResult { match control_event { ServiceControl::Interrogate => ServiceControlHandlerResult::NoError, ServiceControl::Stop => { cancellation_token.cancel(); ServiceControlHandlerResult::NoError } ServiceControl::Shutdown => { cancellation_token.cancel(); ServiceControlHandlerResult::NoError } ServiceControl::UserEvent(code) => { match code.to_raw() { 130 => { // Stop signal cancellation_token.cancel(); } 131 => { // Restart signal restart_token_clone.cancel(); } _ => {} } ServiceControlHandlerResult::NoError } _ => ServiceControlHandlerResult::NotImplemented, } }; let status_handle = service_control_handler::register(SERVICE_NAME, event_handler)?; // Report that we're starting up and give Windows 60 seconds timeout status_handle.set_service_status(ServiceStatus { service_type: SERVICE_TYPE, current_state: ServiceState::StartPending, controls_accepted: ServiceControlAccept::empty(), exit_code: ServiceExitCode::Win32(0), checkpoint: 0, wait_hint: Duration::from_secs(600), // Tell Windows we need up to 60 seconds to start process_id: None, })?; let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; // Now report that we're fully running status_handle.set_service_status(ServiceStatus { service_type: SERVICE_TYPE, current_state: ServiceState::Running, controls_accepted: ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN, exit_code: ServiceExitCode::Win32(0), checkpoint: 0, wait_hint: Duration::default(), process_id: None, })?; let should_restart = rt.block_on(async { tokio::select! { result = blue_onyx_service => { match result { Ok((restart_requested, worker_handle)) => { // Wait for worker thread to complete if available if let Some(handle) = worker_handle { info!("Waiting for worker thread to complete..."); if let Err(e) = handle.join() { error!("Worker thread panicked: {:?}", e); } } restart_requested }, Err(err) => { error!(?err, "Blue onyx service encountered an error"); false // Don't restart on error } } } _ = restart_token.cancelled() => { info!("Restart signal received"); true // Restart requested } } }); // Only set service status to Stopped if we're not restarting if !should_restart { status_handle.set_service_status(ServiceStatus { service_type: SERVICE_TYPE, current_state: ServiceState::Stopped, controls_accepted: ServiceControlAccept::empty(), exit_code: ServiceExitCode::Win32(0), checkpoint: 0, wait_hint: Duration::default(), process_id: None, })?; } Ok((should_restart, status_handle)) } /// Validate GPU environment for DirectML access in service context fn validate_gpu_environment() { // Check session information info!("Validating GPU environment for service context"); // Set environment variables for better GPU access unsafe { std::env::set_var("DIRECTML_DEBUG", "0") }; unsafe { std::env::set_var("D3D12_EXPERIMENTAL_SHADER_MODELS", "1") }; // Validate DirectX 12 availability validate_directx12_support(); } /// Validate DirectX 12 support fn validate_directx12_support() { use windows::Win32::Graphics::Dxgi::*; // First try with debug flag which provides more information let factory_result = unsafe { CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_DEBUG) }; // If debug fails, try without debug let factory = match factory_result { Ok(f) => f, Err(e) => { info!( "DirectX 12 debug factory creation failed: {:?}. Trying without debug flag.", e ); match unsafe { CreateDXGIFactory2::<IDXGIFactory4>( windows::Win32::Graphics::Dxgi::DXGI_CREATE_FACTORY_FLAGS(0), ) } { Ok(f) => f, Err(e) => { error!( "DirectX 12 factory creation failed: {:?}. GPU acceleration will not be available.", e ); error!( "Possible causes: outdated graphics driver, no compatible GPU, or running in a remote desktop session." ); error!("DirectML will fall back to CPU execution."); return; } } } }; // Check for adapters let mut adapter_count = 0; let mut has_compatible_adapter = false; for i in 0..8 { match unsafe { factory.EnumAdapters1(i) } { Ok(adapter) => { adapter_count += 1; match unsafe { adapter.GetDesc1() } { Ok(desc) => { let desc_string = String::from_utf16_lossy(&desc.Description); let adapter_name = desc_string.trim_end_matches('\0'); let dedicated_video_memory_mb = desc.DedicatedVideoMemory / (1024 * 1024); info!( "GPU Adapter {}: {} (VRAM: {} MB)", i, adapter_name, dedicated_video_memory_mb ); // Check if this is likely a compatible adapter // DirectML typically works well with dedicated GPUs with sufficient VRAM if dedicated_video_memory_mb >= 1024 { has_compatible_adapter = true; } } Err(e) => { info!("GPU Adapter {}: Description unavailable - {:?}", i, e); } } } Err(_) => break, // No more adapters } } if adapter_count == 0 { error!("No GPU adapters found. DirectML will fall back to CPU execution."); } else if !has_compatible_adapter { warn!( "Found {} GPU adapter(s) but none seem to have sufficient VRAM (>=1GB).", adapter_count ); warn!("DirectML may still work but performance could be limited."); } else { info!( "Found {} compatible GPU adapter(s) - DirectX 12 support available", adapter_count ); } } /// Preload required DLLs for faster service startup fn preload_service_dlls() { use windows::Win32::System::LibraryLoader::LoadLibraryA; use windows::core::PCSTR; info!("Preloading service DLLs for optimized startup"); // List of DLLs to preload let dlls_to_preload = ["DirectML.dll", "onnxruntime.dll"]; let mut directml_available = false; for dll_name in &dlls_to_preload { let dll_cstr = format!("{dll_name}\0"); match unsafe { LoadLibraryA(PCSTR(dll_cstr.as_ptr())) } { Ok(handle) => { if !handle.is_invalid() { info!("Successfully preloaded: {}", dll_name); if dll_name == &"DirectML.dll" { directml_available = true; } } else if dll_name == &"DirectML.dll" { warn!( "Failed to preload DirectML.dll - GPU acceleration will not be available" ); } else { warn!( "Failed to preload: {} (library not found or invalid)", dll_name ); } } Err(e) => { if dll_name == &"DirectML.dll" { warn!( "Failed to preload DirectML.dll: {:?} - GPU acceleration will not be available", e ); } else { warn!("Failed to preload {}: {:?}", dll_name, e); } } } } if !directml_available { info!("DirectML is not available - CPU inference will be used"); } // Set DLL search optimization unsafe { std::env::set_var( "PATH", format!( "{};{}", std::env::current_exe() .unwrap_or_default() .parent() .unwrap_or(std::path::Path::new(".")) .display(), std::env::var("PATH").unwrap_or_default() ), ) }; } }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/bin/blue_onyx_benchmark.rs
src/bin/blue_onyx_benchmark.rs
//! Blue Onyx Benchmark Application //! //! This application benchmarks the inference performance of the rt-detrv2 model across //! different device configurations. It records statistics such as total inference time, //! average, minimum, and maximum inference durations, as well as images processed per second. //! The results is logged and can be saved to a file. //! //! The default model is the small rt-detrv2 model, and the default object classes are the 80 //! standard COCO classes. The application can also filter the results to include only the specified //! labels. The confidence threshold for object detection can be set, and the application can be //! forced to use the CPU for inference. The application can also be configured to save the processed //! image and the reference image, repeat the image processing. //! //! The application can be run with the following command: //! //! Downloaded binary: //! ```sh //! blue_onyx_benchmark --help //! ``` //! //! From repository: //! ```sh //! cargo run --bin blue_onyx_benchmark -- --help //! ``` //! use anyhow::bail; use blue_onyx::{ LogLevel, detector::{ Detector, DetectorConfig, DeviceType, EndpointProvider, ObjectDetectionModel, OnnxConfig, }, download_models::Model, image::load_image, init_logging, system_info::{cpu_model, gpu_model, system_info}, }; use bytes::Bytes; use clap::Parser; use std::{io::Write, path::PathBuf, time::Duration}; use tracing::{error, info}; #[derive(Parser)] #[command(author = "Marcus Asteborg", version=env!("CARGO_PKG_VERSION"), about = " Blue Onyx Benchmark Application This application benchmarks the inference performance of the rt-detrv2 model across different device configurations. It records statistics such as total inference time, average, minimum, and maximum inference durations, as well as images processed per second. The results is logged and can be saved to a file. The default model is the small rt-detrv2 model, and the default object classes are the 80 standard COCO classes. The application can also filter the results to include only the specified labels. The confidence threshold for object detection can be set, and the application can be forced to use the CPU for inference. The application can also be configured to save the processed image and the reference image, repeat the image processing. ")] struct Cli { /// Path to the image file /// If not given default test image is used #[clap(long)] image: Option<PathBuf>, /// Path to the ONNX model file. /// If not specified, the default rt-detrv2 small model will be used /// provided it is available in the directory. #[clap(long)] pub model: Option<PathBuf>, /// Type of model type to use. /// Default: rt-detrv2 #[clap(long, default_value_t = ObjectDetectionModel::RtDetrv2)] pub object_detection_model_type: ObjectDetectionModel, /// Path to the object classes yaml file /// Default: coco_classes.yaml which is the 80 standard COCO classes #[clap(long)] object_classes: Option<PathBuf>, /// Filters the results to include only the specified labels. Provide labels separated by ','. /// Example: --object_filter "person,cup" #[arg(long, value_delimiter = ',', num_args = 1..)] pub object_filter: Vec<String>, /// Sets the level of logging #[clap(long, value_enum, default_value_t = LogLevel::Info)] log_level: LogLevel, /// Confidence threshold for object detection #[clap(long, default_value_t = 0.5)] confidence_threshold: f32, /// Force using CPU for inference #[clap(long, default_value_t = false)] force_cpu: bool, /// Intra thread parallelism max is cpu cores - 1 #[clap(long, default_value_t = 192)] intra_threads: usize, /// Inter thread parallelism max is cpu cores - 1 #[clap(long, default_value_t = 192)] inter_threads: usize, /// Optional path to save the processed image #[clap(long)] save_image_path: Option<PathBuf>, /// Save the reference image (only if save_image_path is provided) #[clap(long, default_value_t = false)] save_ref_image: bool, /// Repeat the image processing #[clap(long, default_value_t = 1)] repeat: u32, /// GPU #[clap(long, default_value_t = 0)] gpu_index: i32, /// Save inference stats to file #[clap(long)] save_stats_path: Option<PathBuf>, /// Path to download all models to /// This command will only download the models to the specified path /// and then exit #[clap(long)] download_model_path: Option<PathBuf>, /// List all available models that can be downloaded #[clap(long)] list_models: bool, } fn main() -> anyhow::Result<()> { let args = Cli::parse(); let _guard = init_logging(args.log_level, &mut None)?; system_info()?; if args.list_models { blue_onyx::download_models::list_models(); return Ok(()); } if args.download_model_path.is_some() { let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; rt.block_on(async { blue_onyx::download_models::download_model( args.download_model_path.unwrap(), Model::All, ) .await })?; return Ok(()); } let detector_config = DetectorConfig { object_detection_onnx_config: OnnxConfig { model: args.model, force_cpu: args.force_cpu, gpu_index: args.gpu_index, intra_threads: args.intra_threads, inter_threads: args.inter_threads, }, object_classes: args.object_classes, object_filter: args.object_filter, confidence_threshold: args.confidence_threshold, save_image_path: args.save_image_path, save_ref_image: args.save_ref_image, timeout: Duration::MAX, object_detection_model: args.object_detection_model_type, }; let mut detector = Detector::new(detector_config)?; let (image_bytes, image_name) = if let Some(image) = args.image { (load_image(&image)?, image.to_string_lossy().to_string()) } else { ( Bytes::from(blue_onyx::DOG_BIKE_CAR_BYTES), "dog_bike_car.jpg".to_string(), ) }; let mut inference_times: Vec<Duration> = Vec::with_capacity(args.repeat as usize); info!( "Starting inference benchmark with {} repetitions", args.repeat ); let start_time = std::time::Instant::now(); let mut predictions = detector.detect(image_bytes.clone(), Some(image_name.clone()), None)?; if predictions.predictions.is_empty() { error!(?predictions, "No objects detected"); bail!("No objects detected"); } inference_times.push(predictions.inference_time); for _ in 1..args.repeat { predictions = detector.detect(image_bytes.clone(), Some(image_name.clone()), None)?; inference_times.push(predictions.inference_time); } let elapsed = start_time.elapsed(); info!("All done predictions: {:#?} in {:?}", predictions, elapsed); let device_name = match predictions.device_type { DeviceType::CPU => cpu_model(), DeviceType::GPU => gpu_model(args.gpu_index as usize), }; let inference_stats = InferenceStats::new( detector.get_model_name().clone(), device_name, predictions.device_type, predictions.endpoint_provider, inference_times, ); inference_stats.print_table(); inference_stats.save_to_file(args.save_stats_path)?; Ok(()) } #[derive(Debug, Clone)] pub enum Platform { Linux, Windows, } impl std::fmt::Display for Platform { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Platform::Linux => write!(f, "Linux "), Platform::Windows => write!(f, "Windows"), } } } impl Default for Platform { fn default() -> Self { if cfg!(target_os = "windows") { Platform::Windows } else if cfg!(target_os = "linux") { Platform::Linux } else { panic!("Unsupported platform"); } } } #[derive(Debug, Clone)] pub struct InferenceStats { pub model_name: String, pub version: String, pub device_name: String, pub device_type: DeviceType, pub platform: Platform, pub endpoint_provider: EndpointProvider, pub number_of_images: u64, pub total_inference: Duration, pub images_per_second: f64, pub min_inference: Duration, pub max_inference: Duration, pub average_inference: Duration, } impl InferenceStats { pub fn new( model_name: String, device_name: String, device_type: DeviceType, endpoint_provider: EndpointProvider, inference_times: Vec<Duration>, ) -> Self { let number_of_images = inference_times.len() as u64; let total_inference: Duration = inference_times.iter().sum(); let average_inference = Duration::from_secs_f64(total_inference.as_secs_f64() / number_of_images as f64); let min_inference = *inference_times.iter().min().unwrap_or(&Duration::ZERO); let max_inference = *inference_times.iter().max().unwrap_or(&Duration::ZERO); let total_inference_secs = total_inference.as_secs_f64(); let images_per_second = if total_inference_secs > 1. { number_of_images as f64 / total_inference_secs } else { 0. // Not enough time to calculate images per second moar images please! }; Self { model_name: model_name.replace(".onnx", ""), version: env!("CARGO_PKG_VERSION").to_string(), device_name, device_type, platform: Platform::default(), endpoint_provider, average_inference, min_inference, max_inference, total_inference, images_per_second, number_of_images, } } pub fn print_table(&self) { info!("Inference stats for {}", self.device_name); info!("{}", InferenceStats::format_stats_header()); info!("{}", self.format_stats()); } pub fn format_stats_header() -> String { format!( "{},{},{},{},{},{},{},{},{},{},{},{}", "Model Name", "Device Name", "Version", "Type", "Platform", "EndpointProvider", "Images", "Total [s]", "Min [ms]", "Max [ms]", "Average [ms]", "FPS" ) } pub fn format_stats(&self) -> String { let total_inference_secs = format!("{:.1}", self.total_inference.as_secs_f64()); let min_inference_ms = format!("{:.1}", self.min_inference.as_micros() as f64 / 1000.0); let max_inference_ms = format!("{:.1}", self.max_inference.as_micros() as f64 / 1000.0); let average_inference_ms = format!("{:.1}", self.average_inference.as_micros() as f64 / 1000.0); let images_per_second = format!("{:.1}", self.images_per_second); format!( "{},{},{},{},{},{},{},{},{},{},{},{}", self.model_name, self.device_name, self.version, self.device_type, self.platform, self.endpoint_provider, self.number_of_images, total_inference_secs, min_inference_ms, max_inference_ms, average_inference_ms, images_per_second ) } pub fn save_to_file(&self, path: Option<PathBuf>) -> std::io::Result<()> { let Some(path) = path else { return Ok(()); }; let sanitized_device_name: String = self .device_name .chars() .filter(|c| c.is_alphanumeric() || *c == '_') .collect(); let sanitized_model_name = self.model_name.replace(" ", "_").replace(".onnx", ""); let file_name = format!("blue_onyx_{sanitized_device_name}_{sanitized_model_name}_report.txt"); let path = path.join(file_name); let mut file = std::fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(path.clone())?; writeln!(file, "{}", InferenceStats::format_stats_header())?; write!(file, "{}", self.format_stats())?; info!(?path, "Inference stats saved"); Ok(()) } }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
xnorpx/blue-onyx
https://github.com/xnorpx/blue-onyx/blob/dc00f8bd73857e721a73e0ea804da436fef3ebed/src/bin/blue_onyx.rs
src/bin/blue_onyx.rs
use blue_onyx::{ blue_onyx_service as create_blue_onyx_service, cli::Cli, init_logging, system_info::system_info, update_log_level, }; use tracing::{error, info, warn}; fn main() -> anyhow::Result<()> { let Some(mut current_args) = Cli::from_config_and_args()? else { return Ok(()); }; let _guard = init_logging(current_args.log_level, &mut current_args.log_path)?; system_info()?; // Print the configuration being used current_args.print_config(); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; // Set up Ctrl+C handler once, outside the restart loop let global_shutdown = tokio_util::sync::CancellationToken::new(); let ctrl_c_shutdown = global_shutdown.clone(); rt.spawn(async move { tokio::signal::ctrl_c() .await .expect("Failed to listen for Ctrl+C"); info!("Ctrl+C received, shutting down server"); ctrl_c_shutdown.cancel(); }); loop { let (blue_onyx_service_future, cancellation_token, restart_token) = create_blue_onyx_service(current_args.clone())?; let should_restart = rt.block_on(async { // Wait for either the service to complete, restart to be requested, or global shutdown tokio::select! { result = blue_onyx_service_future => { match result { Ok((restart_requested, worker_handle)) => { // Wait for worker thread to complete if available if let Some(handle) = worker_handle { info!("Waiting for worker thread to complete..."); if let Err(e) = handle.join() { error!("Worker thread panicked: {:?}", e); } } restart_requested }, Err(e) => { error!("Service failed: {}", e); false // Don't restart on error } } } _ = restart_token.cancelled() => { info!("Restart requested via API"); true // Restart requested } _ = global_shutdown.cancelled() => { info!("Global shutdown requested"); cancellation_token.cancel(); // Cancel the current service false // Don't restart, just exit } } }); if should_restart { info!("Restarting server with updated configuration..."); // Reload configuration for restart let new_args = Cli::from_config_and_args()?.expect("Should always have args"); // Check if log level changed and update dynamically if new_args.log_level != current_args.log_level { info!( old_level = ?current_args.log_level, new_level = ?new_args.log_level, "Log level change detected, applying dynamically" ); if let Err(e) = update_log_level(new_args.log_level) { warn!("Failed to update log level dynamically: {}", e); } } current_args = new_args; continue; } else { break; // Normal shutdown } } Ok(()) }
rust
MIT
dc00f8bd73857e721a73e0ea804da436fef3ebed
2026-01-04T20:24:46.035395Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/builder.rs
src/builder.rs
//! contains the QuickJsRuntimeBuilder which may be used to instantiate a new QuickjsRuntimeFacade use crate::facades::QuickJsRuntimeFacade; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use crate::jsutils::modules::{CompiledModuleLoader, NativeModuleLoader, ScriptModuleLoader}; use crate::jsutils::{JsError, ScriptPreProcessor}; use std::time::Duration; pub type EsRuntimeInitHooks = Vec<Box<dyn FnOnce(&QuickJsRuntimeFacade) -> Result<(), JsError> + Send + 'static>>; /// the EsRuntimeBuilder is used to init an EsRuntime /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// // init a rt which may use 16MB of memory /// let rt = QuickJsRuntimeBuilder::new() /// .memory_limit(1024*1024*16) /// .build(); /// ``` pub struct QuickJsRuntimeBuilder { pub(crate) script_module_loaders: Vec<Box<dyn ScriptModuleLoader + Send>>, pub(crate) native_module_loaders: Vec<Box<dyn NativeModuleLoader + Send>>, pub(crate) compiled_module_loaders: Vec<Box<dyn CompiledModuleLoader + Send>>, pub(crate) opt_memory_limit_bytes: Option<u64>, pub(crate) opt_gc_threshold: Option<u64>, pub(crate) opt_max_stack_size: Option<u64>, pub(crate) opt_gc_interval: Option<Duration>, pub(crate) runtime_init_hooks: EsRuntimeInitHooks, pub(crate) script_pre_processors: Vec<Box<dyn ScriptPreProcessor + Send>>, #[allow(clippy::type_complexity)] pub(crate) interrupt_handler: Option<Box<dyn Fn(&QuickJsRuntimeAdapter) -> bool + Send>>, } impl QuickJsRuntimeBuilder { /// build an EsRuntime pub fn build(self) -> QuickJsRuntimeFacade { log::debug!("QuickJsRuntimeBuilder.build"); QuickJsRuntimeFacade::new(self) } /// init a new EsRuntimeBuilder pub fn new() -> Self { Self { script_module_loaders: vec![], native_module_loaders: vec![], compiled_module_loaders: vec![], opt_memory_limit_bytes: None, opt_gc_threshold: None, opt_max_stack_size: None, opt_gc_interval: None, runtime_init_hooks: vec![], script_pre_processors: vec![], interrupt_handler: None, } } /// add a script loaders which will be used to load modules when they are imported from script /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::modules::ScriptModuleLoader; /// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter; /// use quickjs_runtime::jsutils::Script; /// struct MyModuleLoader {} /// impl ScriptModuleLoader for MyModuleLoader { /// fn normalize_path(&self, realm: &QuickJsRealmAdapter ,ref_path: &str,path: &str) -> Option<String> { /// Some(path.to_string()) /// } /// /// fn load_module(&self, realm: &QuickJsRealmAdapter, absolute_path: &str) -> String { /// "export const foo = 12;".to_string() /// } /// } /// /// let rt = QuickJsRuntimeBuilder::new() /// .script_module_loader(MyModuleLoader{}) /// .build(); /// rt.eval_module_sync(None, Script::new("test_module.es", "import {foo} from 'some_module.mes';\nconsole.log('foo = %s', foo);")).ok().unwrap(); /// ``` pub fn script_module_loader<M: ScriptModuleLoader + Send + 'static>( mut self, loader: M, ) -> Self { self.script_module_loaders.push(Box::new(loader)); self } /// add a ScriptPreProcessor which will be called for all scripts which are evaluated and compiled pub fn script_pre_processor<S: ScriptPreProcessor + Send + 'static>( mut self, processor: S, ) -> Self { self.script_pre_processors.push(Box::new(processor)); self } /// add a module loader which can load native functions and proxy classes /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::modules::NativeModuleLoader; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter; /// use quickjs_runtime::quickjs_utils::functions; /// use quickjs_runtime::quickjs_utils::primitives::{from_bool, from_i32}; /// use quickjs_runtime::reflection::Proxy; /// /// struct MyModuleLoader{} /// impl NativeModuleLoader for MyModuleLoader { /// fn has_module(&self, _q_ctx: &QuickJsRealmAdapter,module_name: &str) -> bool { /// module_name.eq("my_module") /// } /// /// fn get_module_export_names(&self, _q_ctx: &QuickJsRealmAdapter, _module_name: &str) -> Vec<&str> { /// vec!["someVal", "someFunc", "SomeClass"] /// } /// /// fn get_module_exports(&self, q_ctx: &QuickJsRealmAdapter, _module_name: &str) -> Vec<(&str, QuickJsValueAdapter)> { /// /// let js_val = from_i32(1470); /// let js_func = functions::new_function_q( /// q_ctx, /// "someFunc", |_q_ctx, _this, _args| { /// return Ok(from_i32(432)); /// }, 0) /// .ok().unwrap(); /// let js_class = Proxy::new() /// .name("SomeClass") /// .static_method("doIt", |_rt, _q_ctx, _args|{ /// return Ok(from_i32(185)); /// }) /// .install(q_ctx, false) /// .ok().unwrap(); /// /// vec![("someVal", js_val), ("someFunc", js_func), ("SomeClass", js_class)] /// } /// } /// /// let rt = QuickJsRuntimeBuilder::new() /// .native_module_loader(MyModuleLoader{}) /// .build(); /// /// rt.eval_module_sync(None, Script::new("test_native_mod.es", "import {someVal, someFunc, SomeClass} from 'my_module';\nlet i = (someVal + someFunc() + SomeClass.doIt());\nif (i !== 2087){throw Error('i was not 2087');}")).ok().expect("script failed"); /// ``` pub fn native_module_loader<S: NativeModuleLoader + Send + 'static>( mut self, module_loader: S, ) -> Self where Self: Sized, { self.native_module_loaders.push(Box::new(module_loader)); self } /// set max memory the runtime may use pub fn memory_limit(mut self, bytes: u64) -> Self { self.opt_memory_limit_bytes = Some(bytes); self } /// number of allocations before gc is run pub fn gc_threshold(mut self, size: u64) -> Self { self.opt_gc_threshold = Some(size); self } /// set a max stack size pub fn max_stack_size(mut self, size: u64) -> Self { self.opt_max_stack_size = Some(size); self } /// set a Garbage Collection interval, this will start a timer thread which will trigger a full GC every set interval pub fn gc_interval(mut self, interval: Duration) -> Self { self.opt_gc_interval = Some(interval); self } /// add an interrupt handler, this will be called several times during script execution and may be used to cancel a running script pub fn set_interrupt_handler<I: Fn(&QuickJsRuntimeAdapter) -> bool + Send + 'static>( mut self, interrupt_handler: I, ) -> Self { self.interrupt_handler = Some(Box::new(interrupt_handler)); self } } impl Default for QuickJsRuntimeBuilder { fn default() -> Self { QuickJsRuntimeBuilder::new() } } impl QuickJsRuntimeBuilder { pub fn runtime_facade_init_hook< H: FnOnce(&QuickJsRuntimeFacade) -> Result<(), JsError> + Send + 'static, >( mut self, hook: H, ) -> Self { self.runtime_init_hooks.push(Box::new(hook)); self } pub fn realm_adapter_init_hook< H: Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> Result<(), JsError> + Send + 'static, >( self, hook: H, ) -> Self { self.runtime_adapter_init_hook(move |rt| { rt.add_context_init_hook(hook)?; Ok(()) }) } pub fn runtime_adapter_init_hook< H: FnOnce(&QuickJsRuntimeAdapter) -> Result<(), JsError> + Send + 'static, >( self, hook: H, ) -> Self { self.runtime_facade_init_hook(|rt| { rt.exe_rt_task_in_event_loop(|rt| { let _ = hook(rt); }); Ok(()) }) } pub fn compiled_module_loader<S: CompiledModuleLoader + Send + 'static>( mut self, module_loader: S, ) -> Self { self.compiled_module_loaders.push(Box::new(module_loader)); self } } #[cfg(test)] pub mod tests { use crate::builder::QuickJsRuntimeBuilder; use crate::jsutils::modules::ScriptModuleLoader; use crate::jsutils::Script; use crate::quickjsrealmadapter::QuickJsRealmAdapter; #[test] fn test_module_loader() { crate::facades::tests::init_logging(); struct MyModuleLoader {} impl ScriptModuleLoader for MyModuleLoader { fn normalize_path( &self, _realm: &QuickJsRealmAdapter, _ref_path: &str, path: &str, ) -> Option<String> { Some(path.to_string()) } fn load_module(&self, _realm: &QuickJsRealmAdapter, _absolute_path: &str) -> String { "export const foo = 12;".to_string() } } let rt = QuickJsRuntimeBuilder::new() .script_module_loader(MyModuleLoader {}) .build(); match rt.eval_module_sync( None, Script::new( "test_module.es", "import {foo} from 'some_module.mes';\nconsole.log('foo = %s', foo);", ), ) { Ok(_) => {} Err(e) => panic!("script failed {}", e), } } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/lib.rs
src/lib.rs
//! # quickjs_runtime //! This crate consists of two main parts: //! * thread-safe utils and wrappers //! you can call these from any thread, all logic is directed to a single worker-thread(EventLoop) which invokes the quickjs API //! * quickjs bindings and utils //! these talk to the quickjs API directly and need to run in the same thread as the Runtime //! //! ## Noteworthy structs //! //! These are the structs you'll use the most //! //! | Thread safe (Facades) | Runtime Thread-local (Adapters) | //! | --- | --- | //! | [QuickJsRuntimeFacade](facades/struct.QuickJsRuntimeFacade.html) the 'starting point' | [QuickJsRuntimeAdapter](quickjsruntimeadapter/struct.QuickJsRuntimeAdapter.html) the wrapper for all things quickjs | //! | - | [QuickJsRealmAdapter](quickjsrealmadapter/struct.QuickJsRealmAdapter.html) a realm or context | //! | [JsValueFacade](https://hirofa.github.io/utils/hirofa_utils/js_utils/facades/values/enum.JsValueFacade.html) copy of- or reference to a value in the JsRuntimeAdapter | [QuickJsValueAdapter](quickjsvalueadapter/struct.QuickJsValueAdapter.html) reference counting pointer to a Value | //! //! ## Doing something in the runtime worker thread //! //! You always start with building a new [QuickjsRuntimeFacade](facades/struct.QuickjsRuntimeFacade.html) //! //! ```dontrun //! use quickjs_runtime::builder::QuickJsRuntimeBuilder; //! let rt: JsRuntimeFacade = QuickJsRuntimeBuilder::new().js_build(); //! ``` //! //! [QuickJsRuntimeFacade](facades/struct.QuickJsRuntimeFacade.html) has plenty public methods you can check out but one of the things you'll need to understand is how to communicate with the [QuickJsRuntimeAdapter](quickjsruntimeadapter/struct.QuickJsRuntimeAdapter.html) and the [QuickJsRealmAdapter](quickjsrealmadapter/struct.QuickJsRealmAdapter.html) //! This is done by adding a job to the [EventLoop](https://hirofa.github.io/utils/hirofa_utils/eventloop/struct.EventLoop.html) of the [QuickJsRuntimeFacade](facades/struct.QuickJsRuntimeFacade.html) //! //! ```dontrun //! // with the first Option you may specify which realm to use, None indicates the default or main realm //! let res = rt.loop_realm(None, |rt: QuickJsRuntimeAdapter, realm: QuickJsRealmAdapter| { //! // this will run in the Worker thread, here we can use the Adapters //! // since we passed None as realm the realm adapter will be the "main" realm //! return true; //! }).await; //! ``` //! All the non-sync functions return a Future so you can .await them from async functions. //! //! In order to do something and get the result synchronously you can use the sync variant //! ```dontrun //! use quickjs_runtime::quickjsruntime::QuickJsRuntime; //! let res = rt.loop_realm_sync(None, |rt, realm| { //! // this will run in the Worker thread, here we can use the quickjs API //! return 1; //! }); //! ``` //! //! One last thing you need to know is how to pass values from the js engine out of the worker thread //! //! This is where the JsValueFacade comes in //! //! ```dontrun //! //! // init a simple function //! rt.eval(Script::new("init_func.js", "globalThis.myObj = {someMember: {someFunction: function(input){return(input + " > hello rust!");}}};")).await; //! //! // create an input variable by using one of the constructor methods of the JsValueFacade //! let input_facade = JsValueFacade::new_str("hello js!"); //! // move it into a closure which will run in the worker thread //! let res = rt.loop_realm(None, move |rt: JsRuntimeAdapter, realm: JsRealmAdapter| { //! // convert the input JsValueFacade to JsValueAdapter //! let input_adapter = realm.from_js_value_facade(input_facade)?; //! // call myObj.someMember.someFunction(); //! let result_adapter = realm.invoke_function_by_name(&["myObj", "someMember"], "someFunction", &[input_adapter])?; //! // convert adapter to facade again so it may move out of the worker thread //! return realm.to_js_value_facade(&result_adapter); //! }).await; //! assert_eq!(res.get_str(), "hello_js! > hello rust!"); //! ``` //! //! For more details and examples please explore the packages below #[macro_use] extern crate lazy_static; extern crate core; pub mod builder; pub mod facades; #[cfg(any( feature = "settimeout", feature = "setinterval", feature = "console", feature = "setimmediate" ))] pub mod features; pub mod jsutils; pub mod quickjs_utils; pub mod quickjsrealmadapter; pub mod quickjsruntimeadapter; pub mod quickjsvalueadapter; pub mod reflection; #[cfg(feature = "typescript")] pub mod typescript; pub mod values; pub use libquickjs_sys; #[cfg(test)] pub mod tests { use crate::builder::QuickJsRuntimeBuilder; use crate::facades::tests::init_test_rt; use crate::facades::QuickJsRuntimeFacade; use crate::jsutils::jsproxies::JsProxy; use crate::jsutils::{JsError, Script}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::values::{JsValueConvertable, JsValueFacade}; use futures::executor::block_on; use std::thread; use std::time::Duration; #[test] fn test_examples() { let rt = QuickJsRuntimeBuilder::new().build(); let outcome = block_on(run_examples(&rt)); if outcome.is_err() { log::error!("an error occured: {}", outcome.err().unwrap()); } log::info!("done"); } #[test] fn test_st() { let rt = init_test_rt(); let _res = rt .eval_sync( None, Script::new( "t.js", r#" async function a(){ await b(); } async function b(){ throw Error("poof"); } a().then(() => { console.log("a done"); }).catch(() => { console.log("a error"); }); 1 "#, ), ) .expect("script failed"); thread::sleep(Duration::from_secs(1)); } async fn take_long() -> i32 { std::thread::sleep(Duration::from_millis(500)); 537 } async fn run_examples(rt: &QuickJsRuntimeFacade) -> Result<(), JsError> { // ensure console.log calls get outputted //simple_logging::log_to_stderr(LevelFilter::Info); // do a simple eval on the main realm let eval_res = rt.eval(None, Script::new("simple_eval.js", "2*7;")).await?; log::info!("simple eval:{}", eval_res.get_i32()); // invoke a JS method from rust let meth_res = rt .invoke_function(None, &["Math"], "round", vec![12.321.to_js_value_facade()]) .await?; log::info!("Math.round(12.321) = {}", meth_res.get_i32()); // add a rust function to js as a callback let cb = JsValueFacade::new_callback(|args| { let a = args[0].get_i32(); let b = args[1].get_i32(); log::info!("rust cb was called with a:{} and b:{}", a, b); Ok(JsValueFacade::Null) }); rt.invoke_function( None, &[], "setTimeout", vec![ cb, 10.to_js_value_facade(), 12.to_js_value_facade(), 13.to_js_value_facade(), ], ) .await?; std::thread::sleep(Duration::from_millis(20)); log::info!("rust cb should have been called by now"); // create simple proxy class with an async function rt.loop_realm_sync(None, |_rt_adapter, realm_adapter| { let proxy = JsProxy::new() .namespace(&["com", "mystuff"]) .name("MyProxy") .static_method( "doSomething", |_rt_adapter, realm_adapter: &QuickJsRealmAdapter, _args| { realm_adapter.create_resolving_promise_async( async { Ok(take_long().await) }, |realm_adapter, producer_result| { realm_adapter.create_i32(producer_result) }, ) }, ); realm_adapter .install_proxy(proxy, true) .expect("could not install proxy"); }); rt.eval( None, Script::new( "testMyProxy.js", "async function a() {\ console.log('a called at %s ms', new Date().getTime());\ let res = await com.mystuff.MyProxy.doSomething();\ console.log('a got result %s at %s ms', res, new Date().getTime());\ }; a();", ), ) .await?; std::thread::sleep(Duration::from_millis(600)); log::info!("a should have been called by now"); Ok(()) } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjsvalueadapter.rs
src/quickjsvalueadapter.rs
//! JSValueRef is a wrapper for quickjs's JSValue. it provides automatic reference counting making it safer to use use crate::jsutils::{JsError, JsValueType}; use crate::quickjs_utils::typedarrays::is_typed_array; use crate::quickjs_utils::{arrays, errors, functions, primitives, promises}; use crate::reflection::is_proxy_instance; use libquickjs_sys as q; use std::hash::{Hash, Hasher}; use std::ptr::null_mut; #[allow(clippy::upper_case_acronyms)] pub struct QuickJsValueAdapter { pub(crate) context: *mut q::JSContext, value: q::JSValue, ref_ct_decr_on_drop: bool, label: String, } impl Hash for QuickJsValueAdapter { fn hash<H: Hasher>(&self, state: &mut H) { let self_u = self.value.u; if self.is_i32() || self.is_bool() { unsafe { self_u.int32.hash(state) }; } else if self.is_f64() { unsafe { (self_u.float64 as i32).hash(state) }; } else { unsafe { self_u.ptr.hash(state) }; } } } impl PartialEq for QuickJsValueAdapter { fn eq(&self, other: &Self) -> bool { if self.get_tag() != other.get_tag() { false } else { let self_u = self.value.u; let other_u = other.value.u; unsafe { self_u.int32 == other_u.int32 && self_u.float64 == other_u.float64 && self_u.ptr == other_u.ptr } } } } impl Eq for QuickJsValueAdapter {} impl QuickJsValueAdapter { #[allow(dead_code)] pub(crate) fn label(&mut self, label: &str) { self.label = label.to_string() } } impl Clone for QuickJsValueAdapter { fn clone(&self) -> Self { Self::new( self.context, self.value, true, true, format!("clone of {}", self.label).as_str(), ) } } impl Drop for QuickJsValueAdapter { fn drop(&mut self) { //log::debug!( // "dropping OwnedValueRef, before free: {}, ref_ct: {}, tag: {}", // self.label, // self.get_ref_count(), // self.value.tag //); // All tags < 0 are garbage collected and need to be freed. if self.value.tag < 0 { // This transmute is OK since if tag < 0, the union will be a refcount // pointer. if self.ref_ct_decr_on_drop { #[cfg(feature = "bellard")] if self.get_ref_count() <= 0 { log::error!( "dropping ref while refcount already 0, which is bad mmkay.. {}", self.label ); panic!( "dropping ref while refcount already 0, which is bad mmkay.. {}", self.label ); } self.decrement_ref_count(); } } //log::trace!("dropping OwnedValueRef, after free",); } } impl std::fmt::Debug for QuickJsValueAdapter { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self.value.tag { TAG_EXCEPTION => write!(f, "Exception(?)"), TAG_NULL => write!(f, "NULL"), TAG_UNDEFINED => write!(f, "UNDEFINED"), TAG_BOOL => write!(f, "Bool(?)",), TAG_INT => write!(f, "Int(?)"), TAG_FLOAT64 => write!(f, "Float(?)"), TAG_STRING => write!(f, "String(?)"), #[cfg(feature = "bellard")] TAG_STRING_ROPE => write!(f, "String(?)"), TAG_OBJECT => write!(f, "Object(?)"), TAG_MODULE => write!(f, "Module(?)"), TAG_BIG_INT => write!(f, "BigInt(?)"), _ => write!(f, "Unknown Tag(?)"), } } } impl QuickJsValueAdapter { pub(crate) fn increment_ref_count(&self) { if self.get_tag() < 0 { unsafe { #[allow(clippy::let_unit_value)] let _ = libquickjs_sys::JS_DupValue(self.context, *self.borrow_value()); } } } pub(crate) fn decrement_ref_count(&self) { if self.get_tag() < 0 { unsafe { libquickjs_sys::JS_FreeValue(self.context, *self.borrow_value()) } } } pub fn get_tag(&self) -> i64 { self.value.tag } pub fn new_no_context(value: q::JSValue, label: &str) -> Self { Self { context: null_mut(), value, ref_ct_decr_on_drop: false, label: label.to_string(), } } pub fn new( context: *mut q::JSContext, value: q::JSValue, ref_ct_incr: bool, ref_ct_decr_on_drop: bool, label: &str, ) -> Self { debug_assert!(!label.is_empty()); let s = Self { context, value, ref_ct_decr_on_drop, label: label.to_string(), }; if ref_ct_incr { s.increment_ref_count(); } s } #[cfg(feature = "bellard")] pub fn get_ref_count(&self) -> i32 { if self.get_tag() < 0 { // This transmute is OK since if tag < 0, the union will be a refcount // pointer. let ptr = unsafe { self.value.u.ptr as *mut q::JSRefCountHeader }; let pref: &mut q::JSRefCountHeader = &mut unsafe { *ptr }; pref.ref_count } else { -1 } } /// borrow the value but first increment the refcount, this is useful for when the value is returned or passed to functions pub fn clone_value_incr_rc(&self) -> q::JSValue { self.increment_ref_count(); self.value } pub fn borrow_value(&self) -> &q::JSValue { &self.value } pub fn borrow_value_mut(&mut self) -> &mut q::JSValue { &mut self.value } pub fn is_null_or_undefined(&self) -> bool { self.is_null() || self.is_undefined() } /// return true if the wrapped value represents a JS null value pub fn is_undefined(&self) -> bool { unsafe { q::JS_IsUndefined(self.value) } } /// return true if the wrapped value represents a JS null value pub fn is_null(&self) -> bool { unsafe { q::JS_IsNull(self.value) } } /// return true if the wrapped value represents a JS boolean value pub fn is_bool(&self) -> bool { unsafe { q::JS_IsBool(self.value) } } /// return true if the wrapped value represents a JS INT value pub fn is_i32(&self) -> bool { // todo figure out diff between i32/f64/Number // unsafe { q::JS_IsNumber(self.borrow_value()) } self.borrow_value().tag == TAG_INT } /// return true if the wrapped value represents a Module pub fn is_module(&self) -> bool { self.borrow_value().tag == TAG_MODULE } /// return true if the wrapped value represents a compiled function pub fn is_compiled_function(&self) -> bool { self.borrow_value().tag == TAG_FUNCTION_BYTECODE } /// return true if the wrapped value represents a JS F64 value pub fn is_f64(&self) -> bool { self.borrow_value().tag == TAG_FLOAT64 } pub fn is_big_int(&self) -> bool { // unsafe { q::JS_IsBigInt(ctx, self.borrow_value()) } self.borrow_value().tag == TAG_BIG_INT || self.borrow_value().tag == TAG_SHORT_BIG_INT } /// return true if the wrapped value represents a JS Exception value pub fn is_exception(&self) -> bool { unsafe { q::JS_IsException(self.value) } } /// return true if the wrapped value represents a JS Object value pub fn is_object(&self) -> bool { unsafe { q::JS_IsObject(self.value) } } /// return true if the wrapped value represents a JS String value pub fn is_string(&self) -> bool { unsafe { q::JS_IsString(self.value) } } } pub(crate) const TAG_BIG_INT: i64 = libquickjs_sys::JS_TAG_BIG_INT as i64; pub(crate) const TAG_SHORT_BIG_INT: i64 = libquickjs_sys::JS_TAG_SHORT_BIG_INT as i64; pub(crate) const TAG_STRING: i64 = libquickjs_sys::JS_TAG_STRING as i64; #[cfg(feature = "bellard")] pub(crate) const TAG_STRING_ROPE: i64 = libquickjs_sys::JS_TAG_STRING_ROPE as i64; pub(crate) const TAG_MODULE: i64 = libquickjs_sys::JS_TAG_MODULE as i64; pub(crate) const TAG_FUNCTION_BYTECODE: i64 = libquickjs_sys::JS_TAG_FUNCTION_BYTECODE as i64; pub(crate) const TAG_OBJECT: i64 = libquickjs_sys::JS_TAG_OBJECT as i64; pub(crate) const TAG_INT: i64 = libquickjs_sys::JS_TAG_INT as i64; pub(crate) const TAG_BOOL: i64 = libquickjs_sys::JS_TAG_BOOL as i64; pub(crate) const TAG_NULL: i64 = libquickjs_sys::JS_TAG_NULL as i64; pub(crate) const TAG_UNDEFINED: i64 = libquickjs_sys::JS_TAG_UNDEFINED as i64; pub(crate) const TAG_EXCEPTION: i64 = libquickjs_sys::JS_TAG_EXCEPTION as i64; pub(crate) const TAG_FLOAT64: i64 = libquickjs_sys::JS_TAG_FLOAT64 as i64; impl QuickJsValueAdapter { pub fn is_function(&self) -> bool { self.is_object() && self.get_js_type() == JsValueType::Function } pub fn is_array(&self) -> bool { self.is_object() && self.get_js_type() == JsValueType::Array } pub fn is_error(&self) -> bool { self.is_object() && self.get_js_type() == JsValueType::Error } pub fn is_promise(&self) -> bool { self.is_object() && self.get_js_type() == JsValueType::Promise } pub fn get_js_type(&self) -> JsValueType { match self.get_tag() { TAG_EXCEPTION => JsValueType::Error, TAG_NULL => JsValueType::Null, TAG_UNDEFINED => JsValueType::Undefined, TAG_BOOL => JsValueType::Boolean, TAG_INT => JsValueType::I32, TAG_FLOAT64 => JsValueType::F64, TAG_STRING => JsValueType::String, #[cfg(feature = "bellard")] TAG_STRING_ROPE => JsValueType::String, TAG_OBJECT => { // todo get classProto.name and match // if bellard, match on classid if unsafe { functions::is_function(self.context, self) } { JsValueType::Function } else if unsafe { errors::is_error(self.context, self) } { JsValueType::Error } else if unsafe { arrays::is_array(self.context, self) } { JsValueType::Array } else if unsafe { promises::is_promise(self.context, self) } { JsValueType::Promise } else { JsValueType::Object } } TAG_BIG_INT | TAG_SHORT_BIG_INT => JsValueType::BigInt, TAG_MODULE => todo!(), _ => JsValueType::Undefined, } } pub fn is_typed_array(&self) -> bool { self.is_object() && unsafe { is_typed_array(self.context, self) } } pub fn is_proxy_instance(&self) -> bool { self.is_object() && unsafe { is_proxy_instance(self.context, self) } } pub fn type_of(&self) -> &'static str { match self.get_tag() { TAG_BIG_INT => "bigint", TAG_STRING => "string", #[cfg(feature = "bellard")] TAG_STRING_ROPE => "string", TAG_MODULE => "module", TAG_FUNCTION_BYTECODE => "function", TAG_OBJECT => { if self.get_js_type() == JsValueType::Function { "function" } else { "object" } } TAG_INT => "number", TAG_BOOL => "boolean", TAG_NULL => "object", TAG_UNDEFINED => "undefined", TAG_EXCEPTION => "object", TAG_FLOAT64 => "number", _ => "unknown", } } pub fn to_bool(&self) -> bool { if self.get_js_type() == JsValueType::Boolean { primitives::to_bool(self).expect("could not convert bool to bool") } else { panic!("not a boolean"); } } pub fn to_i32(&self) -> i32 { if self.get_js_type() == JsValueType::I32 { primitives::to_i32(self).expect("could not convert to i32") } else { panic!("not an i32"); } } pub fn to_f64(&self) -> f64 { if self.get_js_type() == JsValueType::F64 { primitives::to_f64(self).expect("could not convert to f64") } else { panic!("not a f64"); } } pub fn to_string(&self) -> Result<String, JsError> { match self.get_js_type() { JsValueType::I32 => Ok(self.to_i32().to_string()), JsValueType::F64 => Ok(self.to_f64().to_string()), JsValueType::String => unsafe { primitives::to_string(self.context, self) }, JsValueType::Boolean => { if self.to_bool() { Ok("true".to_string()) } else { Ok("false".to_string()) } } JsValueType::Error => { let js_error = unsafe { errors::error_to_js_error(self.context, self) }; Ok(format!("{js_error}")) } _ => unsafe { functions::call_to_string(self.context, self) }, } } } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::{JsValueType, Script}; #[test] fn test_to_str() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let res = q_ctx.eval(Script::new("test_to_str.es", "('hello ' + 'world');")); match res { Ok(res) => { log::info!("script ran ok: {:?}", res); assert!(res.get_js_type() == JsValueType::String); assert_eq!(res.to_string().expect("str conv failed"), "hello world"); } Err(e) => { log::error!("script failed: {}", e); panic!("script failed"); } } }); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/values.rs
src/values.rs
use crate::facades::QuickjsRuntimeFacadeInner; use crate::jsutils::{JsError, JsValueType}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use crate::reflection::JsProxyInstanceId; use futures::executor::block_on; use futures::Future; use hirofa_utils::debug_mutex::DebugMutex; use serde::Serialize; use serde_json::Value; use std::collections::HashMap; use std::error::Error; use std::fmt::{Debug, Formatter}; use std::pin::Pin; use std::sync::atomic::{AtomicU16, Ordering}; use std::sync::{Arc, Weak}; use std::time::Duration; use string_cache::DefaultAtom; pub struct CachedJsObjectRef { pub(crate) id: i32, rti: Weak<QuickjsRuntimeFacadeInner>, realm_id: String, drop_action: DebugMutex<Option<Box<dyn FnOnce() + Send>>>, } pub struct CachedJsPromiseRef { pub cached_object: CachedJsObjectRef, } pub struct CachedJsArrayRef { pub cached_object: CachedJsObjectRef, } pub struct CachedJsFunctionRef { pub cached_object: CachedJsObjectRef, } impl CachedJsObjectRef { pub(crate) fn new(realm: &QuickJsRealmAdapter, obj: QuickJsValueAdapter) -> Self { let id = realm.cache_object(obj); let rti_ref = realm.get_runtime_facade_inner(); let drop_id = id; let drop_realm_name = realm.get_realm_id().to_string(); Self::new2( id, rti_ref.clone(), realm.get_realm_id().to_string(), move || { if let Some(rti) = rti_ref.upgrade() { rti.add_rt_task_to_event_loop_void(move |rt| { if let Some(realm) = rt.get_realm(drop_realm_name.as_str()) { realm.dispose_cached_object(drop_id); } }) } }, ) } fn new2<F: FnOnce() + Send + 'static>( id: i32, rti: Weak<QuickjsRuntimeFacadeInner>, realm_name: String, drop_action: F, ) -> Self { Self { id, rti, realm_id: realm_name, drop_action: DebugMutex::new( Some(Box::new(drop_action)), "CachedJsObjectRef.drop_action", ), } } pub async fn to_json_string(&self) -> Result<String, JsError> { let id = self.id; let realm_name = self.realm_id.clone(); let rti = self.rti.upgrade().expect("invalid state"); rti.add_rt_task_to_event_loop(move |rt| { if let Some(realm) = rt.get_realm(realm_name.as_str()) { //let realm: JsRealmAdapter<JsRuntimeAdapterType = (), JsValueAdapterType = ()> = realm; realm.with_cached_object(id, |obj| realm.json_stringify(obj, None)) } else { Err(JsError::new_str("no such realm")) } }) .await } pub fn get_object_sync(&self) -> Result<HashMap<String, JsValueFacade>, JsError> { block_on(self.get_object()) } pub async fn get_object(&self) -> Result<HashMap<String, JsValueFacade>, JsError> { let id = self.id; let realm_name = self.realm_id.clone(); let rti = self.rti.upgrade().expect("invalid state"); rti.add_rt_task_to_event_loop(move |rt| { if let Some(realm) = rt.get_realm(realm_name.as_str()) { //let realm: JsRealmAdapter = realm; let mut ret = HashMap::new(); let results = realm.with_cached_object(id, |obj| { realm.traverse_object(obj, |name, value| { // Ok((name.to_string(), realm.to_js_value_facade(value))) }) })?; for result in results { ret.insert(result.0, result.1?); } Ok(ret) } else { Err(JsError::new_str("no such realm")) } }) .await } pub async fn get_serde_value(&self) -> Result<serde_json::Value, JsError> { let id = self.id; let realm_name = self.realm_id.clone(); let rti = self.rti.upgrade().expect("invalid state"); rti.add_rt_task_to_event_loop(move |rt| { if let Some(realm) = rt.get_realm(realm_name.as_str()) { realm.with_cached_object(id, |obj| realm.value_adapter_to_serde_value(obj)) } else { Err(JsError::new_str("no such realm")) } }) .await } pub fn with_obj_sync< S: Send + 'static, C: FnOnce(&QuickJsRealmAdapter, &QuickJsValueAdapter) -> S + Send + 'static, >( &self, consumer: C, ) -> Result<S, JsError> { let id = self.id; let realm_id = self.realm_id.clone(); let rti = self.rti.upgrade().expect("invalid state"); rti.exe_rt_task_in_event_loop(move |rt| { if let Some(realm) = rt.get_realm(realm_id.as_str()) { Ok(realm.with_cached_object(id, |obj| consumer(realm, obj))) } else { Err(JsError::new_str("Realm was disposed")) } }) } pub fn with_obj_void< S: Send + 'static, C: FnOnce(&QuickJsRealmAdapter, &QuickJsValueAdapter) -> S + Send + 'static, >( &self, consumer: C, ) { let id = self.id; let realm_id = self.realm_id.clone(); let rti = self.rti.upgrade().expect("invalid state"); rti.add_rt_task_to_event_loop_void(move |rt| { if let Some(realm) = rt.get_realm(realm_id.as_str()) { realm.with_cached_object(id, |obj| consumer(realm, obj)); } else { log::error!("no such realm"); } }) } pub async fn with_obj< S: Send + 'static, C: FnOnce(&QuickJsRealmAdapter, &QuickJsValueAdapter) -> S + Send + 'static, >( &self, consumer: C, ) -> Result<S, JsError> { let id = self.id; let realm_id = self.realm_id.clone(); let rti = self.rti.upgrade().expect("invalid state"); rti.add_rt_task_to_event_loop(move |rt| { if let Some(realm) = rt.get_realm(realm_id.as_str()) { Ok(realm.with_cached_object(id, |obj| consumer(realm, obj))) } else { Err(JsError::new_str("Realm was disposed")) } }) .await } } impl Drop for CachedJsObjectRef { fn drop(&mut self) { let lck = &mut *self.drop_action.lock("drop").unwrap(); if let Some(da) = lck.take() { da(); } } } impl CachedJsPromiseRef { pub async fn get_serde_value(&self) -> Result<serde_json::Value, JsError> { self.cached_object.get_serde_value().await } pub async fn to_json_string(&self) -> Result<String, JsError> { self.cached_object.to_json_string().await } pub fn get_promise_result_sync(&self) -> Result<Result<JsValueFacade, JsValueFacade>, JsError> { let rx = self.get_promise_result_receiver(); rx.recv() .map_err(|e| JsError::new_string(format!("get_promise_result_sync/1: {e}")))? } pub fn get_promise_result_sync_timeout( &self, timeout: Option<Duration>, ) -> Result<Result<JsValueFacade, JsValueFacade>, JsError> { let rx = self.get_promise_result_receiver(); let res = if let Some(timeout) = timeout { rx.recv_timeout(timeout) .map_err(|e| JsError::new_string(format!("get_promise_result_sync_timeout/1: {e}"))) } else { rx.recv() .map_err(|e| JsError::new_string(format!("get_promise_result_sync_timeout/2: {e}"))) }; res? } pub async fn get_promise_result( &self, ) -> Result<Result<JsValueFacade, JsValueFacade>, JsError> { let rx = self.get_promise_result_receiver(); rx.into_recv_async() .await .map_err(|e| JsError::new_string(format!("{e}")))? } pub fn get_promise_result_receiver( &self, ) -> flume::Receiver<Result<Result<JsValueFacade, JsValueFacade>, JsError>> { let (tx, rx) = flume::bounded(1); let tx1 = tx.clone(); let tx2 = tx.clone(); let state = Arc::new(AtomicU16::new(0)); let state_then = state.clone(); let state_catch = state.clone(); self.cached_object.with_obj_void(move |realm, obj| { let res = || { let then_func = realm.create_function( "then", move |realm, _this, args| { // state_then.fetch_add(1, Ordering::Relaxed); let resolution = &args[0]; let send_res = match realm.to_js_value_facade(resolution) { Ok(vf) => tx1.send(Ok(Ok(vf))), Err(conv_err) => tx1.send(Err(conv_err)), }; send_res.map_err(|e| { JsError::new_string(format!( "could not send: {e} state:{}", state_then.load(Ordering::Relaxed) )) })?; realm.create_undefined() }, 1, )?; let catch_func = realm.create_function( "catch", move |realm, _this, args| { // state_catch.fetch_add(16, Ordering::Relaxed); let rejection = &args[0]; let send_res = match realm.to_js_value_facade(rejection) { Ok(vf) => tx2.send(Ok(Err(vf))), Err(conv_err) => tx2.send(Err(conv_err)), }; send_res.map_err(|e| { JsError::new_string(format!( "could not send: {e} state:{}", state_catch.load(Ordering::Relaxed) )) })?; realm.create_undefined() }, 1, )?; realm.add_promise_reactions(obj, Some(then_func), Some(catch_func), None)?; Ok(()) }; match res() { Ok(_) => {} Err(e) => { state.fetch_add(64, Ordering::Relaxed); log::error!("failed to add promise reactions {}", e); match tx.send(Err(e)) { Ok(_) => {} Err(e) => { log::error!("failed to resolve 47643: {}", e); } } } } }); rx } } impl CachedJsArrayRef { pub async fn get_serde_value(&self) -> Result<serde_json::Value, JsError> { self.cached_object.get_serde_value().await } pub async fn to_json_string(&self) -> Result<String, JsError> { self.cached_object.to_json_string().await } pub async fn get_array(&self) -> Result<Vec<JsValueFacade>, JsError> { self.cached_object .with_obj(|realm, arr| { let mut vec: Vec<JsValueFacade> = vec![]; realm.traverse_array_mut(arr, |_index, element| { vec.push(realm.to_js_value_facade(element)?); Ok(()) })?; Ok(vec) }) .await? } } impl CachedJsFunctionRef { pub async fn get_serde_value(&self) -> Result<serde_json::Value, JsError> { self.cached_object.get_serde_value().await } pub fn invoke_function( &self, args: Vec<JsValueFacade>, ) -> impl Future<Output = Result<JsValueFacade, JsError>> + Send { //Pin<Box<dyn futures::Future<Output = Result<JsValueFacade, JsError>>>> let cached_obj_id = self.cached_object.id; let realm_id = self.cached_object.realm_id.clone(); let rti = self.cached_object.rti.upgrade().expect("invalid state"); rti.add_rt_task_to_event_loop(move |rt| { // if let Some(realm) = rt.get_realm(realm_id.as_str()) { realm.with_cached_object(cached_obj_id, move |func_adapter| { let mut adapter_args = vec![]; for arg in args { adapter_args.push(realm.from_js_value_facade(arg)?); } let adapter_refs: Vec<&QuickJsValueAdapter> = adapter_args.iter().collect(); let val_adapter = realm.invoke_function(None, func_adapter, &adapter_refs)?; realm.to_js_value_facade(&val_adapter) }) } else { Ok(JsValueFacade::Null) } }) } pub fn invoke_function_sync(&self, args: Vec<JsValueFacade>) -> Result<JsValueFacade, JsError> { self.cached_object.with_obj_sync(|realm, func_adapter| { // let mut adapter_args = vec![]; for arg in args { adapter_args.push(realm.from_js_value_facade(arg)?); } let adapter_refs: Vec<&QuickJsValueAdapter> = adapter_args.iter().collect(); let val_adapter = realm.invoke_function(None, func_adapter, &adapter_refs)?; realm.to_js_value_facade(&val_adapter) })? } } pub enum TypedArrayType { Uint8, } /// The JsValueFacade is a Send-able representation of a value in the Script engine #[allow(clippy::type_complexity)] pub enum JsValueFacade { I32 { val: i32, }, F64 { val: f64, }, String { val: DefaultAtom, }, Boolean { val: bool, }, JsObject { // obj which is a ref to obj in Js cached_object: CachedJsObjectRef, }, JsPromise { cached_promise: CachedJsPromiseRef, }, JsArray { cached_array: CachedJsArrayRef, }, JsFunction { cached_function: CachedJsFunctionRef, }, // obj created from rust Object { val: HashMap<String, JsValueFacade>, }, // array created from rust Array { val: Vec<JsValueFacade>, }, // promise created from rust which will run an async producer Promise { producer: DebugMutex< Option<Pin<Box<dyn Future<Output = Result<JsValueFacade, JsError>> + Send + 'static>>>, >, }, // Function created from rust Function { name: String, arg_count: u32, func: Arc<Box<dyn Fn(&[JsValueFacade]) -> Result<JsValueFacade, JsError> + Send + Sync>>, }, JsError { val: JsError, }, ProxyInstance { namespace: &'static [&'static str], class_name: &'static str, instance_id: JsProxyInstanceId, }, TypedArray { buffer: Vec<u8>, array_type: TypedArrayType, }, JsonStr { json: String, }, SerdeValue { value: serde_json::Value, }, Null, Undefined, } impl JsValueFacade { pub fn from_serializable<T: Serialize>(obj: &T) -> Result<Self, Box<dyn Error>> { let json = serde_json::to_string(obj)?; Ok(Self::JsonStr { json }) } pub fn new_i32(val: i32) -> Self { Self::I32 { val } } pub fn new_f64(val: f64) -> Self { Self::F64 { val } } pub fn new_bool(val: bool) -> Self { Self::Boolean { val } } pub fn new_str_atom(val: DefaultAtom) -> Self { Self::String { val } } pub fn new_str(val: &str) -> Self { Self::String { val: DefaultAtom::from(val), } } pub fn new_string(val: String) -> Self { Self::String { val: DefaultAtom::from(val), } } pub fn new_callback< F: Fn(&[JsValueFacade]) -> Result<JsValueFacade, JsError> + Send + Sync + 'static, >( callback: F, ) -> Self { Self::Function { name: "".to_string(), arg_count: 0, func: Arc::new(Box::new(callback)), } } pub fn new_function< F: Fn(&[JsValueFacade]) -> Result<JsValueFacade, JsError> + Send + Sync + 'static, >( name: &str, function: F, arg_count: u32, ) -> Self { Self::Function { name: name.to_string(), arg_count, func: Arc::new(Box::new(function)), } } /// create a new promise with a producer which will run async in a threadpool pub fn new_promise<R, P, M>(producer: P) -> Self where P: Future<Output = Result<JsValueFacade, JsError>> + Send + 'static, { JsValueFacade::Promise { producer: DebugMutex::new(Some(Box::pin(producer)), "JsValueFacade::Promise.producer"), } } pub fn is_i32(&self) -> bool { matches!(self, JsValueFacade::I32 { .. }) } pub fn is_f64(&self) -> bool { matches!(self, JsValueFacade::F64 { .. }) } pub fn is_bool(&self) -> bool { matches!(self, JsValueFacade::Boolean { .. }) } pub fn is_string(&self) -> bool { matches!(self, JsValueFacade::String { .. }) } pub fn is_js_promise(&self) -> bool { matches!(self, JsValueFacade::JsPromise { .. }) } pub fn is_js_object(&self) -> bool { matches!(self, JsValueFacade::JsObject { .. }) } pub fn is_js_array(&self) -> bool { matches!(self, JsValueFacade::JsArray { .. }) } pub fn get_i32(&self) -> i32 { match self { JsValueFacade::I32 { val } => *val, _ => { panic!("Not an i32"); } } } pub fn get_f64(&self) -> f64 { match self { JsValueFacade::F64 { val } => *val, _ => { panic!("Not an f64"); } } } pub fn get_bool(&self) -> bool { match self { JsValueFacade::Boolean { val } => *val, _ => { panic!("Not a boolean"); } } } pub fn get_str(&self) -> &str { match self { JsValueFacade::String { val } => val, _ => { panic!("Not a string"); } } } pub fn get_str_atom(&self) -> &DefaultAtom { match self { JsValueFacade::String { val } => val, _ => { panic!("Not a string"); } } } pub fn is_null_or_undefined(&self) -> bool { matches!(self, JsValueFacade::Null | JsValueFacade::Undefined) } pub fn get_value_type(&self) -> JsValueType { match self { JsValueFacade::I32 { .. } => JsValueType::I32, JsValueFacade::F64 { .. } => JsValueType::F64, JsValueFacade::String { .. } => JsValueType::String, JsValueFacade::Boolean { .. } => JsValueType::Boolean, JsValueFacade::JsObject { .. } => JsValueType::Object, JsValueFacade::Null => JsValueType::Null, JsValueFacade::Undefined => JsValueType::Undefined, JsValueFacade::Object { .. } => JsValueType::Object, JsValueFacade::Array { .. } => JsValueType::Array, JsValueFacade::Promise { .. } => JsValueType::Promise, JsValueFacade::Function { .. } => JsValueType::Function, JsValueFacade::JsPromise { .. } => JsValueType::Promise, JsValueFacade::JsArray { .. } => JsValueType::Array, JsValueFacade::JsFunction { .. } => JsValueType::Function, JsValueFacade::JsError { .. } => JsValueType::Error, JsValueFacade::ProxyInstance { .. } => JsValueType::Object, JsValueFacade::TypedArray { .. } => JsValueType::Object, JsValueFacade::JsonStr { .. } => JsValueType::Object, JsValueFacade::SerdeValue { value } => match value { serde_json::Value::Null => JsValueType::Null, serde_json::Value::Bool(_) => JsValueType::Boolean, serde_json::Value::Number(_) => { if value.is_i64() { let num = value.as_i64().unwrap(); if num <= i32::MAX as i64 { JsValueType::I32 } else { JsValueType::F64 } } else if value.is_f64() { JsValueType::F64 } else { // u64 let num = value.as_u64().unwrap(); if num <= i32::MAX as u64 { JsValueType::I32 } else { JsValueType::F64 } } } serde_json::Value::String(_) => JsValueType::String, serde_json::Value::Array(_) => JsValueType::Array, serde_json::Value::Object(_) => JsValueType::Object, }, } } pub fn stringify(&self) -> String { match self { JsValueFacade::I32 { val } => { format!("I32: {val}") } JsValueFacade::F64 { val } => { format!("F64: {val}") } JsValueFacade::String { val } => { format!("String: {val}") } JsValueFacade::Boolean { val } => { format!("Boolean: {val}") } JsValueFacade::JsObject { cached_object } => { format!( "JsObject: [{}.{}]", cached_object.realm_id, cached_object.id ) } JsValueFacade::JsPromise { cached_promise } => { format!( "JsPromise: [{}.{}]", cached_promise.cached_object.realm_id, cached_promise.cached_object.id ) } JsValueFacade::JsArray { cached_array } => { format!( "JsArray: [{}.{}]", cached_array.cached_object.realm_id, cached_array.cached_object.id ) } JsValueFacade::JsFunction { cached_function } => { format!( "JsFunction: [{}.{}]", cached_function.cached_object.realm_id, cached_function.cached_object.id ) } JsValueFacade::Object { val } => { format!("Object: [len={}]", val.keys().len()) } JsValueFacade::Array { val } => { format!("Array: [len={}]", val.len()) } JsValueFacade::Promise { .. } => "Promise".to_string(), JsValueFacade::Function { .. } => "Function".to_string(), JsValueFacade::Null => "Null".to_string(), JsValueFacade::Undefined => "Undefined".to_string(), JsValueFacade::JsError { val } => format!("{val}"), JsValueFacade::ProxyInstance { .. } => "ProxyInstance".to_string(), JsValueFacade::TypedArray { .. } => "TypedArray".to_string(), JsValueFacade::JsonStr { json } => format!("JsonStr: '{json}'"), JsValueFacade::SerdeValue { value } => format!("Serde value: {value}"), } } pub async fn to_serde_value(&self) -> Result<serde_json::Value, JsError> { match self { JsValueFacade::I32 { val } => Ok(serde_json::Value::from(*val)), JsValueFacade::F64 { val } => Ok(serde_json::Value::from(*val)), JsValueFacade::String { val } => Ok(serde_json::Value::from(val.to_string())), JsValueFacade::Boolean { val } => Ok(serde_json::Value::from(*val)), JsValueFacade::JsObject { cached_object } => cached_object.get_serde_value().await, JsValueFacade::JsPromise { cached_promise } => cached_promise.get_serde_value().await, JsValueFacade::JsArray { cached_array } => cached_array.get_serde_value().await, JsValueFacade::JsFunction { .. } => Ok(Value::Null), JsValueFacade::Object { .. } => Ok(Value::Null), JsValueFacade::Array { .. } => Ok(Value::Null), JsValueFacade::Promise { .. } => Ok(Value::Null), JsValueFacade::Function { .. } => Ok(Value::Null), JsValueFacade::Null => Ok(Value::Null), JsValueFacade::Undefined => Ok(Value::Null), JsValueFacade::JsError { .. } => Ok(Value::Null), JsValueFacade::ProxyInstance { .. } => Ok(Value::Null), JsValueFacade::TypedArray { .. } => Ok(Value::Null), JsValueFacade::JsonStr { json } => Ok(serde_json::from_str(json).unwrap()), JsValueFacade::SerdeValue { value } => Ok(value.clone()), } } pub async fn to_json_string(&self) -> Result<String, JsError> { match self { JsValueFacade::I32 { val } => Ok(format!("{val}")), JsValueFacade::F64 { val } => Ok(format!("{val}")), JsValueFacade::String { val } => Ok(format!("'{}'", val.replace('\'', "\\'"))), JsValueFacade::Boolean { val } => Ok(format!("{val}")), JsValueFacade::JsObject { cached_object } => cached_object.to_json_string().await, JsValueFacade::JsPromise { cached_promise } => cached_promise.to_json_string().await, JsValueFacade::JsArray { cached_array } => cached_array.to_json_string().await, JsValueFacade::JsFunction { .. } => Ok("function () {}".to_string()), JsValueFacade::Object { .. } => Ok("{}".to_string()), JsValueFacade::Array { .. } => Ok("{}".to_string()), JsValueFacade::Promise { .. } => Ok("{}".to_string()), JsValueFacade::Function { .. } => Ok("function () {}".to_string()), JsValueFacade::Null => Ok("null".to_string()), JsValueFacade::Undefined => Ok("undefined".to_string()), JsValueFacade::JsError { val } => Ok(format!("'{val}'")), JsValueFacade::ProxyInstance { .. } => Ok("{}".to_string()), JsValueFacade::TypedArray { .. } => Ok("[]".to_string()), JsValueFacade::JsonStr { json } => Ok(json.clone()), JsValueFacade::SerdeValue { value } => Ok(serde_json::to_string(value).unwrap()), } } } impl Debug for JsValueFacade { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(self.stringify().as_str()) } } pub trait JsValueConvertable { fn to_js_value_facade(self) -> JsValueFacade; } impl JsValueConvertable for serde_json::Value { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::SerdeValue { value: self } } } impl JsValueConvertable for bool { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::new_bool(self) } } impl JsValueConvertable for i32 { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::new_i32(self) } } impl JsValueConvertable for f64 { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::new_f64(self) } } impl JsValueConvertable for &str { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::new_str(self) } } impl JsValueConvertable for String { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::new_string(self) } } impl JsValueConvertable for Vec<u8> { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::TypedArray { buffer: self, array_type: TypedArrayType::Uint8, } } } impl JsValueConvertable for Vec<JsValueFacade> { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::Array { val: self } } } impl JsValueConvertable for HashMap<String, JsValueFacade> { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::Object { val: self } } } /* todo impl JsValueConvertable for Fn(&[JsValueFacade]) -> Result<JsValueFacade, JsError> + Send + Sync { fn to_js_value_facade(self) -> JsValueFacade { JsValueFacade::Function { name: "".to_string(), arg_count: 0, func: Arc::new(Box::new(self)), } } } */
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjsruntimeadapter.rs
src/quickjsruntimeadapter.rs
// store in thread_local use crate::facades::QuickjsRuntimeFacadeInner; use crate::jsutils::modules::{CompiledModuleLoader, NativeModuleLoader, ScriptModuleLoader}; use crate::jsutils::{JsError, Script, ScriptPreProcessor}; use crate::quickjs_utils::compile::from_bytecode; use crate::quickjs_utils::modules::{ add_module_export, compile_module, get_module_def, get_module_name, new_module, set_module_export, }; use crate::quickjs_utils::runtime::new_class_id; use crate::quickjs_utils::{gc, interrupthandler, modules, promises}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use libquickjs_sys as q; use serde::Serialize; use std::cell::RefCell; use std::collections::HashMap; use std::ffi::CString; use std::fmt::{Debug, Formatter}; use std::os::raw::c_int; use std::panic; use std::sync::{Arc, Weak}; /// this is the internal abstract loader which is used to actually load the modules pub trait ModuleLoader { /// the normalize methods is used to translate a possible relative path to an absolute path of a module /// it doubles as a method to see IF a module can actually be loaded by a module loader (return None if the module can not be found) fn normalize_path( &self, q_ctx: &QuickJsRealmAdapter, ref_path: &str, path: &str, ) -> Option<String>; /// load the Module fn load_module( &self, q_ctx: &QuickJsRealmAdapter, absolute_path: &str, ) -> Result<*mut q::JSModuleDef, JsError>; /// has module is used to check if a loader can provide a certain module, this is currently used to check which loader should init a native module fn has_module(&self, q_ctx: &QuickJsRealmAdapter, absolute_path: &str) -> bool; /// init a module, currently used to init native modules /// # Safety /// be safe with the moduledef ptr unsafe fn init_module( &self, q_ctx: &QuickJsRealmAdapter, module: *mut q::JSModuleDef, ) -> Result<(), JsError>; } // these are the external (util) loaders (todo move these to esruntime?) pub struct CompiledModuleLoaderAdapter { inner: Box<dyn CompiledModuleLoader>, } impl CompiledModuleLoaderAdapter { pub fn new(loader: Box<dyn CompiledModuleLoader>) -> Self { Self { inner: loader } } } pub struct ScriptModuleLoaderAdapter { inner: Box<dyn ScriptModuleLoader>, } impl ScriptModuleLoaderAdapter { pub fn new(loader: Box<dyn ScriptModuleLoader>) -> Self { Self { inner: loader } } } impl ModuleLoader for CompiledModuleLoaderAdapter { fn normalize_path( &self, q_ctx: &QuickJsRealmAdapter, ref_path: &str, path: &str, ) -> Option<String> { self.inner.normalize_path(q_ctx, ref_path, path) } fn load_module( &self, q_ctx: &QuickJsRealmAdapter, absolute_path: &str, ) -> Result<*mut q::JSModuleDef, JsError> { let bytes = self.inner.load_module(q_ctx, absolute_path); let compiled_module = unsafe { from_bytecode(q_ctx.context, &bytes)? }; Ok(get_module_def(&compiled_module)) } fn has_module(&self, q_ctx: &QuickJsRealmAdapter, absolute_path: &str) -> bool { self.normalize_path(q_ctx, absolute_path, absolute_path) .is_some() } unsafe fn init_module( &self, _q_ctx: &QuickJsRealmAdapter, _module: *mut q::JSModuleDef, ) -> Result<(), JsError> { Ok(()) } } impl ModuleLoader for ScriptModuleLoaderAdapter { fn normalize_path( &self, realm: &QuickJsRealmAdapter, ref_path: &str, path: &str, ) -> Option<String> { self.inner.normalize_path(realm, ref_path, path) } fn load_module( &self, realm: &QuickJsRealmAdapter, absolute_path: &str, ) -> Result<*mut q::JSModuleDef, JsError> { log::trace!("load_module"); let code = self.inner.load_module(realm, absolute_path); let mut script = Script::new(absolute_path, code.as_str()); script = QuickJsRuntimeAdapter::pre_process(script)?; log::trace!("load_module / 2"); let compiled_module = unsafe { compile_module(realm.context, script)? }; log::trace!("load_module / 3"); Ok(get_module_def(&compiled_module)) } fn has_module(&self, q_ctx: &QuickJsRealmAdapter, absolute_path: &str) -> bool { self.normalize_path(q_ctx, absolute_path, absolute_path) .is_some() } unsafe fn init_module( &self, _q_ctx: &QuickJsRealmAdapter, _module: *mut q::JSModuleDef, ) -> Result<(), JsError> { Ok(()) } } pub struct NativeModuleLoaderAdapter { inner: Box<dyn NativeModuleLoader>, } impl NativeModuleLoaderAdapter { pub fn new(loader: Box<dyn NativeModuleLoader>) -> Self { Self { inner: loader } } } impl ModuleLoader for NativeModuleLoaderAdapter { fn normalize_path( &self, q_ctx: &QuickJsRealmAdapter, _ref_path: &str, path: &str, ) -> Option<String> { if self.inner.has_module(q_ctx, path) { Some(path.to_string()) } else { None } } fn load_module( &self, q_ctx: &QuickJsRealmAdapter, absolute_path: &str, ) -> Result<*mut q::JSModuleDef, JsError> { // create module let module = unsafe { new_module(q_ctx.context, absolute_path, Some(native_module_init))? }; for name in self.inner.get_module_export_names(q_ctx, absolute_path) { unsafe { add_module_export(q_ctx.context, module, name)? } } //std::ptr::null_mut() Ok(module) } fn has_module(&self, q_ctx: &QuickJsRealmAdapter, absolute_path: &str) -> bool { self.inner.has_module(q_ctx, absolute_path) } unsafe fn init_module( &self, q_ctx: &QuickJsRealmAdapter, module: *mut q::JSModuleDef, ) -> Result<(), JsError> { let module_name = get_module_name(q_ctx.context, module)?; for (name, val) in self.inner.get_module_exports(q_ctx, module_name.as_str()) { set_module_export(q_ctx.context, module, name, val)?; } Ok(()) } } unsafe extern "C" fn native_module_init( ctx: *mut q::JSContext, module: *mut q::JSModuleDef, ) -> c_int { let module_name = get_module_name(ctx, module).expect("could not get name"); log::trace!("native_module_init: {}", module_name); QuickJsRuntimeAdapter::do_with(|q_js_rt| { QuickJsRealmAdapter::with_context(ctx, |q_ctx| { q_js_rt .with_all_module_loaders(|module_loader| { if module_loader.has_module(q_ctx, module_name.as_str()) { match module_loader.init_module(q_ctx, module) { Ok(_) => { Some(0) // ok } Err(e) => { q_ctx.report_ex( format!( "Failed to init native module: {module_name} caused by {e}" ) .as_str(), ); Some(1) } } } else { None } }) .unwrap_or(0) }) }) } thread_local! { /// the thread-local QuickJsRuntime /// this only exists for the worker thread of the EsEventQueue /// todo move rt init to toplevel stackframe (out of lazy init) /// so the thread_local should be a refcel containing a null reF? or a None pub(crate) static QJS_RT: RefCell<Option<QuickJsRuntimeAdapter >> = const { RefCell::new(None) }; } pub type ContextInitHooks = Vec<Box<dyn Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> Result<(), JsError>>>; pub struct QuickJsRuntimeAdapter { pub(crate) runtime: *mut q::JSRuntime, pub(crate) contexts: HashMap<String, QuickJsRealmAdapter>, rti_ref: Option<Weak<QuickjsRuntimeFacadeInner>>, id: String, pub(crate) context_init_hooks: RefCell<ContextInitHooks>, script_module_loaders: Vec<ScriptModuleLoaderAdapter>, native_module_loaders: Vec<NativeModuleLoaderAdapter>, compiled_module_loaders: Vec<CompiledModuleLoaderAdapter>, // script preprocs just preproc the input code, typescript transpiler will be special option which is run as last preproc pub(crate) script_pre_processors: Vec<Box<dyn ScriptPreProcessor + Send>>, #[allow(clippy::type_complexity)] pub(crate) interrupt_handler: Option<Box<dyn Fn(&QuickJsRuntimeAdapter) -> bool>>, } thread_local! { static NESTED: RefCell<bool> = const {RefCell::new(false)}; } #[derive(Serialize)] pub struct MemoryUsage { pub realm_ct: usize, pub malloc_size: i64, pub malloc_limit: i64, pub memory_used_size: i64, pub malloc_count: i64, pub memory_used_count: i64, pub atom_count: i64, pub atom_size: i64, pub str_count: i64, pub str_size: i64, pub obj_count: i64, pub obj_size: i64, pub prop_count: i64, pub prop_size: i64, pub shape_count: i64, pub shape_size: i64, pub js_func_count: i64, pub js_func_size: i64, pub js_func_code_size: i64, pub js_func_pc2line_count: i64, pub js_func_pc2line_size: i64, pub c_func_count: i64, pub array_count: i64, pub fast_array_count: i64, pub fast_array_elements: i64, pub binary_object_count: i64, pub binary_object_size: i64, } impl Debug for MemoryUsage { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("MemoryUsage:")?; f.write_str(format!("\n realm_ct: {}", self.realm_ct).as_str())?; f.write_str(format!("\n malloc_size: {}", self.malloc_size).as_str())?; f.write_str(format!("\n malloc_limit: {}", self.malloc_limit).as_str())?; f.write_str(format!("\n memory_used_size: {}", self.memory_used_size).as_str())?; f.write_str(format!("\n malloc_count: {}", self.malloc_count).as_str())?; f.write_str(format!("\n memory_used_count: {}", self.memory_used_count).as_str())?; f.write_str(format!("\n atom_count: {}", self.atom_count).as_str())?; f.write_str(format!("\n atom_size: {}", self.atom_size).as_str())?; f.write_str(format!("\n str_count: {}", self.str_count).as_str())?; f.write_str(format!("\n str_size: {}", self.str_size).as_str())?; f.write_str(format!("\n obj_count: {}", self.obj_count).as_str())?; f.write_str(format!("\n obj_size: {}", self.obj_size).as_str())?; f.write_str(format!("\n prop_count: {}", self.prop_count).as_str())?; f.write_str(format!("\n prop_size: {}", self.prop_size).as_str())?; f.write_str(format!("\n shape_count: {}", self.shape_count).as_str())?; f.write_str(format!("\n shape_size: {}", self.shape_size).as_str())?; f.write_str(format!("\n js_func_count: {}", self.js_func_count).as_str())?; f.write_str(format!("\n js_func_size: {}", self.js_func_size).as_str())?; f.write_str(format!("\n js_func_code_size: {}", self.js_func_code_size).as_str())?; f.write_str(format!("\n js_func_pc2line_count: {}", self.js_func_pc2line_count).as_str())?; f.write_str(format!("\n js_func_pc2line_size: {}", self.js_func_pc2line_size).as_str())?; f.write_str(format!("\n c_func_count: {}", self.c_func_count).as_str())?; f.write_str(format!("\n array_count: {}", self.array_count).as_str())?; f.write_str(format!("\n fast_array_count: {}", self.fast_array_count).as_str())?; f.write_str(format!("\n fast_array_elements: {}", self.fast_array_elements).as_str())?; f.write_str(format!("\n binary_object_count: {}", self.binary_object_count).as_str())?; f.write_str(format!("\n binary_object_size: {}", self.binary_object_size).as_str())?; Ok(()) } } impl QuickJsRuntimeAdapter { pub(crate) fn init_rt_for_current_thread(rt: QuickJsRuntimeAdapter) { QJS_RT.with(|rc| { let opt = &mut *rc.borrow_mut(); opt.replace(rt); }) } pub fn new_class_id(&self) -> u32 { unsafe { new_class_id(self.runtime) } } pub fn print_stats(&self) { for ctx in &self.contexts { println!("> ----- ctx: {}", ctx.0); ctx.1.print_stats(); println!("< ----- ctx: {}", ctx.0); } // crate::quickjs_utils::typedarrays::BUFFERS.with(|rc| { let map = &*rc.borrow(); println!("typedarrays::BUFFERS.len() = {}", map.len()); }); crate::quickjs_utils::functions::CALLBACK_REGISTRY.with(|rc| { let map = &*rc.borrow(); println!("functions::CALLBACK_REGISTRY.len() = {}", map.len()); }); crate::quickjs_utils::functions::CALLBACK_IDS.with(|rc| { let map = &*rc.borrow(); println!("functions::CALLBACK_IDS.len() = {}", map.len()); }); let mu = self.memory_usage(); println!("MemoryUsage: {mu:?}"); } /// get memory usage for this runtime pub fn memory_usage(&self) -> MemoryUsage { let mu: q::JSMemoryUsage = unsafe { crate::quickjs_utils::get_memory_usage(self.runtime) }; MemoryUsage { realm_ct: self.contexts.len(), malloc_size: mu.malloc_size, malloc_limit: mu.malloc_limit, memory_used_size: mu.memory_used_size, malloc_count: mu.malloc_count, memory_used_count: mu.memory_used_count, atom_count: mu.atom_count, atom_size: mu.atom_size, str_count: mu.str_count, str_size: mu.str_size, obj_count: mu.obj_count, obj_size: mu.obj_size, prop_count: mu.prop_count, prop_size: mu.prop_size, shape_count: mu.shape_count, shape_size: mu.shape_size, js_func_count: mu.js_func_count, js_func_size: mu.js_func_size, js_func_code_size: mu.js_func_code_size, js_func_pc2line_count: mu.js_func_pc2line_count, js_func_pc2line_size: mu.js_func_pc2line_size, c_func_count: mu.c_func_count, array_count: mu.array_count, fast_array_count: mu.fast_array_count, fast_array_elements: mu.fast_array_elements, binary_object_count: mu.binary_object_count, binary_object_size: mu.binary_object_size, } } pub(crate) fn pre_process(mut script: Script) -> Result<Script, JsError> { Self::do_with(|q_js_rt| { for pp in &q_js_rt.script_pre_processors { pp.process(&mut script)?; } #[cfg(feature = "typescript")] crate::typescript::transpile_serverside(q_js_rt, &mut script)?; Ok(script) }) } pub fn add_context_init_hook<H>(&self, hook: H) -> Result<(), JsError> where H: Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> Result<(), JsError> + 'static, { let i = { let hooks = &mut *self.context_init_hooks.borrow_mut(); hooks.push(Box::new(hook)); hooks.len() - 1 }; let hooks = &*self.context_init_hooks.borrow(); let hook = hooks.get(i).expect("invalid state"); for ctx in self.contexts.values() { if let Err(e) = hook(self, ctx) { panic!("hook failed {}", e); } } Ok(()) } pub fn create_context(id: &str) -> Result<(), JsError> { let ctx = Self::do_with(|q_js_rt| { assert!(!q_js_rt.has_context(id)); QuickJsRealmAdapter::new(id.to_string(), q_js_rt) }); QuickJsRuntimeAdapter::do_with_mut(|q_js_rt| { q_js_rt.contexts.insert(id.to_string(), ctx); }); Self::do_with(|q_js_rt| { let ctx = q_js_rt.get_context(id); let hooks = &*q_js_rt.context_init_hooks.borrow(); for hook in hooks { hook(q_js_rt, ctx)?; } Ok(()) }) } pub fn list_contexts(&self) -> Vec<&str> { self.contexts.keys().map(|k| k.as_str()).collect() } pub fn remove_context(id: &str) -> anyhow::Result<()> { log::debug!("QuickJsRuntime::drop_context: {}", id); QuickJsRuntimeAdapter::do_with(|rt| { let q_ctx = rt.get_context(id); log::trace!("QuickJsRuntime::q_ctx.free: {}", id); q_ctx.free(); log::trace!("after QuickJsRuntime::q_ctx.free: {}", id); rt.gc(); }); let ctx = QuickJsRuntimeAdapter::do_with_mut(|m_rt| m_rt.contexts.remove(id)); match ctx { None => { anyhow::bail!("no such context"); } Some(ctx) => { drop(ctx); } } Ok(()) } pub(crate) fn get_context_ids() -> Vec<String> { QuickJsRuntimeAdapter::do_with(|q_js_rt| { q_js_rt.contexts.iter().map(|c| c.0.clone()).collect() }) } pub fn get_context(&self, id: &str) -> &QuickJsRealmAdapter { self.contexts.get(id).expect("no such context") } pub fn opt_context(&self, id: &str) -> Option<&QuickJsRealmAdapter> { self.contexts.get(id) } pub fn has_context(&self, id: &str) -> bool { self.contexts.contains_key(id) } pub(crate) fn init_rti_ref(&mut self, el_ref: Weak<QuickjsRuntimeFacadeInner>) { self.rti_ref = Some(el_ref); } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_quickjs_context(&self, context: *mut q::JSContext) -> &QuickJsRealmAdapter { let id = QuickJsRealmAdapter::get_id(context); self.get_context(id) } pub fn get_rti_ref(&self) -> Option<Arc<QuickjsRuntimeFacadeInner>> { if let Some(rt_ref) = &self.rti_ref { rt_ref.upgrade() } else { None } } pub(crate) fn new(runtime: *mut q::JSRuntime) -> Self { log::trace!("creating new QuickJsRuntime"); if runtime.is_null() { panic!("RuntimeCreationFailed"); } // Configure memory limit if specified. //let memory_limit = None; //if let Some(limit) = memory_limit { // unsafe { //q::JS_SetMemoryLimit(runtime, limit as _); //} //} let id = format!("q_{}", thread_id::get()); let mut q_rt = Self { runtime, contexts: Default::default(), rti_ref: None, id, context_init_hooks: RefCell::new(vec![]), script_module_loaders: vec![], native_module_loaders: vec![], compiled_module_loaders: vec![], script_pre_processors: vec![], interrupt_handler: None, }; modules::set_module_loader(&q_rt); promises::init_promise_rejection_tracker(&q_rt); let main_ctx = QuickJsRealmAdapter::new("__main__".to_string(), &q_rt); q_rt.contexts.insert("__main__".to_string(), main_ctx); q_rt } pub fn set_interrupt_handler<I: Fn(&QuickJsRuntimeAdapter) -> bool + 'static>( &mut self, interrupt_handler: I, ) -> &mut Self { self.interrupt_handler = Some(Box::new(interrupt_handler)); interrupthandler::init(self); self } pub fn add_script_module_loader(&mut self, sml: ScriptModuleLoaderAdapter) { self.script_module_loaders.push(sml); } pub fn add_compiled_module_loader(&mut self, cml: CompiledModuleLoaderAdapter) { self.compiled_module_loaders.push(cml); } pub fn add_native_module_loader(&mut self, nml: NativeModuleLoaderAdapter) { self.native_module_loaders.push(nml); } pub fn get_main_realm(&self) -> &QuickJsRealmAdapter { // todo store this somewhere so we don't need a lookup in the map every time self.get_context("__main__") } pub fn with_all_module_loaders<C, R>(&self, consumer: C) -> Option<R> where C: Fn(&dyn ModuleLoader) -> Option<R>, { for loader in &self.compiled_module_loaders { let res = consumer(loader); if res.is_some() { return res; } } for loader in &self.native_module_loaders { let res = consumer(loader); if res.is_some() { return res; } } for loader in &self.script_module_loaders { let res = consumer(loader); if res.is_some() { return res; } } None } /// run the garbage collector pub fn gc(&self) { gc(self); } pub fn do_with<C, R>(task: C) -> R where C: FnOnce(&QuickJsRuntimeAdapter) -> R, { let most_outer = NESTED.with(|rc| { if *rc.borrow() { false } else { *rc.borrow_mut() = true; true } }); let res = QJS_RT.with(|qjs_rc| { let qjs_rt_opt = &*qjs_rc.borrow(); let q_js_rt = qjs_rt_opt .as_ref() .expect("runtime was not yet initialized for this thread"); if most_outer { unsafe { libquickjs_sys::JS_UpdateStackTop(q_js_rt.runtime) }; } task(q_js_rt) }); if most_outer { NESTED.with(|rc| { *rc.borrow_mut() = false; }); } res } pub fn do_with_mut<C, R>(task: C) -> R where C: FnOnce(&mut QuickJsRuntimeAdapter) -> R, { let most_outer = NESTED.with(|rc| { if *rc.borrow() { false } else { *rc.borrow_mut() = true; true } }); let res = QJS_RT.with(|qjs_rc| { let qjs_rt_opt = &mut *qjs_rc.borrow_mut(); let qjs_rt = qjs_rt_opt .as_mut() .expect("runtime was not yet initialized for this thread"); if most_outer { unsafe { libquickjs_sys::JS_UpdateStackTop(qjs_rt.runtime) }; } task(qjs_rt) }); if most_outer { NESTED.with(|rc| { *rc.borrow_mut() = false; }); } res } /// run pending jobs if avail /// # todo /// move this to a quickjs_utils::pending_jobs so it can be used without doing QuickjsRuntime.do_with() pub fn run_pending_jobs_if_any(&self) { log::trace!("quick_js_rt.run_pending_jobs_if_any"); while self.has_pending_jobs() { log::trace!("quick_js_rt.has_pending_jobs!"); let res = self.run_pending_job(); match res { Ok(_) => { log::trace!("run_pending_job OK!"); } Err(e) => { log::error!("run_pending_job failed: {}", e); } } } } pub fn has_pending_jobs(&self) -> bool { let flag = unsafe { q::JS_IsJobPending(self.runtime) }; #[cfg(feature = "bellard")] { flag > 0 } #[cfg(feature = "quickjs-ng")] { flag } } pub fn run_pending_job(&self) -> Result<(), JsError> { let mut ctx: *mut q::JSContext = std::ptr::null_mut(); let flag = unsafe { // ctx is a return arg here q::JS_ExecutePendingJob(self.runtime, &mut ctx) }; if flag < 0 { let e = unsafe { QuickJsRealmAdapter::get_exception(ctx) } .unwrap_or_else(|| JsError::new_str("Unknown exception while running pending job")); return Err(e); } Ok(()) } pub fn get_id(&self) -> &str { self.id.as_str() } /// this method tries to load a module script using the runtimes script_module loaders pub fn load_module_script_opt(&self, ref_path: &str, path: &str) -> Option<Script> { let realm = self.get_main_realm(); for loader in &self.script_module_loaders { let i = &loader.inner; if let Some(normalized) = i.normalize_path(realm, ref_path, path) { let code = i.load_module(realm, normalized.as_str()); return Some(Script::new(normalized.as_str(), code.as_str())); } } None } } impl Drop for QuickJsRuntimeAdapter { fn drop(&mut self) { // drop contexts first, should be done when Dropping EsRuntime? log::trace!("drop QuickJsRuntime, dropping contexts"); self.contexts.clear(); log::trace!("drop QuickJsRuntime, after dropping contexts"); log::trace!("before JS_FreeRuntime"); unsafe { q::JS_FreeRuntime(self.runtime) }; log::trace!("after JS_FreeRuntime"); } } impl QuickJsRuntimeAdapter { pub fn load_module_script(&self, ref_path: &str, path: &str) -> Option<Script> { self.load_module_script_opt(ref_path, path) } pub fn get_realm(&self, id: &str) -> Option<&QuickJsRealmAdapter> { if self.has_context(id) { Some(self.get_context(id)) } else { None } } pub fn add_realm_init_hook<H>(&self, hook: H) -> Result<(), JsError> where H: Fn(&Self, &QuickJsRealmAdapter) -> Result<(), JsError> + 'static, { self.add_context_init_hook(hook) } } /// Helper for creating CStrings. pub(crate) fn make_cstring(value: &str) -> Result<CString, JsError> { let res = CString::new(value); match res { Ok(val) => Ok(val), Err(_) => Err(JsError::new_string(format!( "could not create cstring from {value}" ))), } } #[cfg(test)] pub mod tests { use crate::builder::QuickJsRuntimeBuilder; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use crate::facades::tests::init_test_rt; use std::panic; use crate::jsutils::modules::ScriptModuleLoader; use crate::jsutils::Script; struct FooScriptModuleLoader {} impl ScriptModuleLoader for FooScriptModuleLoader { fn normalize_path( &self, _realm: &QuickJsRealmAdapter, _ref_path: &str, path: &str, ) -> Option<String> { Some(path.to_string()) } fn load_module(&self, _realm: &QuickJsRealmAdapter, _absolute_path: &str) -> String { log::debug!("load_module"); "{}".to_string() } } #[test] fn test_mem_usage() { let rt = QuickJsRuntimeBuilder::new() .memory_limit(1024 * 1024) .build(); rt.eval_sync(None, Script::new("", "globalThis.f = function(){};")) .expect("script failed"); rt.loop_realm_sync(None, |rt, _realm| { let mu = rt.memory_usage(); println!("mu: {mu:?}"); }); } #[test] fn test_script_load() { log::debug!("testing1"); let rt = QuickJsRuntimeBuilder::new() .script_module_loader(FooScriptModuleLoader {}) .build(); rt.exe_rt_task_in_event_loop(|q_js_rt| { log::debug!("testing2"); let script = q_js_rt.load_module_script_opt("", "test.mjs").unwrap(); assert_eq!(script.get_runnable_code(), "{}"); log::debug!("tested"); }); } #[test] fn test_eval() { let rt = init_test_rt(); rt.eval_sync( None, Script::new( "eval.js", "console.log('euc: ' + encodeURIComponent('hello world'));", ), ) .expect("script failed to compile"); } #[test] fn test_realm_init() { /*panic::set_hook(Box::new(|panic_info| { let backtrace = Backtrace::new(); println!( "thread panic occurred: {}\nbacktrace: {:?}", panic_info, backtrace ); log::error!( "thread panic occurred: {}\nbacktrace: {:?}", panic_info, backtrace ); })); simple_logging::log_to_stderr(LevelFilter::max()); */ let rt = QuickJsRuntimeBuilder::new().build(); rt.exe_task_in_event_loop(|| { QuickJsRuntimeAdapter::do_with(|rt| { rt.add_realm_init_hook(|_rt, realm| { realm .install_function( &["utils"], "doSomething", |_rt, realm, _this, _args| realm.create_null(), 0, ) .expect("failed to install function"); match realm.eval(Script::new("t.js", "1+1")) { Ok(_) => {} Err(e) => { panic!("script failed {}", e); } } Ok(()) }) .expect("init hook addition failed"); }) }); rt.loop_realm_void(Some("testrealm1"), |_rt, realm| { realm .eval(Script::new("test.js", "console.log(utils.doSomething());")) .expect("script failed"); }); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjsrealmadapter.rs
src/quickjsrealmadapter.rs
use crate::facades::QuickjsRuntimeFacadeInner; use crate::quickjs_utils::objects::construct_object; use crate::quickjs_utils::primitives::{from_bool, from_f64, from_i32, from_string_q}; use crate::quickjs_utils::typedarrays::{ detach_array_buffer_buffer_q, get_array_buffer_buffer_copy_q, get_array_buffer_q, new_uint8_array_copy_q, new_uint8_array_q, }; use crate::quickjs_utils::{arrays, errors, functions, get_global_q, json, new_null_ref, objects}; use crate::quickjsruntimeadapter::{make_cstring, QuickJsRuntimeAdapter}; use crate::quickjsvalueadapter::{QuickJsValueAdapter, TAG_EXCEPTION}; use crate::reflection::eventtarget::dispatch_event; use crate::reflection::eventtarget::dispatch_static_event; use crate::reflection::{new_instance, new_instance3, Proxy}; use hirofa_utils::auto_id_map::AutoIdMap; use crate::jsutils::jsproxies::{JsProxy, JsProxyInstanceId}; use crate::jsutils::{JsError, JsValueType, Script}; use crate::quickjs_utils::promises::QuickJsPromiseAdapter; use crate::values::{ CachedJsArrayRef, CachedJsFunctionRef, CachedJsObjectRef, CachedJsPromiseRef, JsValueFacade, TypedArrayType, }; use libquickjs_sys as q; use serde_json::Value; use std::cell::RefCell; use std::collections::HashMap; use std::ffi::CString; use std::future::Future; use std::os::raw::c_void; use std::rc::Rc; use std::sync::{Arc, Weak}; use crate::jsutils::promises::new_resolving_promise; use crate::jsutils::promises::new_resolving_promise_async; use string_cache::DefaultAtom; type ProxyEventListenerMaps = HashMap< String, /*proxy_class_name*/ HashMap< usize, /*proxy_instance_id*/ HashMap< String, /*event_id*/ HashMap< QuickJsValueAdapter, /*listener_func*/ QuickJsValueAdapter, /*options_obj*/ >, >, >, >; type ProxyStaticEventListenerMaps = HashMap< String, /*proxy_class_name*/ HashMap< String, /*event_id*/ HashMap< QuickJsValueAdapter, /*listener_func*/ QuickJsValueAdapter, /*options_obj*/ >, >, >; pub struct QuickJsRealmAdapter { object_cache: RefCell<AutoIdMap<QuickJsValueAdapter>>, promise_cache: RefCell<AutoIdMap<QuickJsPromiseAdapter>>, pub(crate) proxy_registry: RefCell<HashMap<String, Rc<Proxy>>>, // todo is this Rc needed or can we just borrow the Proxy when needed? pub(crate) proxy_constructor_refs: RefCell<HashMap<String, QuickJsValueAdapter>>, pub(crate) proxy_event_listeners: RefCell<ProxyEventListenerMaps>, pub(crate) proxy_static_event_listeners: RefCell<ProxyStaticEventListenerMaps>, pub id: String, pub context: *mut q::JSContext, } thread_local! { #[allow(clippy::box_collection)] static ID_REGISTRY: RefCell<HashMap<String, Box<String>>> = RefCell::new(HashMap::new()); } impl QuickJsRealmAdapter { pub fn print_stats(&self) { println!( "QuickJsRealmAdapter.object_cache.len = {}", self.object_cache.borrow().len() ); println!( "QuickJsRealmAdapter.promise_cache.len = {}", self.promise_cache.borrow().len() ); println!("-- > QuickJsRealmAdapter.proxy instances"); for p in &*self.proxy_registry.borrow() { let prc = p.1.clone(); let proxy = &*prc; let mappings = &*proxy.proxy_instance_id_mappings.borrow(); println!("---- > {} len:{}", p.0, mappings.len()); print!("------ ids: "); for i in mappings { print!("{}, ", i.0); } println!("\n---- < {}", p.0); } println!("-- < QuickJsRealmAdapter.proxy instances"); let _spsel: &ProxyStaticEventListenerMaps = &self.proxy_static_event_listeners.borrow(); let psel: &ProxyEventListenerMaps = &self.proxy_event_listeners.borrow(); println!("> psel"); for a in psel { println!("- psel - {}", a.0); let map = a.1; for b in map { println!("- psel - id {}", b.0); let map_b = b.1; for c in map_b { println!("- psel - id {} - evt {}", b.0, c.0); let map_c = c.1; println!( "- psel - id {} - evt {} - mapC.len={}", b.0, c.0, map_c.len() ); for eh in map_c { // handler, options? println!( "- psel - id {} - evt {} - handler:{} options:{}", b.0, c.0, eh.0.to_string().expect("could not toString"), eh.1.to_string().expect("could not toString") ); } } } } println!("< psel"); } pub(crate) fn free(&self) { log::trace!("QuickJsContext:free {}", self.id); { let cache_map = &mut *self.object_cache.borrow_mut(); log::trace!( "QuickJsContext:free {}, dropping {} cached objects", self.id, cache_map.len() ); cache_map.clear(); } let mut all_listeners = { let proxy_event_listeners: &mut ProxyEventListenerMaps = &mut self.proxy_event_listeners.borrow_mut(); std::mem::take(proxy_event_listeners) }; // drop outside of borrowmut so finalizers don;t get error when trying to get mut borrow on map all_listeners.clear(); // hmm these should still exist minus the constrcutor ref on free, so we need to remove the constructor refs, then call free, then call gc and then clear proxies // so here we should just clear the refs.. let mut all_constructor_refs = { let proxy_constructor_refs = &mut *self.proxy_constructor_refs.borrow_mut(); std::mem::take(proxy_constructor_refs) }; all_constructor_refs.clear(); unsafe { q::JS_FreeContext(self.context) }; log::trace!("after QuickJsContext:free {}", self.id); } pub(crate) fn new(id: String, q_js_rt: &QuickJsRuntimeAdapter) -> Self { let context = unsafe { q::JS_NewContext(q_js_rt.runtime) }; let mut bx = Box::new(id.clone()); let ibp: &mut String = &mut bx; let info_ptr = ibp as *mut _ as *mut c_void; ID_REGISTRY.with(|rc| { let registry = &mut *rc.borrow_mut(); registry.insert(id.clone(), bx); }); unsafe { q::JS_SetContextOpaque(context, info_ptr) }; if context.is_null() { panic!("ContextCreationFailed"); } Self { id, context, object_cache: RefCell::new(AutoIdMap::new_with_max_size(i32::MAX as usize)), promise_cache: RefCell::new(AutoIdMap::new()), proxy_registry: RefCell::new(Default::default()), proxy_constructor_refs: RefCell::new(Default::default()), proxy_event_listeners: RefCell::new(Default::default()), proxy_static_event_listeners: RefCell::new(Default::default()), } } /// get the id of a QuickJsContext from a JSContext /// # Safety /// when passing a context ptr please be sure that the corresponding QuickJsContext is still active pub unsafe fn get_id(context: *mut q::JSContext) -> &'static str { let info_ptr: *mut c_void = q::JS_GetContextOpaque(context); let info: &mut String = &mut *(info_ptr as *mut String); info } /// invoke a function by namespace and name pub fn invoke_function_by_name( &self, namespace: &[&str], func_name: &str, arguments: &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> { let namespace_ref = unsafe { objects::get_namespace(self.context, namespace, false) }?; functions::invoke_member_function_q(self, &namespace_ref, func_name, arguments) } /// evaluate a script pub fn eval(&self, script: Script) -> Result<QuickJsValueAdapter, JsError> { unsafe { Self::eval_ctx(self.context, script, None) } } pub fn eval_this( &self, script: Script, this: QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { Self::eval_ctx(self.context, script, Some(this)) } } /// # Safety /// when passing a context ptr please be sure that the corresponding QuickJsContext is still active pub unsafe fn eval_ctx( context: *mut q::JSContext, mut script: Script, this_opt: Option<QuickJsValueAdapter>, ) -> Result<QuickJsValueAdapter, JsError> { log::debug!("q_js_rt.eval file {}", script.get_path()); script = QuickJsRuntimeAdapter::pre_process(script)?; let code_str = script.get_runnable_code(); let filename_c = make_cstring(script.get_path())?; let code_c = make_cstring(code_str)?; let value_raw = match this_opt { None => q::JS_Eval( context, code_c.as_ptr(), code_str.len() as _, filename_c.as_ptr(), q::JS_EVAL_TYPE_GLOBAL as i32, ), Some(this) => q::JS_EvalThis( context, this.clone_value_incr_rc(), code_c.as_ptr(), code_str.len() as _, filename_c.as_ptr(), q::JS_EVAL_TYPE_GLOBAL as i32, ), }; log::trace!("after eval, checking error"); // check for error let ret = QuickJsValueAdapter::new( context, value_raw, false, true, format!("eval result of {}", script.get_path()).as_str(), ); if ret.is_exception() { let ex_opt = Self::get_exception(context); if let Some(ex) = ex_opt { log::debug!("eval_ctx failed: {}", ex); Err(ex) } else { Err(JsError::new_str("eval failed and could not get exception")) } } else { Ok(ret) } } /// evaluate a Module pub fn eval_module(&self, script: Script) -> Result<QuickJsValueAdapter, JsError> { unsafe { Self::eval_module_ctx(self.context, script) } } /// # Safety /// when passing a context ptr please be sure that the corresponding QuickJsContext is still active pub unsafe fn eval_module_ctx( context: *mut q::JSContext, mut script: Script, ) -> Result<QuickJsValueAdapter, JsError> { log::debug!("q_js_rt.eval_module file {}", script.get_path()); script = QuickJsRuntimeAdapter::pre_process(script)?; let code_str = script.get_runnable_code(); let filename_c = make_cstring(script.get_path())?; let code_c = make_cstring(code_str)?; let value_raw = q::JS_Eval( context, code_c.as_ptr(), code_str.len() as _, filename_c.as_ptr(), q::JS_EVAL_TYPE_MODULE as i32, ); let ret = QuickJsValueAdapter::new( context, value_raw, false, true, format!("eval_module result of {}", script.get_path()).as_str(), ); log::trace!("evalled module yielded a {}", ret.borrow_value().tag); // check for error if ret.is_exception() { let ex_opt = Self::get_exception(context); if let Some(ex) = ex_opt { log::debug!("eval_module_ctx failed: {}", ex); Err(ex) } else { Err(JsError::new_str( "eval_module failed and could not get exception", )) } } else { Ok(ret) } } /// throw an internal error to quickjs and create a new ex obj pub fn report_ex(&self, err: &str) -> q::JSValue { unsafe { Self::report_ex_ctx(self.context, err) } } /// throw an Error in the runtime and init an Exception JSValue to return /// # Safety /// when passing a context ptr please be sure that the corresponding QuickJsContext is still active pub unsafe fn report_ex_ctx(context: *mut q::JSContext, err: &str) -> q::JSValue { let c_err = CString::new(err); q::JS_ThrowInternalError(context, c_err.as_ref().ok().unwrap().as_ptr()); q::JSValue { u: q::JSValueUnion { int32: 0 }, tag: TAG_EXCEPTION, } } /// Get the last exception from the runtime, and if present, convert it to a JsError. pub fn get_exception_ctx(&self) -> Option<JsError> { unsafe { errors::get_exception(self.context) } } /// Get the last exception from the runtime, and if present, convert it to a JsError. /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_exception(context: *mut q::JSContext) -> Option<JsError> { errors::get_exception(context) } pub fn cache_object(&self, obj: QuickJsValueAdapter) -> i32 { let cache_map = &mut *self.object_cache.borrow_mut(); let id = cache_map.insert(obj) as i32; log::trace!("cache_object: id={}, thread={}", id, thread_id::get()); id } pub fn remove_cached_obj_if_present(&self, id: i32) { log::trace!( "remove_cached_obj_if_present: id={}, thread={}", id, thread_id::get() ); let cache_map = &mut *self.object_cache.borrow_mut(); if cache_map.contains_key(&(id as usize)) { let _ = cache_map.remove(&(id as usize)); } } pub fn consume_cached_obj(&self, id: i32) -> QuickJsValueAdapter { log::trace!("consume_cached_obj: id={}, thread={}", id, thread_id::get()); let cache_map = &mut *self.object_cache.borrow_mut(); cache_map.remove(&(id as usize)) } pub fn with_cached_obj<C, R>(&self, id: i32, consumer: C) -> R where C: FnOnce(QuickJsValueAdapter) -> R, { log::trace!("with_cached_obj: id={}, thread={}", id, thread_id::get()); let clone_ref = { let cache_map = &*self.object_cache.borrow(); let opt = cache_map.get(&(id as usize)); let cached_ref = opt.expect("no such obj in cache"); cached_ref.clone() }; // prevent running consumer while borrowed consumer(clone_ref) } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn with_context<C, R>(context: *mut q::JSContext, consumer: C) -> R where C: FnOnce(&QuickJsRealmAdapter) -> R, { QuickJsRuntimeAdapter::do_with(|q_js_rt| { let id = QuickJsRealmAdapter::get_id(context); let q_ctx = q_js_rt.get_context(id); consumer(q_ctx) }) } } impl Drop for QuickJsRealmAdapter { fn drop(&mut self) { log::trace!("before drop QuickJSContext {}", self.id); let id = &self.id; { ID_REGISTRY.with(|rc| { let registry = &mut *rc.borrow_mut(); registry.remove(id); }); } { let proxies = &mut *self.proxy_registry.borrow_mut(); proxies.clear(); } log::trace!("after drop QuickJSContext {}", self.id); } } impl QuickJsRealmAdapter { pub fn get_realm_id(&self) -> &str { self.id.as_str() } pub fn get_runtime_facade_inner(&self) -> Weak<QuickjsRuntimeFacadeInner> { QuickJsRuntimeAdapter::do_with(|rt| { Arc::downgrade(&rt.get_rti_ref().expect("Runtime was dropped")) }) } pub fn get_script_or_module_name(&self) -> Result<String, JsError> { crate::quickjs_utils::get_script_or_module_name_q(self) } pub fn install_proxy( &self, proxy: JsProxy, add_global_var: bool, ) -> Result<QuickJsValueAdapter, JsError> { // create qjs proxy from proxy proxy.install(self, add_global_var) } pub fn instantiate_proxy_with_id( &self, namespace: &[&str], class_name: &str, instance_id: usize, ) -> Result<QuickJsValueAdapter, JsError> { // todo store proxies with slice/name as key? let cn = if namespace.is_empty() { class_name.to_string() } else { format!("{}.{}", namespace.join("."), class_name) }; let proxy_map = self.proxy_registry.borrow(); let proxy = proxy_map.get(cn.as_str()).expect("class not found"); new_instance3(proxy, instance_id, self) } pub fn instantiate_proxy( &self, namespace: &[&str], class_name: &str, arguments: &[QuickJsValueAdapter], ) -> Result<(JsProxyInstanceId, QuickJsValueAdapter), JsError> { // todo store proxies with slice/name as key? let cn = if namespace.is_empty() { class_name.to_string() } else { format!("{}.{}", namespace.join("."), class_name) }; let proxy_map = self.proxy_registry.borrow(); let proxy = proxy_map.get(cn.as_str()).expect("class not found"); let instance_info = new_instance(cn.as_str(), self)?; if let Some(constructor) = &proxy.constructor { // call constructor myself QuickJsRuntimeAdapter::do_with(|rt| constructor(rt, self, instance_info.0, arguments))? } Ok(instance_info) } pub fn dispatch_proxy_event( &self, namespace: &[&str], class_name: &str, proxy_instance_id: &usize, event_id: &str, event_obj: &QuickJsValueAdapter, ) -> Result<bool, JsError> { // todo store proxies with slice/name as key? let cn = if namespace.is_empty() { class_name.to_string() } else { format!("{}.{}", namespace.join("."), class_name) }; let proxy_map = self.proxy_registry.borrow(); let proxy = proxy_map.get(cn.as_str()).expect("class not found"); dispatch_event(self, proxy, *proxy_instance_id, event_id, event_obj.clone()) } pub fn dispatch_static_proxy_event( &self, namespace: &[&str], class_name: &str, event_id: &str, event_obj: &QuickJsValueAdapter, ) -> Result<bool, JsError> { // todo store proxies with slice/name as key? let cn = if namespace.is_empty() { class_name.to_string() } else { format!("{}.{}", namespace.join("."), class_name) }; let proxy_map = self.proxy_registry.borrow(); let proxy = proxy_map.get(cn.as_str()).expect("class not found"); dispatch_static_event( self, proxy.get_class_name().as_str(), event_id, event_obj.clone(), ) } pub fn install_function( &self, namespace: &[&str], name: &str, js_function: fn( &QuickJsRuntimeAdapter, &Self, &QuickJsValueAdapter, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError>, arg_count: u32, ) -> Result<(), JsError> { // todo namespace as slice? let ns = self.get_namespace(namespace)?; let func = functions::new_function_q( self, name, move |ctx, this, args| { QuickJsRuntimeAdapter::do_with(|rt| js_function(rt, ctx, this, args)) }, arg_count, )?; self.set_object_property(&ns, name, &func)?; Ok(()) } pub fn install_closure< F: Fn( &QuickJsRuntimeAdapter, &Self, &QuickJsValueAdapter, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> + 'static, >( &self, namespace: &[&str], name: &str, js_function: F, arg_count: u32, ) -> Result<(), JsError> { // todo namespace as slice? let ns = self.get_namespace(namespace)?; let func = functions::new_function_q( self, name, move |ctx, this, args| { QuickJsRuntimeAdapter::do_with(|rt| js_function(rt, ctx, this, args)) }, arg_count, )?; self.set_object_property(&ns, name, &func)?; Ok(()) } pub fn get_global(&self) -> Result<QuickJsValueAdapter, JsError> { Ok(get_global_q(self)) } pub fn get_namespace(&self, namespace: &[&str]) -> Result<QuickJsValueAdapter, JsError> { objects::get_namespace_q(self, namespace, true) } pub fn invoke_function_on_object_by_name( &self, this_obj: &QuickJsValueAdapter, method_name: &str, args: &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> { functions::invoke_member_function_q(self, this_obj, method_name, args) } pub fn invoke_function( &self, this_obj: Option<&QuickJsValueAdapter>, function_obj: &QuickJsValueAdapter, args: &[&QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> { functions::call_function_q_ref_args(self, function_obj, args, this_obj) } pub fn create_function< F: Fn( &Self, &QuickJsValueAdapter, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> + 'static, >( &self, name: &str, js_function: F, arg_count: u32, ) -> Result<QuickJsValueAdapter, JsError> { functions::new_function_q(self, name, js_function, arg_count) } pub fn create_function_async<R, F>( &self, name: &str, js_function: F, arg_count: u32, ) -> Result<QuickJsValueAdapter, JsError> where Self: Sized + 'static, R: Future<Output = Result<JsValueFacade, JsError>> + Send + 'static, F: Fn(JsValueFacade, Vec<JsValueFacade>) -> R + 'static, { // self.create_function( name, move |realm, this, args| { let this_fac = realm.to_js_value_facade(this)?; let mut args_fac = vec![]; for arg in args { args_fac.push(realm.to_js_value_facade(arg)?); } let fut = js_function(this_fac, args_fac); realm.create_resolving_promise_async(fut, |realm, pres| { // realm.from_js_value_facade(pres) }) }, arg_count, ) } pub fn create_error( &self, name: &str, message: &str, stack: &str, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { errors::new_error(self.context, name, message, stack) } } pub fn delete_object_property( &self, object: &QuickJsValueAdapter, property_name: &str, ) -> Result<(), JsError> { // todo impl a real delete_prop objects::set_property_q(self, object, property_name, &new_null_ref()) } pub fn set_object_property( &self, object: &QuickJsValueAdapter, property_name: &str, property: &QuickJsValueAdapter, ) -> Result<(), JsError> { objects::set_property_q(self, object, property_name, property) } pub fn get_object_property( &self, object: &QuickJsValueAdapter, property_name: &str, ) -> Result<QuickJsValueAdapter, JsError> { objects::get_property_q(self, object, property_name) } pub fn create_object(&self) -> Result<QuickJsValueAdapter, JsError> { objects::create_object_q(self) } pub fn construct_object( &self, constructor: &QuickJsValueAdapter, args: &[&QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> { // todo alter constructor method to accept slice unsafe { construct_object(self.context, constructor, args) } } pub fn get_object_properties( &self, object: &QuickJsValueAdapter, ) -> Result<Vec<String>, JsError> { let props = objects::get_own_property_names_q(self, object)?; let mut ret = vec![]; for x in 0..props.len() { let prop = props.get_name(x)?; ret.push(prop); } Ok(ret) } pub fn traverse_object<F, R>( &self, object: &QuickJsValueAdapter, visitor: F, ) -> Result<Vec<R>, JsError> where F: Fn(&str, &QuickJsValueAdapter) -> Result<R, JsError>, { objects::traverse_properties_q(self, object, visitor) } pub fn traverse_object_mut<F>( &self, object: &QuickJsValueAdapter, visitor: F, ) -> Result<(), JsError> where F: FnMut(&str, &QuickJsValueAdapter) -> Result<(), JsError>, { objects::traverse_properties_q_mut(self, object, visitor) } pub fn get_array_element( &self, array: &QuickJsValueAdapter, index: u32, ) -> Result<QuickJsValueAdapter, JsError> { arrays::get_element_q(self, array, index) } /// push an element into an Array pub fn push_array_element( &self, array: &QuickJsValueAdapter, element: &QuickJsValueAdapter, ) -> Result<u32, JsError> { let push_func = self.get_object_property(array, "push")?; let res = self.invoke_function(Some(array), &push_func, &[element])?; Ok(res.to_i32() as u32) } pub fn set_array_element( &self, array: &QuickJsValueAdapter, index: u32, element: &QuickJsValueAdapter, ) -> Result<(), JsError> { arrays::set_element_q(self, array, index, element) } pub fn get_array_length(&self, array: &QuickJsValueAdapter) -> Result<u32, JsError> { arrays::get_length_q(self, array) } pub fn create_array(&self) -> Result<QuickJsValueAdapter, JsError> { arrays::create_array_q(self) } pub fn traverse_array<F, R>( &self, array: &QuickJsValueAdapter, visitor: F, ) -> Result<Vec<R>, JsError> where F: Fn(u32, &QuickJsValueAdapter) -> Result<R, JsError>, { // todo impl real traverse methods let mut ret = vec![]; for x in 0..arrays::get_length_q(self, array)? { let val = arrays::get_element_q(self, array, x)?; ret.push(visitor(x, &val)?) } Ok(ret) } pub fn traverse_array_mut<F>( &self, array: &QuickJsValueAdapter, mut visitor: F, ) -> Result<(), JsError> where F: FnMut(u32, &QuickJsValueAdapter) -> Result<(), JsError>, { // todo impl real traverse methods for x in 0..arrays::get_length_q(self, array)? { let val = arrays::get_element_q(self, array, x)?; visitor(x, &val)?; } Ok(()) } pub fn create_null(&self) -> Result<QuickJsValueAdapter, JsError> { Ok(crate::quickjs_utils::new_null_ref()) } pub fn create_undefined(&self) -> Result<QuickJsValueAdapter, JsError> { Ok(crate::quickjs_utils::new_undefined_ref()) } pub fn create_i32(&self, val: i32) -> Result<QuickJsValueAdapter, JsError> { Ok(from_i32(val)) } pub fn create_string(&self, val: &str) -> Result<QuickJsValueAdapter, JsError> { from_string_q(self, val) } pub fn create_boolean(&self, val: bool) -> Result<QuickJsValueAdapter, JsError> { Ok(from_bool(val)) } pub fn create_f64(&self, val: f64) -> Result<QuickJsValueAdapter, JsError> { Ok(from_f64(val)) } pub fn create_promise(&self) -> Result<QuickJsPromiseAdapter, JsError> { crate::quickjs_utils::promises::new_promise_q(self) } pub fn add_promise_reactions( &self, promise: &QuickJsValueAdapter, then: Option<QuickJsValueAdapter>, catch: Option<QuickJsValueAdapter>, finally: Option<QuickJsValueAdapter>, ) -> Result<(), JsError> { crate::quickjs_utils::promises::add_promise_reactions_q(self, promise, then, catch, finally) } pub fn cache_promise(&self, promise_ref: QuickJsPromiseAdapter) -> usize { let map = &mut *self.promise_cache.borrow_mut(); map.insert(promise_ref) } pub fn consume_cached_promise(&self, id: usize) -> Option<QuickJsPromiseAdapter> { let map = &mut *self.promise_cache.borrow_mut(); map.remove_opt(&id) } pub fn dispose_cached_object(&self, id: i32) { let _ = self.consume_cached_obj(id); } pub fn with_cached_object<C, R>(&self, id: i32, consumer: C) -> R where C: FnOnce(&QuickJsValueAdapter) -> R, { self.with_cached_obj(id, |obj| consumer(&obj)) } pub fn consume_cached_object(&self, id: i32) -> QuickJsValueAdapter { self.consume_cached_obj(id) } pub fn is_instance_of( &self, object: &QuickJsValueAdapter, constructor: &QuickJsValueAdapter, ) -> bool { objects::is_instance_of_q(self, object, constructor) } pub fn json_stringify( &self, object: &QuickJsValueAdapter, opt_space: Option<&str>, ) -> Result<String, JsError> { let opt_space_jsvr = match opt_space { None => None, Some(s) => Some(self.create_string(s)?), }; let res = json::stringify_q(self, object, opt_space_jsvr); match res { Ok(jsvr) => jsvr.to_string(), Err(e) => Err(e), } } pub fn json_parse(&self, json_string: &str) -> Result<QuickJsValueAdapter, JsError> { json::parse_q(self, json_string) } pub fn create_typed_array_uint8( &self, buffer: Vec<u8>, ) -> Result<QuickJsValueAdapter, JsError> { new_uint8_array_q(self, buffer) } pub fn create_typed_array_uint8_copy( &self, buffer: &[u8], ) -> Result<QuickJsValueAdapter, JsError> { new_uint8_array_copy_q(self, buffer) } pub fn detach_typed_array_buffer( &self, array: &QuickJsValueAdapter, ) -> Result<Vec<u8>, JsError> { let abuf = get_array_buffer_q(self, array)?; detach_array_buffer_buffer_q(self, &abuf) } pub fn copy_typed_array_buffer(&self, array: &QuickJsValueAdapter) -> Result<Vec<u8>, JsError> { let abuf = get_array_buffer_q(self, array)?; get_array_buffer_buffer_copy_q(self, &abuf) } pub fn get_proxy_instance_info( &self, obj: &QuickJsValueAdapter, ) -> Result<(String, JsProxyInstanceId), JsError> where Self: Sized, { if let Some((p, i)) = crate::reflection::get_proxy_instance_proxy_and_instance_id_q(self, obj) { Ok((p.get_class_name(), i)) } else { Err(JsError::new_str("not a proxy instance")) } } pub fn to_js_value_facade( &self, js_value: &QuickJsValueAdapter, ) -> Result<JsValueFacade, JsError> where Self: Sized + 'static, { let res: JsValueFacade = match js_value.get_js_type() { JsValueType::I32 => JsValueFacade::I32 { val: js_value.to_i32(), }, JsValueType::F64 => JsValueFacade::F64 { val: js_value.to_f64(), }, JsValueType::String => JsValueFacade::String { val: DefaultAtom::from(js_value.to_string()?), }, JsValueType::Boolean => JsValueFacade::Boolean { val: js_value.to_bool(), }, JsValueType::Object => { if js_value.is_typed_array() { // todo TypedArray as JsValueType? // passing a typedarray out of the worker thread is sketchy because you either copy the buffer like we do here, or you detach the buffer effectively destroying the jsvalue
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
true
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/facades.rs
src/facades.rs
//! contains the QuickJsRuntimeFacade use crate::builder::QuickJsRuntimeBuilder; use crate::jsutils::{JsError, Script}; use crate::quickjs_utils::{functions, objects}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::{ CompiledModuleLoaderAdapter, MemoryUsage, NativeModuleLoaderAdapter, QuickJsRuntimeAdapter, ScriptModuleLoaderAdapter, QJS_RT, }; use crate::quickjsvalueadapter::QuickJsValueAdapter; use crate::reflection; use crate::values::JsValueFacade; use either::{Either, Left, Right}; use hirofa_utils::eventloop::EventLoop; use hirofa_utils::task_manager::TaskManager; use libquickjs_sys as q; use lru::LruCache; use std::cell::RefCell; use std::future::Future; use std::num::NonZeroUsize; use std::pin::Pin; use std::rc::Rc; use std::sync::{Arc, Weak}; use tokio::task::JoinError; lazy_static! { /// a static Multithreaded task manager used to run rust ops async and multithreaded ( in at least 2 threads) static ref HELPER_TASKS: TaskManager = TaskManager::new(std::cmp::max(2, num_cpus::get())); } impl Drop for QuickJsRuntimeFacade { fn drop(&mut self) { log::trace!("> EsRuntime::drop"); self.clear_contexts(); log::trace!("< EsRuntime::drop"); } } pub struct QuickjsRuntimeFacadeInner { event_loop: EventLoop, } impl QuickjsRuntimeFacadeInner { /// this is how you add a closure to the worker thread which has an instance of the QuickJsRuntime /// this will run and return synchronously /// # example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::primitives; /// let rt = QuickJsRuntimeBuilder::new().build(); /// let res = rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// // here you are in the worker thread and you can use the quickjs_utils /// let val_ref = q_ctx.eval(Script::new("test.es", "(11 * 6);")).ok().expect("script failed"); /// primitives::to_i32(&val_ref).ok().expect("could not get i32") /// }); /// assert_eq!(res, 66); /// ``` pub fn exe_rt_task_in_event_loop<C, R>(&self, consumer: C) -> R where C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static, R: Send + 'static, { self.exe_task_in_event_loop(|| QuickJsRuntimeAdapter::do_with(consumer)) } /// this is how you add a closure to the worker thread which has an instance of the QuickJsRuntime /// this will run asynchronously /// # example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.add_rt_task_to_event_loop(|q_js_rt| { /// // here you are in the worker thread and you can use the quickjs_utils /// q_js_rt.gc(); /// }); /// ``` pub fn add_rt_task_to_event_loop<C, R: Send + 'static>( &self, consumer: C, ) -> impl Future<Output = R> where C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static, { self.add_task_to_event_loop(|| QuickJsRuntimeAdapter::do_with(consumer)) } pub fn add_rt_task_to_event_loop_void<C>(&self, consumer: C) where C: FnOnce(&QuickJsRuntimeAdapter) + Send + 'static, { self.add_task_to_event_loop_void(|| QuickJsRuntimeAdapter::do_with(consumer)) } /// this can be used to run a function in the event_queue thread for the QuickJSRuntime /// without borrowing the q_js_rt pub fn add_task_to_event_loop_void<C>(&self, task: C) where C: FnOnce() + Send + 'static, { self.event_loop.add_void(move || { task(); EventLoop::add_local_void(|| { QuickJsRuntimeAdapter::do_with(|q_js_rt| { q_js_rt.run_pending_jobs_if_any(); }) }) }); } pub fn exe_task_in_event_loop<C, R: Send + 'static>(&self, task: C) -> R where C: FnOnce() -> R + Send + 'static, { self.event_loop.exe(move || { let res = task(); EventLoop::add_local_void(|| { QuickJsRuntimeAdapter::do_with(|q_js_rt| { q_js_rt.run_pending_jobs_if_any(); }) }); res }) } pub fn add_task_to_event_loop<C, R: Send + 'static>(&self, task: C) -> impl Future<Output = R> where C: FnOnce() -> R + Send + 'static, { self.event_loop.add(move || { let res = task(); EventLoop::add_local_void(|| { QuickJsRuntimeAdapter::do_with(|q_js_rt| { q_js_rt.run_pending_jobs_if_any(); }); }); res }) } /// used to add tasks from the worker threads which require run_pending_jobs_if_any to run after it #[allow(dead_code)] pub(crate) fn add_local_task_to_event_loop<C>(consumer: C) where C: FnOnce(&QuickJsRuntimeAdapter) + 'static, { EventLoop::add_local_void(move || { QuickJsRuntimeAdapter::do_with(|q_js_rt| { consumer(q_js_rt); }); EventLoop::add_local_void(|| { QuickJsRuntimeAdapter::do_with(|q_js_rt| { q_js_rt.run_pending_jobs_if_any(); }) }) }); } } /// EsRuntime is the main public struct representing a JavaScript runtime. /// You can construct a new QuickJsRuntime by using the [QuickJsRuntimeBuilder] struct /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// let rt = QuickJsRuntimeBuilder::new().build(); /// ``` pub struct QuickJsRuntimeFacade { inner: Arc<QuickjsRuntimeFacadeInner>, } impl QuickJsRuntimeFacade { pub(crate) fn new(mut builder: QuickJsRuntimeBuilder) -> Self { let ret = Self { inner: Arc::new(QuickjsRuntimeFacadeInner { event_loop: EventLoop::new(), }), }; ret.exe_task_in_event_loop(|| { let rt_ptr = unsafe { q::JS_NewRuntime() }; let rt = QuickJsRuntimeAdapter::new(rt_ptr); QuickJsRuntimeAdapter::init_rt_for_current_thread(rt); functions::init_statics(); reflection::init_statics(); }); // init ref in q_js_rt let rti_weak = Arc::downgrade(&ret.inner); ret.exe_task_in_event_loop(move || { QuickJsRuntimeAdapter::do_with_mut(move |m_q_js_rt| { m_q_js_rt.init_rti_ref(rti_weak); }) }); // run single job in eventQueue to init thread_local weak<rtref> #[cfg(any( feature = "settimeout", feature = "setinterval", feature = "console", feature = "setimmediate" ))] { let res = crate::features::init(&ret); if res.is_err() { panic!("could not init features: {}", res.err().unwrap()); } } if let Some(interval) = builder.opt_gc_interval { let rti_ref: Weak<QuickjsRuntimeFacadeInner> = Arc::downgrade(&ret.inner); std::thread::spawn(move || loop { std::thread::sleep(interval); if let Some(el) = rti_ref.upgrade() { log::debug!("running gc from gc interval thread"); el.event_loop.add_void(|| { QJS_RT .try_with(|rc| { let rt = &*rc.borrow(); rt.as_ref().unwrap().gc(); }) .expect("QJS_RT.try_with failed"); }); } else { break; } }); } let init_hooks: Vec<_> = builder.runtime_init_hooks.drain(..).collect(); ret.exe_task_in_event_loop(move || { QuickJsRuntimeAdapter::do_with_mut(|q_js_rt| { for native_module_loader in builder.native_module_loaders { q_js_rt.add_native_module_loader(NativeModuleLoaderAdapter::new( native_module_loader, )); } for script_module_loader in builder.script_module_loaders { q_js_rt.add_script_module_loader(ScriptModuleLoaderAdapter::new( script_module_loader, )); } for compiled_module_loader in builder.compiled_module_loaders { q_js_rt.add_compiled_module_loader(CompiledModuleLoaderAdapter::new( compiled_module_loader, )); } q_js_rt.script_pre_processors = builder.script_pre_processors; if let Some(limit) = builder.opt_memory_limit_bytes { unsafe { q::JS_SetMemoryLimit(q_js_rt.runtime, limit as _); } } if let Some(threshold) = builder.opt_gc_threshold { unsafe { q::JS_SetGCThreshold(q_js_rt.runtime, threshold as _); } } if let Some(stack_size) = builder.opt_max_stack_size { unsafe { q::JS_SetMaxStackSize(q_js_rt.runtime, stack_size as _); } } if let Some(interrupt_handler) = builder.interrupt_handler { q_js_rt.set_interrupt_handler(interrupt_handler); } }) }); for hook in init_hooks { match hook(&ret) { Ok(_) => {} Err(e) => { panic!("runtime_init_hook failed: {}", e); } } } ret } /// get memory usage for this runtime pub async fn memory_usage(&self) -> MemoryUsage { self.loop_async(|rt| rt.memory_usage()).await } pub(crate) fn clear_contexts(&self) { log::trace!("EsRuntime::clear_contexts"); self.exe_task_in_event_loop(|| { let context_ids = QuickJsRuntimeAdapter::get_context_ids(); for id in context_ids { let _ = QuickJsRuntimeAdapter::remove_context(id.as_str()); } }); } /// this can be used to run a function in the event_queue thread for the QuickJSRuntime /// without borrowing the q_js_rt pub fn add_task_to_event_loop_void<C>(&self, task: C) where C: FnOnce() + Send + 'static, { self.inner.add_task_to_event_loop_void(task) } pub fn exe_task_in_event_loop<C, R: Send + 'static>(&self, task: C) -> R where C: FnOnce() -> R + Send + 'static, { self.inner.exe_task_in_event_loop(task) } pub fn add_task_to_event_loop<C, R: Send + 'static>(&self, task: C) -> impl Future<Output = R> where C: FnOnce() -> R + Send + 'static, { self.inner.add_task_to_event_loop(task) } /// this is how you add a closure to the worker thread which has an instance of the QuickJsRuntime /// this will run asynchronously /// # example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.add_rt_task_to_event_loop(|q_js_rt| { /// // here you are in the worker thread and you can use the quickjs_utils /// q_js_rt.gc(); /// }); /// ``` pub fn add_rt_task_to_event_loop<C, R: Send + 'static>( &self, task: C, ) -> impl Future<Output = R> where C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static, { self.inner.add_rt_task_to_event_loop(task) } pub fn add_rt_task_to_event_loop_void<C>(&self, task: C) where C: FnOnce(&QuickJsRuntimeAdapter) + Send + 'static, { self.inner.add_rt_task_to_event_loop_void(task) } /// used to add tasks from the worker threads which require run_pending_jobs_if_any to run after it #[allow(dead_code)] pub(crate) fn add_local_task_to_event_loop<C>(consumer: C) where C: FnOnce(&QuickJsRuntimeAdapter) + 'static, { QuickjsRuntimeFacadeInner::add_local_task_to_event_loop(consumer) } pub fn builder() -> QuickJsRuntimeBuilder { QuickJsRuntimeBuilder::new() } /// run the garbage collector asynchronously pub async fn gc(&self) { self.add_rt_task_to_event_loop(|q_js_rt| q_js_rt.gc()).await } /// run the garbage collector and wait for it to be done pub fn gc_sync(&self) { self.exe_rt_task_in_event_loop(|q_js_rt| q_js_rt.gc()) } /// this is how you add a closure to the worker thread which has an instance of the QuickJsRuntime /// this will run and return synchronously /// # example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::primitives; /// let rt = QuickJsRuntimeBuilder::new().build(); /// let res = rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// // here you are in the worker thread and you can use the quickjs_utils /// let val_ref = q_ctx.eval(Script::new("test.es", "(11 * 6);")).ok().expect("script failed"); /// primitives::to_i32(&val_ref).ok().expect("could not get i32") /// }); /// assert_eq!(res, 66); /// ``` pub fn exe_rt_task_in_event_loop<C, R>(&self, consumer: C) -> R where C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static, R: Send + 'static, { self.exe_task_in_event_loop(|| QuickJsRuntimeAdapter::do_with(consumer)) } /// this adds a rust function to JavaScript, it is added for all current and future contexts /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::values::{JsValueConvertable, JsValueFacade}; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// /// rt.set_function(&["com", "mycompany", "util"], "methodA", |q_ctx, args: Vec<JsValueFacade>|{ /// let a = args[0].get_i32(); /// let b = args[1].get_i32(); /// Ok((a * b).to_js_value_facade()) /// }).expect("set func failed"); /// /// let res = rt.eval_sync(None, Script::new("test.es", "let a = com.mycompany.util.methodA(13, 17); a * 2;")).ok().expect("script failed"); /// /// assert_eq!(res.get_i32(), (13*17*2)); /// ``` pub fn set_function<F>( &self, namespace: &[&str], name: &str, function: F, ) -> Result<(), JsError> where F: Fn(&QuickJsRealmAdapter, Vec<JsValueFacade>) -> Result<JsValueFacade, JsError> + Send + 'static, { let name = name.to_string(); let namespace = namespace .iter() .map(|s| s.to_string()) .collect::<Vec<String>>(); self.exe_rt_task_in_event_loop(move |q_js_rt| { let func_rc = Rc::new(function); let name = name.to_string(); q_js_rt.add_context_init_hook(move |_q_js_rt, realm| { let namespace_slice = namespace.iter().map(|s| s.as_str()).collect::<Vec<&str>>(); let ns = objects::get_namespace_q(realm, &namespace_slice, true)?; let func_rc = func_rc.clone(); let func = functions::new_function_q( realm, name.as_str(), move |realm, _this_ref, args| { let mut args_facades = vec![]; for arg_ref in args { args_facades.push(realm.to_js_value_facade(arg_ref)?); } let res = func_rc(realm, args_facades); match res { Ok(val_jsvf) => realm.from_js_value_facade(val_jsvf), Err(e) => Err(e), } }, 1, )?; objects::set_property2_q(realm, &ns, name.as_str(), &func, 0)?; Ok(()) }) }) } /// add a task the the "helper" thread pool pub fn add_helper_task<T>(task: T) where T: FnOnce() + Send + 'static, { log::trace!("adding a helper task"); HELPER_TASKS.add_task(task); } /// add an async task the the "helper" thread pool pub fn add_helper_task_async<R: Send + 'static, T: Future<Output = R> + Send + 'static>( task: T, ) -> impl Future<Output = Result<R, JoinError>> { log::trace!("adding an async helper task"); HELPER_TASKS.add_task_async(task) } /// create a new context besides the always existing main_context /// # Example /// ``` /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.create_context("my_context"); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let my_ctx = q_js_rt.get_context("my_context"); /// my_ctx.eval(Script::new("ctx_test.es", "this.myVar = 'only exists in my_context';")); /// }); /// ``` pub fn create_context(&self, id: &str) -> Result<(), JsError> { let id = id.to_string(); self.inner .event_loop .exe(move || QuickJsRuntimeAdapter::create_context(id.as_str())) } /// drop a context which was created earlier with a call to [create_context()](struct.EsRuntime.html#method.create_context) pub fn drop_context(&self, id: &str) -> anyhow::Result<()> { let id = id.to_string(); self.inner .event_loop .exe(move || QuickJsRuntimeAdapter::remove_context(id.as_str())) } } thread_local! { // Each thread has its own LRU cache with capacity 128 to limit the number of auto-created contexts // todo make this configurable via env.. static REALM_ID_LRU_CACHE: RefCell<LruCache<String, ()>> = RefCell::new(LruCache::new(NonZeroUsize::new(128).unwrap())); } fn loop_realm_func< R: Send + 'static, C: FnOnce(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> R + Send + 'static, >( realm_name: Option<String>, consumer: C, ) -> R { // housekeeping, lru map for realms // the problem with doing those in drop in a realm is that finalizers cant find the realm anymore // so we need to actively delete realms here instead of just making runtimeadapter::context a lru cache if let Some(realm_str) = realm_name.as_ref() { REALM_ID_LRU_CACHE.with(|cache_cell| { let mut cache = cache_cell.borrow_mut(); // it's ok if this str does not yet exist cache.promote(realm_str); }); } // run in existing realm let res: Either<R, C> = QuickJsRuntimeAdapter::do_with(|q_js_rt| { if let Some(realm_str) = realm_name.as_ref() { if let Some(realm) = q_js_rt.get_realm(realm_str) { Left(consumer(q_js_rt, realm)) } else { Right(consumer) } } else { Left(consumer(q_js_rt, q_js_rt.get_main_realm())) } }); match res { Left(r) => r, Right(consumer) => { // create realm first // if more than max present, drop the least used realm let realm_str = realm_name.expect("invalid state"); REALM_ID_LRU_CACHE.with(|cache_cell| { let mut cache = cache_cell.borrow_mut(); // it's ok if this str does not yet exist if cache.len() == cache.cap().get() { if let Some((_evicted_key, _evicted_value)) = cache.pop_lru() { // cleanup evicted key //QuickJsRuntimeAdapter::remove_context(evicted_key.as_str()) // .expect("could not destroy realm"); } } cache.put(realm_str.to_string(), ()); }); // create realm QuickJsRuntimeAdapter::do_with_mut(|m_rt| { let ctx = QuickJsRealmAdapter::new(realm_str.to_string(), m_rt); m_rt.contexts.insert(realm_str.to_string(), ctx); }); QuickJsRuntimeAdapter::do_with(|q_js_rt| { let realm = q_js_rt .get_realm(realm_str.as_str()) .expect("invalid state"); let hooks = &*q_js_rt.context_init_hooks.borrow(); for hook in hooks { let res = hook(q_js_rt, realm); if res.is_err() { panic!("realm init hook failed: {}", res.err().unwrap()); } } consumer(q_js_rt, realm) }) } } } impl QuickJsRuntimeFacade { pub fn create_realm(&self, name: &str) -> Result<(), JsError> { let name = name.to_string(); self.inner .event_loop .exe(move || QuickJsRuntimeAdapter::create_context(name.as_str())) } pub fn destroy_realm(&self, name: &str) -> anyhow::Result<()> { let name = name.to_string(); self.exe_task_in_event_loop(move || QuickJsRuntimeAdapter::remove_context(name.as_str())) } pub fn has_realm(&self, name: &str) -> Result<bool, JsError> { let name = name.to_string(); self.exe_rt_task_in_event_loop(move |rt| Ok(rt.get_realm(name.as_str()).is_some())) } /// add a job to the eventloop which will execute sync(placed at end of eventloop) pub fn loop_sync<R: Send + 'static, C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static>( &self, consumer: C, ) -> R { self.exe_rt_task_in_event_loop(consumer) } pub fn loop_sync_mut< R: Send + 'static, C: FnOnce(&mut QuickJsRuntimeAdapter) -> R + Send + 'static, >( &self, consumer: C, ) -> R { self.exe_task_in_event_loop(|| QuickJsRuntimeAdapter::do_with_mut(consumer)) } /// add a job to the eventloop which will execute async(placed at end of eventloop) /// returns a Future which can be waited ob with .await pub fn loop_async< R: Send + 'static, C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static, >( &self, consumer: C, ) -> Pin<Box<dyn Future<Output = R> + Send>> { Box::pin(self.add_rt_task_to_event_loop(consumer)) } /// add a job to the eventloop (placed at end of eventloop) without expecting a result pub fn loop_void<C: FnOnce(&QuickJsRuntimeAdapter) + Send + 'static>(&self, consumer: C) { self.add_rt_task_to_event_loop_void(consumer) } /// add a job to the eventloop which will be executed synchronously (placed at end of eventloop) pub fn loop_realm_sync< R: Send + 'static, C: FnOnce(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> R + Send + 'static, >( &self, realm_name: Option<&str>, consumer: C, ) -> R { let realm_name = realm_name.map(|s| s.to_string()); self.exe_task_in_event_loop(|| loop_realm_func(realm_name, consumer)) } /// add a job to the eventloop which will be executed async (placed at end of eventloop) /// returns a Future which can be waited ob with .await pub fn loop_realm< R: Send + 'static, C: FnOnce(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> R + Send + 'static, >( &self, realm_name: Option<&str>, consumer: C, ) -> Pin<Box<dyn Future<Output = R> + Send>> { let realm_name = realm_name.map(|s| s.to_string()); Box::pin(self.add_task_to_event_loop(|| loop_realm_func(realm_name, consumer))) } /// add a job for a specific realm without expecting a result. /// the job will be added to the end of the eventloop pub fn loop_realm_void< C: FnOnce(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) + Send + 'static, >( &self, realm_name: Option<&str>, consumer: C, ) { let realm_name = realm_name.map(|s| s.to_string()); self.add_task_to_event_loop_void(|| loop_realm_func(realm_name, consumer)); } /// Evaluate a script asynchronously /// # Example /// ```rust /// use futures::executor::block_on; /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// let rt = QuickJsRuntimeBuilder::new().build(); /// let my_script = r#" /// console.log("i'm a script"); /// "#; /// block_on(rt.eval(None, Script::new("my_script.js", my_script))).expect("script failed"); /// ``` #[allow(clippy::type_complexity)] pub fn eval( &self, realm_name: Option<&str>, script: Script, ) -> Pin<Box<dyn Future<Output = Result<JsValueFacade, JsError>> + Send>> { self.loop_realm(realm_name, |_rt, realm| { let res = realm.eval(script); match res { Ok(jsvr) => realm.to_js_value_facade(&jsvr), Err(e) => Err(e), } }) } /// Evaluate a script and return the result synchronously /// # example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// let rt = QuickJsRuntimeBuilder::new().build(); /// let script = Script::new("my_file.js", "(9 * 3);"); /// let res = rt.eval_sync(None, script).ok().expect("script failed"); /// assert_eq!(res.get_i32(), 27); /// ``` #[allow(clippy::type_complexity)] pub fn eval_sync( &self, realm_name: Option<&str>, script: Script, ) -> Result<JsValueFacade, JsError> { self.loop_realm_sync(realm_name, |_rt, realm| { let res = realm.eval(script); match res { Ok(jsvr) => realm.to_js_value_facade(&jsvr), Err(e) => Err(e), } }) } /// evaluate a module, you need this if you want to compile a script that contains static imports /// e.g. /// ```javascript /// import {util} from 'file.js'; /// console.log(util(1, 2, 3)); /// ``` /// please note that the module is cached under the absolute path you passed in the Script object /// and thus you should take care to make the path unique (hence the absolute_ name) /// also to use this you need to build the QuickJsRuntimeFacade with a module loader /// # example /// ```rust /// use futures::executor::block_on; /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::modules::ScriptModuleLoader; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter; /// struct TestModuleLoader {} /// impl ScriptModuleLoader for TestModuleLoader { /// fn normalize_path(&self, _realm: &QuickJsRealmAdapter, ref_path: &str,path: &str) -> Option<String> { /// Some(path.to_string()) /// } /// /// fn load_module(&self, _realm: &QuickJsRealmAdapter, absolute_path: &str) -> String { /// "export const util = function(a, b, c){return a+b+c;};".to_string() /// } /// } /// let rt = QuickJsRuntimeBuilder::new().script_module_loader(TestModuleLoader{}).build(); /// let script = Script::new("/opt/files/my_module.js", r#" /// import {util} from 'other_module.js';\n /// console.log(util(1, 2, 3)); /// "#); /// // in real life you would .await this /// let _res = block_on(rt.eval_module(None, script)); /// ``` pub fn eval_module( &self, realm_name: Option<&str>, script: Script, ) -> Pin<Box<dyn Future<Output = Result<JsValueFacade, JsError>> + Send>> { self.loop_realm(realm_name, |_rt, realm| { let res = realm.eval_module(script)?; realm.to_js_value_facade(&res) }) } /// evaluate a module synchronously, you need this if you want to compile a script that contains static imports /// e.g. /// ```javascript /// import {util} from 'file.js'; /// console.log(util(1, 2, 3)); /// ``` /// please note that the module is cached under the absolute path you passed in the Script object /// and thus you should take care to make the path unique (hence the absolute_ name) /// also to use this you need to build the QuickJsRuntimeFacade with a module loader /// # example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::modules::ScriptModuleLoader; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter; /// struct TestModuleLoader {} /// impl ScriptModuleLoader for TestModuleLoader { /// fn normalize_path(&self, _realm: &QuickJsRealmAdapter, ref_path: &str,path: &str) -> Option<String> { /// Some(path.to_string()) /// } /// /// fn load_module(&self, _realm: &QuickJsRealmAdapter, absolute_path: &str) -> String { /// "export const util = function(a, b, c){return a+b+c;};".to_string() /// } /// } /// let rt = QuickJsRuntimeBuilder::new().script_module_loader(TestModuleLoader{}).build(); /// let script = Script::new("/opt/files/my_module.js", r#" /// import {util} from 'other_module.js';\n /// console.log(util(1, 2, 3)); /// "#); /// let _res = rt.eval_module_sync(None, script); /// ``` pub fn eval_module_sync( &self, realm_name: Option<&str>, script: Script, ) -> Result<JsValueFacade, JsError> { self.loop_realm_sync(realm_name, |_rt, realm| { let res = realm.eval_module(script)?; realm.to_js_value_facade(&res) }) } /// invoke a function in the engine and get the result synchronously /// # example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::values::JsValueConvertable; /// let rt = QuickJsRuntimeBuilder::new().build(); /// let script = Script::new("my_file.es", "this.com = {my: {methodA: function(a, b, someStr, someBool){return a*b;}}};"); /// rt.eval_sync(None, script).ok().expect("script failed"); /// let res = rt.invoke_function_sync(None, &["com", "my"], "methodA", vec![7i32.to_js_value_facade(), 5i32.to_js_value_facade(), "abc".to_js_value_facade(), true.to_js_value_facade()]).ok().expect("func failed"); /// assert_eq!(res.get_i32(), 35); /// ``` #[warn(clippy::type_complexity)] pub fn invoke_function_sync( &self, realm_name: Option<&str>, namespace: &[&str], method_name: &str, args: Vec<JsValueFacade>, ) -> Result<JsValueFacade, JsError> { let movable_namespace: Vec<String> = namespace.iter().map(|s| s.to_string()).collect(); let movable_method_name = method_name.to_string(); self.loop_realm_sync(realm_name, move |_rt, realm| { let args_adapters: Vec<QuickJsValueAdapter> = args .into_iter() .map(|jsvf| realm.from_js_value_facade(jsvf).expect("conversion failed")) .collect(); let namespace = movable_namespace .iter() .map(|s| s.as_str()) .collect::<Vec<&str>>(); let res = realm.invoke_function_by_name( namespace.as_slice(), movable_method_name.as_str(), args_adapters.as_slice(), ); match res { Ok(jsvr) => realm.to_js_value_facade(&jsvr), Err(e) => Err(e), } }) } /// invoke a function in the engine asynchronously /// N.B. func_name is not a &str because of <https://github.com/rust-lang/rust/issues/56238> (i think) /// # example /// ```rust
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
true
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/reflection/eventtarget.rs
src/reflection/eventtarget.rs
//! EventTarget utils //! use crate::jsutils::JsError; use crate::quickjs_utils; use crate::quickjs_utils::objects::{create_object_q, set_property_q}; use crate::quickjs_utils::primitives::from_bool; use crate::quickjs_utils::{functions, objects, parse_args, primitives}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use crate::reflection::{get_proxy, get_proxy_instance_info, Proxy}; use libquickjs_sys as q; use std::collections::HashMap; fn with_proxy_instances_map<C, R>( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, consumer: C, ) -> R where C: FnOnce( &HashMap<usize, HashMap<String, HashMap<QuickJsValueAdapter, QuickJsValueAdapter>>>, ) -> R, { let listeners = &*q_ctx.proxy_event_listeners.borrow(); if listeners.contains_key(proxy_class_name) { let proxy_instance_map = listeners.get(proxy_class_name).unwrap(); consumer(proxy_instance_map) } else { consumer(&HashMap::new()) } } fn with_proxy_instances_map_mut<C, R>( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, consumer: C, ) -> R where C: FnOnce( &mut HashMap<usize, HashMap<String, HashMap<QuickJsValueAdapter, QuickJsValueAdapter>>>, ) -> R, { let listeners = &mut *q_ctx.proxy_event_listeners.borrow_mut(); if !listeners.contains_key(proxy_class_name) { listeners.insert(proxy_class_name.to_string(), HashMap::new()); } let proxy_instance_map = listeners.get_mut(proxy_class_name).unwrap(); consumer(proxy_instance_map) } fn with_listener_map_mut<C, R>( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, instance_id: usize, event_id: &str, consumer: C, ) -> R where C: FnOnce(&mut HashMap<QuickJsValueAdapter, QuickJsValueAdapter>) -> R, { with_proxy_instances_map_mut(q_ctx, proxy_class_name, |proxy_instance_map| { let event_id_map = proxy_instance_map.entry(instance_id).or_default(); if !event_id_map.contains_key(event_id) { event_id_map.insert(event_id.to_string(), HashMap::new()); } let listener_map = event_id_map.get_mut(event_id).unwrap(); consumer(listener_map) }) } fn with_listener_map<C, R>( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, instance_id: usize, event_id: &str, consumer: C, ) -> R where C: FnOnce(&HashMap<QuickJsValueAdapter, QuickJsValueAdapter>) -> R, { with_proxy_instances_map(q_ctx, proxy_class_name, |proxy_instance_map| { if let Some(event_id_map) = proxy_instance_map.get(&instance_id) { if let Some(listener_map) = event_id_map.get(event_id) { consumer(listener_map) } else { consumer(&HashMap::new()) } } else { consumer(&HashMap::new()) } }) } fn with_static_listener_map<C, R>( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, event_id: &str, consumer: C, ) -> R where C: FnOnce(&mut HashMap<QuickJsValueAdapter, QuickJsValueAdapter>) -> R, { let static_listeners = &mut *q_ctx.proxy_static_event_listeners.borrow_mut(); if !static_listeners.contains_key(proxy_class_name) { static_listeners.insert(proxy_class_name.to_string(), HashMap::new()); } let proxy_static_map = static_listeners.get_mut(proxy_class_name).unwrap(); if !proxy_static_map.contains_key(event_id) { proxy_static_map.insert(event_id.to_string(), HashMap::new()); } let event_map = proxy_static_map.get_mut(event_id).unwrap(); consumer(event_map) } pub fn add_event_listener( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, event_id: &str, instance_id: usize, listener_func: QuickJsValueAdapter, options_obj: QuickJsValueAdapter, ) { log::trace!( "eventtarget::add_listener_to_map p:{} e:{} i:{}", proxy_class_name, event_id, instance_id ); with_listener_map_mut(q_ctx, proxy_class_name, instance_id, event_id, |map| { let _ = map.insert(listener_func, options_obj); }) } pub fn add_static_event_listener( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, event_id: &str, listener_func: QuickJsValueAdapter, options_obj: QuickJsValueAdapter, ) { log::trace!( "eventtarget::add_static_listener_to_map p:{} e:{}", proxy_class_name, event_id ); with_static_listener_map(q_ctx, proxy_class_name, event_id, |map| { let _ = map.insert(listener_func, options_obj); }) } pub fn remove_event_listener( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, event_id: &str, instance_id: usize, listener_func: &QuickJsValueAdapter, ) { log::trace!( "eventtarget::remove_listener_from_map p:{} e:{} i:{}", proxy_class_name, event_id, instance_id ); with_listener_map_mut(q_ctx, proxy_class_name, instance_id, event_id, |map| { let _ = map.remove(listener_func); }) } pub fn remove_static_event_listener( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, event_id: &str, listener_func: &QuickJsValueAdapter, ) { log::trace!( "eventtarget::remove_static_listener_from_map p:{} e:{}", proxy_class_name, event_id ); with_static_listener_map(q_ctx, proxy_class_name, event_id, |map| { let _ = map.remove(listener_func); }) } fn remove_map(q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, instance_id: usize) { log::trace!( "eventtarget::remove_map p:{} i:{}", proxy_class_name, instance_id ); with_proxy_instances_map_mut(q_ctx, proxy_class_name, |map| { let _ = map.remove(&instance_id); }); } /// dispatch an Event on an instance of a Proxy class /// the return value is false if event is cancelable and at least one of the event listeners which received event called Event.preventDefault. Otherwise it returns true pub fn dispatch_event( q_ctx: &QuickJsRealmAdapter, proxy: &Proxy, instance_id: usize, event_id: &str, event: QuickJsValueAdapter, ) -> Result<bool, JsError> { let proxy_class_name = proxy.get_class_name(); with_listener_map( q_ctx, proxy_class_name.as_str(), instance_id, event_id, |listeners| -> Result<(), JsError> { let func_args = [event]; for entry in listeners { let listener = entry.0; let _res = functions::call_function_q(q_ctx, listener, &func_args, None)?; // todo chekc if _res is bool, for cancel and such // and if event is cancelabble and preventDefault was called and such } Ok(()) }, )?; Ok(true) } /// dispatch an Event on a Proxy class /// the return value is false if event is cancelable and at least one of the event listeners which received event called Event.preventDefault. Otherwise it returns true pub fn dispatch_static_event( q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, event_id: &str, event: QuickJsValueAdapter, ) -> Result<bool, JsError> { with_static_listener_map( q_ctx, proxy_class_name, event_id, |listeners| -> Result<(), JsError> { let func_args = [event]; for entry in listeners { let listener = entry.0; let _res = functions::call_function_q(q_ctx, listener, &func_args, None)?; // todo chekc if _res is bool, for cancel and such // and if event is cancelabble and preventDefault was called and such } Ok(()) }, )?; Ok(true) } pub fn _set_event_bubble_target() { unimplemented!() } fn events_instance_finalizer(q_ctx: &QuickJsRealmAdapter, proxy_class_name: &str, id: usize) { // drop all listeners, remove_map(q_ctx, proxy_class_name, id); } pub(crate) fn impl_event_target(proxy: Proxy) -> Proxy { // add (static) addEventListener(), dispatchEvent(), removeEventListener() // a fn getEventsObj will be used to conditionally create and return an Object with Sets per eventId to store the listeners let proxy_class_name = proxy.get_class_name(); let mut proxy = proxy; if proxy.is_event_target { proxy = proxy .native_method("addEventListener", Some(ext_add_event_listener)) .native_method("removeEventListener", Some(ext_remove_event_listener)) .native_method("dispatchEvent", Some(ext_dispatch_event)) .finalizer(move |_rt, q_ctx, id| { let n = proxy_class_name.as_str(); events_instance_finalizer(q_ctx, n, id); }); } if proxy.is_static_event_target { // todo, these should be finalized before context is destroyed, we really need a hook in QuickJsContext for that proxy = proxy .static_native_method("addEventListener", Some(ext_add_static_event_listener)) .static_native_method( "removeEventListener", Some(ext_remove_static_event_listener), ) .static_native_method("dispatchEvent", Some(ext_dispatch_static_event)); } proxy } unsafe extern "C" fn ext_add_event_listener( ctx: *mut q::JSContext, this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { // require 2 or 3 args, string, function, object // if third is boolean it is option {capture: true} // events_obj will be structured like this // ___eventListeners___: {eventId<String>: Map<Function, Object>} // the key of the map is the function, the value are the options let res = QuickJsRealmAdapter::with_context(ctx, |q_ctx| { let args = parse_args(ctx, argc, argv); let this_ref = QuickJsValueAdapter::new(ctx, this_val, true, true, "add_event_listener_this"); let proxy_info = get_proxy_instance_info(this_ref.borrow_value()); if args.len() < 2 || !args[0].is_string() || !functions::is_function_q(q_ctx, &args[1]) { Err(JsError::new_str("addEventListener requires at least 2 arguments (eventId: String and Listener: Function")) } else { let event_id = primitives::to_string_q(q_ctx, &args[0])?; let listener_func = args[1].clone(); // use the passed options arg or create a new obj let options_obj = if args.len() == 3 && args[2].is_object() { args[2].clone() } else { create_object_q(q_ctx)? }; // if the third args was a boolean then set that bool as the capture option if args.len() == 3 && args[2].is_bool() { set_property_q(q_ctx, &options_obj, "capture", &args[2])?; } add_event_listener( q_ctx, proxy_info.class_name.as_str(), event_id.as_str(), proxy_info.id, listener_func, options_obj, ); Ok(()) } }); match res { Ok(_) => quickjs_utils::new_null(), Err(e) => QuickJsRealmAdapter::report_ex_ctx(ctx, format!("{e}").as_str()), } } unsafe extern "C" fn ext_remove_event_listener( ctx: *mut q::JSContext, this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { let res = QuickJsRealmAdapter::with_context(ctx, |q_ctx| { let args = parse_args(ctx, argc, argv); let this_ref = QuickJsValueAdapter::new(ctx, this_val, true, true, "remove_event_listener_this"); let proxy_info = get_proxy_instance_info(this_ref.borrow_value()); if args.len() != 2 || !args[0].is_string() || !functions::is_function_q(q_ctx, &args[1]) { Err(JsError::new_str("removeEventListener requires at least 2 arguments (eventId: String and Listener: Function")) } else { let event_id = primitives::to_string_q(q_ctx, &args[0])?; let listener_func = args[1].clone(); remove_event_listener( q_ctx, proxy_info.class_name.as_str(), event_id.as_str(), proxy_info.id, &listener_func, ); Ok(()) } }); match res { Ok(_) => quickjs_utils::new_null(), Err(e) => QuickJsRealmAdapter::report_ex_ctx(ctx, format!("{e}").as_str()), } } unsafe extern "C" fn ext_dispatch_event( ctx: *mut q::JSContext, this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { let res = QuickJsRealmAdapter::with_context(ctx, |q_ctx| { let args = parse_args(ctx, argc, argv); let this_ref = QuickJsValueAdapter::new(ctx, this_val, true, true, "remove_event_listener_this"); let proxy_info = get_proxy_instance_info(this_ref.borrow_value()); if args.len() != 2 || !args[0].is_string() { Err(JsError::new_str( "dispatchEvent requires at least 2 arguments (eventId: String and eventObj: Object)", )) } else { let event_id = primitives::to_string_q(q_ctx, &args[0])?; let evt_obj = args[1].clone(); let proxy = get_proxy(q_ctx, proxy_info.class_name.as_str()).unwrap(); let res = dispatch_event(q_ctx, &proxy, proxy_info.id, event_id.as_str(), evt_obj)?; Ok(res) } }); match res { Ok(res) => { let b_ref = from_bool(res); b_ref.clone_value_incr_rc() } Err(e) => QuickJsRealmAdapter::report_ex_ctx(ctx, format!("{e}").as_str()), } } unsafe fn get_static_proxy_class_name( q_ctx: &QuickJsRealmAdapter, obj: &QuickJsValueAdapter, ) -> String { let proxy_name_ref = objects::get_property(q_ctx.context, obj, "name") .ok() .unwrap(); primitives::to_string(q_ctx.context, &proxy_name_ref) .ok() .unwrap() } unsafe extern "C" fn ext_add_static_event_listener( ctx: *mut q::JSContext, this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { let res = QuickJsRealmAdapter::with_context(ctx, |q_ctx| { let args = parse_args(ctx, argc, argv); let this_ref = QuickJsValueAdapter::new(ctx, this_val, true, true, "add_event_listener_this"); let proxy_name = get_static_proxy_class_name(q_ctx, &this_ref); if args.len() < 2 || !args[0].is_string() || !functions::is_function_q(q_ctx, &args[1]) { Err(JsError::new_str("addEventListener requires at least 2 arguments (eventId: String and Listener: Function")) } else { let event_id = primitives::to_string_q(q_ctx, &args[0])?; let listener_func = args[1].clone(); // use the passed options arg or create a new obj let options_obj = if args.len() == 3 && args[2].is_object() { args[2].clone() } else { create_object_q(q_ctx)? }; // if the third args was a boolean then set that bool as the capture option if args.len() == 3 && args[2].is_bool() { set_property_q(q_ctx, &options_obj, "capture", &args[2])?; } add_static_event_listener( q_ctx, proxy_name.as_str(), event_id.as_str(), listener_func, options_obj, ); Ok(()) } }); match res { Ok(_) => quickjs_utils::new_null(), Err(e) => QuickJsRealmAdapter::report_ex_ctx(ctx, format!("{e}").as_str()), } } unsafe extern "C" fn ext_remove_static_event_listener( ctx: *mut q::JSContext, this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { let res = QuickJsRealmAdapter::with_context(ctx, |q_ctx| { let args = parse_args(ctx, argc, argv); let this_ref = QuickJsValueAdapter::new(ctx, this_val, true, true, "remove_event_listener_this"); let proxy_name = get_static_proxy_class_name(q_ctx, &this_ref); if args.len() != 2 || !args[0].is_string() || !functions::is_function_q(q_ctx, &args[1]) { Err(JsError::new_str("removeEventListener requires at least 2 arguments (eventId: String and Listener: Function")) } else { let event_id = primitives::to_string_q(q_ctx, &args[0])?; let listener_func = args[1].clone(); remove_static_event_listener( q_ctx, proxy_name.as_str(), event_id.as_str(), &listener_func, ); Ok(()) } }); match res { Ok(_) => quickjs_utils::new_null(), Err(e) => QuickJsRealmAdapter::report_ex_ctx(ctx, format!("{e}").as_str()), } } unsafe extern "C" fn ext_dispatch_static_event( ctx: *mut q::JSContext, this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { let res = QuickJsRealmAdapter::with_context(ctx, |q_ctx| { let args = parse_args(ctx, argc, argv); let this_ref = QuickJsValueAdapter::new(ctx, this_val, true, true, "remove_event_listener_this"); let proxy_name = get_static_proxy_class_name(q_ctx, &this_ref); if args.len() != 2 || !args[0].is_string() { Err(JsError::new_str( "dispatchEvent requires at least 2 arguments (eventId: String and eventObj: Object)", )) } else { let event_id = primitives::to_string_q(q_ctx, &args[0])?; let evt_obj = args[1].clone(); let res = dispatch_static_event(q_ctx, proxy_name.as_str(), event_id.as_str(), evt_obj)?; Ok(res) } }); match res { Ok(res) => { let b_ref = from_bool(res); b_ref.clone_value_incr_rc() } Err(e) => QuickJsRealmAdapter::report_ex_ctx(ctx, format!("{e}").as_str()), } } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::Script; use crate::quickjs_utils::get_global_q; use crate::quickjs_utils::objects::{create_object_q, get_property_q}; use crate::quickjs_utils::primitives::to_i32; use crate::reflection::eventtarget::dispatch_event; use crate::reflection::{get_proxy, Proxy}; use std::sync::{Arc, Mutex}; #[test] fn test_proxy_eh() { let instance_ids: Arc<Mutex<Vec<usize>>> = Arc::new(Mutex::new(vec![])); let instance_ids2 = instance_ids.clone(); let rt = init_test_rt(); let ct = rt.exe_rt_task_in_event_loop(move |q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); Proxy::new() .namespace(&[]) .constructor(move |_rt, _q, id, _args| { log::debug!("construct id={}", id); let vec = &mut *instance_ids2.lock().unwrap(); vec.push(id); Ok(()) }) .finalizer(|_rt, _q_ctx, id| { log::debug!("finalize id={}", id); }) .name("MyThing") .event_target() .install(q_ctx, true) .expect("proxy failed"); match q_ctx.eval(Script::new( "test_proxy_eh.es", "\ this.called = false;\ let test_proxy_eh_instance = new MyThing();\ this.ct = 0;\ let listener1 = (evt) => {this.ct++;};\ let listener2 = (evt) => {this.ct++;};\ test_proxy_eh_instance.addEventListener('someEvent', listener1);\ test_proxy_eh_instance.addEventListener('someEvent', listener2);\ test_proxy_eh_instance.removeEventListener('someEvent', listener2);\ ", )) { Ok(_) => {} Err(e) => { log::error!("script failed: {}", e); panic!("script failed: {}", e); } }; let global = get_global_q(q_ctx); let proxy = get_proxy(q_ctx, "MyThing").unwrap(); let vec = &mut *instance_ids.lock().unwrap(); let id = vec[0]; let evt = create_object_q(q_ctx).ok().unwrap(); let _ = dispatch_event(q_ctx, &proxy, id, "someEvent", evt).expect("dispatch failed"); let ct_ref = get_property_q(q_ctx, &global, "ct").ok().unwrap(); to_i32(&ct_ref).ok().unwrap() }); log::info!("ok was {}", ct); assert_eq!(ct, 1); } #[test] fn test_proxy_eh_rcs() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); Proxy::new() .namespace(&[]) .constructor(move |_rt, _q, id, _args| { log::debug!("construct id={}", id); Ok(()) }) .finalizer(|_rt, _q_ctx, id| { log::debug!("finalize id={}", id); }) .name("MyThing") .event_target() .install(q_ctx, true) .expect("proxy failed"); q_ctx .eval(Script::new("e.es", "let target = new MyThing();")) .expect("constr failed"); let _target_ref = q_ctx .eval(Script::new("t.es", "(target);")) .expect("could not get target"); #[cfg(feature = "bellard")] assert_eq!(_target_ref.get_ref_count(), 2); // one for me one for global q_ctx .eval(Script::new( "r.es", "target.addEventListener('someEvent', (evt) => {console.log('got event');});", )) .expect("addlistnrfailed"); #[cfg(feature = "bellard")] assert_eq!(_target_ref.get_ref_count(), 2); // one for me one for global }); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/reflection/mod.rs
src/reflection/mod.rs
//! utils for implementing proxy classes which can be used to use rust structs from JS (define method/getters/setters/etc) use crate::jsutils::JsError; use crate::quickjs_utils; use crate::quickjs_utils::functions::new_native_function_q; use crate::quickjs_utils::objects::{get_property, set_property2_q}; use crate::quickjs_utils::primitives::from_string; use crate::quickjs_utils::{atoms, errors, functions, objects, parse_args, primitives}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; use log::trace; use rand::{thread_rng, Rng}; use std::cell::RefCell; use std::collections::HashMap; use std::os::raw::{c_char, c_void}; use std::rc::Rc; pub type JsProxyInstanceId = usize; pub mod eventtarget; pub type ProxyConstructor = dyn Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, usize, &[QuickJsValueAdapter], ) -> Result<(), JsError> + 'static; pub type ProxyFinalizer = dyn Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter, usize) + 'static; pub type ProxyMethod = dyn Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> + 'static; pub type ProxyNativeMethod = q::JSCFunction; pub type ProxyStaticMethod = dyn Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> + 'static; pub type ProxyStaticNativeMethod = q::JSCFunction; pub type ProxyStaticGetter = dyn Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> Result<QuickJsValueAdapter, JsError> + 'static; pub type ProxyStaticSetter = dyn Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter, QuickJsValueAdapter) -> Result<(), JsError> + 'static; pub type ProxyStaticCatchAllGetter = dyn Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &str) -> Result<QuickJsValueAdapter, JsError> + 'static; pub type ProxyStaticCatchAllSetter = dyn Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &str, QuickJsValueAdapter, ) -> Result<(), JsError> + 'static; pub type ProxyGetter = dyn Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize) -> Result<QuickJsValueAdapter, JsError> + 'static; pub type ProxyCatchAllGetter = dyn Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, &str, ) -> Result<QuickJsValueAdapter, JsError> + 'static; pub type ProxySetter = dyn Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, QuickJsValueAdapter, ) -> Result<(), JsError> + 'static; pub type ProxyCatchAllSetter = dyn Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, &str, QuickJsValueAdapter, ) -> Result<(), JsError> + 'static; static CNAME: &str = "ProxyInstanceClass\0"; static SCNAME: &str = "ProxyStaticClass\0"; thread_local! { #[cfg(feature = "quickjs-ng")] static PROXY_STATIC_EXOTIC: RefCell<q::JSClassExoticMethods> = RefCell::new(q::JSClassExoticMethods { get_own_property: None, get_own_property_names: None, delete_property: None, define_own_property: None, has_property: Some(proxy_static_has_prop), get_property: Some(proxy_static_get_prop), set_property: Some(proxy_static_set_prop), }); #[cfg(feature = "bellard")] static PROXY_STATIC_EXOTIC: RefCell<q::JSClassExoticMethods> = RefCell::new(q::JSClassExoticMethods { get_own_property: None, get_own_property_names: None, delete_property: None, define_own_property: None, has_property: Some(proxy_static_has_prop), get_property: Some(proxy_static_get_prop), set_property: Some(proxy_static_set_prop), get_prototype: None, is_extensible: None, prevent_extensions: None, set_prototype: None }); #[cfg(feature = "quickjs-ng")] static PROXY_INSTANCE_EXOTIC: RefCell<q::JSClassExoticMethods> = RefCell::new(q::JSClassExoticMethods { get_own_property: None, get_own_property_names: None, delete_property: None, define_own_property: None, has_property: Some(proxy_instance_has_prop), get_property: Some(proxy_instance_get_prop), set_property: Some(proxy_instance_set_prop), }); #[cfg(feature = "bellard")] static PROXY_INSTANCE_EXOTIC: RefCell<q::JSClassExoticMethods> = RefCell::new(q::JSClassExoticMethods { get_own_property: None, get_own_property_names: None, delete_property: None, define_own_property: None, has_property: Some(proxy_instance_has_prop), get_property: Some(proxy_instance_get_prop), set_property: Some(proxy_instance_set_prop), get_prototype: None, is_extensible: None, prevent_extensions: None, set_prototype: None }); static PROXY_STATIC_CLASS_DEF: RefCell<q::JSClassDef> = { PROXY_STATIC_EXOTIC.with(|e_rc|{ let exotic = &mut *e_rc.borrow_mut(); RefCell::new(q::JSClassDef { class_name: SCNAME.as_ptr() as *const c_char, finalizer: None, gc_mark: None, call: None, exotic, }) }) }; static PROXY_INSTANCE_CLASS_DEF: RefCell<q::JSClassDef> = { PROXY_INSTANCE_EXOTIC.with(|e_rc|{ let exotic = &mut *e_rc.borrow_mut(); RefCell::new(q::JSClassDef { class_name: CNAME.as_ptr() as *const c_char, finalizer: Some(finalizer), gc_mark: None, call: None, exotic, }) }) }; pub static PROXY_STATIC_CLASS_ID: RefCell<u32> = { let class_id: u32 = QuickJsRuntimeAdapter::do_with(|q_js_rt| { q_js_rt.new_class_id() }); log::trace!("got static class id {}", class_id); PROXY_STATIC_CLASS_DEF.with(|cd_rc| { let class_def = &*cd_rc.borrow(); QuickJsRuntimeAdapter::do_with(|q_js_rt| { let res = unsafe { q::JS_NewClass(q_js_rt.runtime, class_id, class_def) }; log::trace!("new static class res {}", res); // todo res should be 0 for ok }); }); RefCell::new(class_id) }; pub static PROXY_INSTANCE_CLASS_ID: RefCell<u32> = { let class_id: u32 = QuickJsRuntimeAdapter::do_with(|q_js_rt| { q_js_rt.new_class_id() }); log::trace!("got class id {}", class_id); PROXY_INSTANCE_CLASS_DEF.with(|cd_rc| { let class_def = &*cd_rc.borrow(); QuickJsRuntimeAdapter::do_with(|q_js_rt| { let res = unsafe { q::JS_NewClass(q_js_rt.runtime, class_id, class_def) }; log::trace!("new class res {}", res); // todo res should be 0 for ok }); }); RefCell::new(class_id) }; } const MAX_INSTANCE_NUM: usize = u32::MAX as usize; pub(crate) fn init_statics() { PROXY_INSTANCE_CLASS_ID.with(|_rc| { // }); } fn next_id(proxy: &Proxy) -> usize { let mappings = &*proxy.proxy_instance_id_mappings.borrow(); if mappings.len() == MAX_INSTANCE_NUM { panic!("too many instances"); // todo report ex } let mut rng = thread_rng(); let mut r: usize = rng.r#gen(); while mappings.contains_key(&r) { r += 1; } r } /// The Proxy struct can be used to create a class in JavaScript who's methods can be implemented in rust /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::reflection::Proxy; /// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use std::cell::RefCell; /// use std::collections::HashMap; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::jsutils::Script; /// /// struct MyFunkyStruct{ /// name: String /// } /// /// impl Drop for MyFunkyStruct {fn drop(&mut self) { /// println!("Funky drop: {}", self.name.as_str()); /// } /// } /// /// thread_local! { /// static INSTANCES: RefCell<HashMap<usize, MyFunkyStruct>> = RefCell::new(HashMap::new()); /// } /// /// //create a new EsRuntime /// let rt = QuickJsRuntimeBuilder::new().build(); /// /// // install our proxy class as com.hirofa.FunkyClass /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// Proxy::new() /// .namespace(&["com", "hirofa"]) /// .name("FunkyClass") /// // the constructor is called when a script does new com.hirofa.FunkyClass, the reflection utils /// // generate an instance_id which may be used to identify the instance /// .constructor(|rt, q_ctx: &QuickJsRealmAdapter, instance_id: usize, args: &[QuickJsValueAdapter]| { /// // we'll assume our script always constructs the Proxy with a single name argument /// let name = primitives::to_string_q(q_ctx, &args[0]).ok().expect("bad constructor! bad!"); /// // create a new instance of our struct and store it in a map /// let instance = MyFunkyStruct{name}; /// // store our struct in a thread_local map /// INSTANCES.with(move |rc| { /// let map = &mut *rc.borrow_mut(); /// map.insert(instance_id, instance); /// }); /// // return Ok, or Err if the constructor failed (e.g. wrong args were passed) /// Ok(()) /// }) /// // next we create a simple getName method, this will return a String /// .method("getName", |rt, q_ctx, instance_id, args| { /// INSTANCES.with(move |rc| { /// let map = & *rc.borrow(); /// let instance = map.get(instance_id).unwrap(); /// primitives::from_string_q(q_ctx, instance.name.as_str()) /// }) /// }) /// // and lastly (but very important) implement a finalizer so our rust struct may be dropped /// .finalizer(|rt, q_ctx, instance_id| { /// INSTANCES.with(move |rc| { /// let map = &mut *rc.borrow_mut(); /// map.remove(&instance_id); /// }); /// }) /// // install the Proxy in the context /// .install(q_ctx, true).expect("proxy install failed"); /// }); /// /// match rt.eval_sync(None, Script::new("test_proxy.es", /// "{let inst = new com.hirofa.FunkyClass('FooBar'); let name = inst.getName(); inst = null; name;}" /// )) { /// Ok(name_esvf) => { /// // assert correct getName result /// assert_eq!(name_esvf.get_str(), "FooBar"); /// let i_ct = INSTANCES.with(|rc| rc.borrow().len()); /// // assert instance was finalized /// assert_eq!(i_ct, 0); /// } /// Err(e) => { /// panic!("script failed: {}", e); /// } /// } /// rt.gc_sync(); /// /// ``` pub struct Proxy { name: Option<String>, namespace: Option<Vec<String>>, pub(crate) constructor: Option<Box<ProxyConstructor>>, finalizers: Vec<Box<ProxyFinalizer>>, methods: HashMap<String, Box<ProxyMethod>>, native_methods: HashMap<String, ProxyNativeMethod>, static_methods: HashMap<String, Box<ProxyStaticMethod>>, static_native_methods: HashMap<String, ProxyStaticNativeMethod>, static_getters_setters: HashMap<String, (Box<ProxyStaticGetter>, Box<ProxyStaticSetter>)>, getters_setters: HashMap<String, (Box<ProxyGetter>, Box<ProxySetter>)>, catch_all: Option<(Box<ProxyCatchAllGetter>, Box<ProxyCatchAllSetter>)>, static_catch_all: Option<( Box<ProxyStaticCatchAllGetter>, Box<ProxyStaticCatchAllSetter>, )>, is_event_target: bool, is_static_event_target: bool, pub(crate) proxy_instance_id_mappings: RefCell<HashMap<usize, Box<ProxyInstanceInfo>>>, } impl Default for crate::reflection::Proxy { fn default() -> Self { Self::new() } } /// get a proxy by class_name (namespace.ClassName) pub fn get_proxy(q_ctx: &QuickJsRealmAdapter, class_name: &str) -> Option<Rc<Proxy>> { let registry = &*q_ctx.proxy_registry.borrow(); registry.get(class_name).cloned() } impl Proxy { #[allow(dead_code)] pub fn new() -> Self { Proxy { name: None, namespace: None, constructor: None, finalizers: Default::default(), methods: Default::default(), native_methods: Default::default(), static_methods: Default::default(), static_native_methods: Default::default(), static_getters_setters: Default::default(), getters_setters: Default::default(), catch_all: None, static_catch_all: None, is_event_target: false, is_static_event_target: false, proxy_instance_id_mappings: RefCell::new(Default::default()), } } /// set the name of the proxy class /// this will indicate how to construct the class from script pub fn name(mut self, name: &str) -> Self { self.name = Some(name.to_string()); self } /// set the namespace of the proxy class /// # Example /// ``` /// use quickjs_runtime::reflection::Proxy; /// Proxy::new().namespace(&["com", "hirofa"]).name("SomeClass"); /// ``` /// means from script you can access the class by /// ```javascript /// let instance = new com.hirofa.SomeClass(); /// ``` pub fn namespace(mut self, namespace: &[&str]) -> Self { if namespace.is_empty() { self.namespace = None; } else { self.namespace = Some(namespace.iter().map(|s| s.to_string()).collect()); } self } /// get the canonical classname of a Proxy /// # example /// ``` /// use quickjs_runtime::reflection::Proxy; /// Proxy::new().namespace(&["com", "hirofa"]).name("SomeClass"); /// ``` /// will result in a class_name of "com.hirofa.SomeClass" pub fn get_class_name(&self) -> String { let cn = if let Some(n) = self.name.as_ref() { n.as_str() } else { "__nameless_class__" }; if self.namespace.is_some() { format!("{}.{}", self.namespace.as_ref().unwrap().join("."), cn) } else { cn.to_string() } } /// add a constructor for the Proxy class /// this will enable a script to create a new instance of a Proxy class /// if omitted the Proxy class will not be constructable from script pub fn constructor<C>(mut self, constructor: C) -> Self where C: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, usize, &[QuickJsValueAdapter], ) -> Result<(), JsError> + 'static, { self.constructor = Some(Box::new(constructor)); self } /// add a finalizer for the Proxy class /// this will be called when an instance of the Proxy class is dropped or garbage collected pub fn finalizer<C>(mut self, finalizer: C) -> Self where C: Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter, usize) + 'static, { self.finalizers.push(Box::new(finalizer)); self } /// add a method to the Proxy class, this method will be available as a member of instances of the Proxy class pub fn method<M>(mut self, name: &str, method: M) -> Self where M: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> + 'static, { self.methods.insert(name.to_string(), Box::new(method)); self } /// add a method to the Proxy class, this method will be available as a member of instances of the Proxy class pub fn native_method(mut self, name: &str, method: ProxyNativeMethod) -> Self { self.native_methods.insert(name.to_string(), method); self } /// add a static method to the Proxy class, this method will be available as a member of the Proxy class itself pub fn static_method<M>(mut self, name: &str, method: M) -> Self where M: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> + 'static, { self.static_methods .insert(name.to_string(), Box::new(method)); self } /// add a static method to the Proxy class, this method will be available as a member of the Proxy class itself pub fn static_native_method(mut self, name: &str, method: ProxyStaticNativeMethod) -> Self { self.static_native_methods.insert(name.to_string(), method); self } /// add a static getter and setter to the Proxy class pub fn static_getter_setter<G, S>(mut self, name: &str, getter: G, setter: S) -> Self where G: Fn(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> Result<QuickJsValueAdapter, JsError> + 'static, S: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, QuickJsValueAdapter, ) -> Result<(), JsError> + 'static, { self.static_getters_setters .insert(name.to_string(), (Box::new(getter), Box::new(setter))); self } /// add a static getter and setter to the Proxy class pub fn static_catch_all_getter_setter<G, S>(mut self, getter: G, setter: S) -> Self where G: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &str, ) -> Result<QuickJsValueAdapter, JsError> + 'static, S: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &str, QuickJsValueAdapter, ) -> Result<(), JsError> + 'static, { self.static_catch_all = Some((Box::new(getter), Box::new(setter))); self } /// add a getter and setter to the Proxy class, these will be available as a member of an instance of this Proxy class pub fn getter_setter<G, S>(mut self, name: &str, getter: G, setter: S) -> Self where G: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, ) -> Result<QuickJsValueAdapter, JsError> + 'static, S: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, QuickJsValueAdapter, ) -> Result<(), JsError> + 'static, { self.getters_setters .insert(name.to_string(), (Box::new(getter), Box::new(setter))); self } /// add a getter and setter to the Proxy class, these will be available as a member of an instance of this Proxy class pub fn getter<G>(self, name: &str, getter: G) -> Self where G: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, ) -> Result<QuickJsValueAdapter, JsError> + 'static, { self.getter_setter(name, getter, |_rt, _realm, _id, _val| Ok(())) } /// add a catchall getter and setter to the Proxy class, these will be used for properties which are not specifically defined as getter, setter or method in this Proxy pub fn catch_all_getter_setter<G, S>(mut self, getter: G, setter: S) -> Self where G: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, &str, ) -> Result<QuickJsValueAdapter, JsError> + 'static, S: Fn( &QuickJsRuntimeAdapter, &QuickJsRealmAdapter, &usize, &str, QuickJsValueAdapter, ) -> Result<(), JsError> + 'static, { self.catch_all = Some((Box::new(getter), Box::new(setter))); self } /// indicate the Proxy class should implement the EventTarget interface, this will result in the addEventListener, removeEventListener and dispatchEvent methods to be available on instances of the Proxy class pub fn event_target(mut self) -> Self { self.is_event_target = true; self } /// indicate the Proxy class should implement the EventTarget interface, this will result in the addEventListener, removeEventListener and dispatchEvent methods to be available pub fn static_event_target(mut self) -> Self { self.is_static_event_target = true; self } /// install the Proxy class in a QuickJsContext, this is always needed as a final step to actually make the Proxy class work pub fn install( mut self, q_ctx: &QuickJsRealmAdapter, add_variable_to_global: bool, ) -> Result<QuickJsValueAdapter, JsError> { if self.name.is_none() { return Err(JsError::new_str("Proxy needs a name")); } let prim_cn = self.get_class_name(); let prim_cn2 = prim_cn.clone(); // todo turn these into native methods self = self.method("Symbol.toPrimitive", move |_rt, q_ctx, id, _args| { let prim = primitives::from_string_q( q_ctx, format!("Proxy::instance({id})::{prim_cn}").as_str(), )?; Ok(prim) }); let prim_cn = self.get_class_name(); self = self.static_method("Symbol.hasInstance", move |_rt, realm, args| { if args.len() == 1 { let instance = &args[0]; if instance.is_proxy_instance() { let info = realm.get_proxy_instance_info(instance)?; if info.0.eq(prim_cn2.as_str()) { return realm.create_boolean(true); } } } realm.create_boolean(false) }); self = self.static_method("Symbol.toPrimitive", move |_rt, q_ctx, _args| { let prim = primitives::from_string_q(q_ctx, format!("Proxy::{prim_cn}").as_str())?; Ok(prim) }); let ret = self.install_class_prop(q_ctx, add_variable_to_global)?; eventtarget::impl_event_target(self).install_move_to_registry(q_ctx); Ok(ret) } fn install_move_to_registry(self, q_ctx: &QuickJsRealmAdapter) { let proxy = self; let reg_map = &mut *q_ctx.proxy_registry.borrow_mut(); reg_map.insert(proxy.get_class_name(), Rc::new(proxy)); } fn install_class_prop( &mut self, q_ctx: &QuickJsRealmAdapter, add_variable_to_global: bool, ) -> Result<QuickJsValueAdapter, JsError> { // this creates a constructor function, adds it to the global scope and then makes an instance of the static_proxy_class its prototype so we can add static_getters_setters and static_methods log::trace!("reflection::Proxy::install_class_prop / 1"); let static_class_id = PROXY_STATIC_CLASS_ID.with(|rc| *rc.borrow()); log::trace!("reflection::Proxy::install_class_prop / 2"); let constructor_ref = new_native_function_q( q_ctx, self.name.as_ref().unwrap().as_str(), Some(constructor), 1, true, )?; log::trace!("reflection::Proxy::install_class_prop / 3"); let class_val: q::JSValue = unsafe { q::JS_NewObjectClass(q_ctx.context, static_class_id as _) }; log::trace!("reflection::Proxy::install_class_prop / 4"); let class_val_ref = QuickJsValueAdapter::new( q_ctx.context, class_val, false, true, "reflection::Proxy::install_class_prop class_val", ); #[cfg(feature = "bellard")] assert_eq!(1, class_val_ref.get_ref_count()); log::trace!("reflection::Proxy::install_class_prop / 5"); if class_val_ref.is_exception() { return if let Some(e) = unsafe { QuickJsRealmAdapter::get_exception(q_ctx.context) } { Err(e) } else { Err(JsError::new_string(format!( "could not create class:{}", self.get_class_name() ))) }; } log::trace!("reflection::Proxy::install_class_prop / 6"); unsafe { let res = q::JS_SetPrototype( q_ctx.context, *constructor_ref.borrow_value(), *class_val_ref.borrow_value(), ); if res < 0 { return if let Some(err) = QuickJsRealmAdapter::get_exception(q_ctx.context) { Err(err) } else { Err(JsError::new_str("could not set class proto")) }; } } #[cfg(feature = "bellard")] assert_eq!(2, class_val_ref.get_ref_count()); log::trace!("reflection::Proxy::install_class_prop / 7"); objects::set_property2_q( q_ctx, &constructor_ref, "name", &primitives::from_string_q(q_ctx, &self.get_class_name())?, 0, )?; // todo impl namespace here if add_variable_to_global { log::trace!("reflection::Proxy::install_class_prop / 8"); let ns = if let Some(namespace) = &self.namespace { let ns_str = namespace.iter().map(|s| s.as_str()).collect::<Vec<&str>>(); objects::get_namespace_q(q_ctx, ns_str.as_slice(), true)? } else { quickjs_utils::get_global_q(q_ctx) }; log::trace!("reflection::Proxy::install_class_prop / 9"); objects::set_property2_q( q_ctx, &ns, self.name.as_ref().unwrap().as_str(), &constructor_ref, 0, )?; } log::trace!("reflection::Proxy::install_class_prop / 10"); let proxy_constructor_refs = &mut *q_ctx.proxy_constructor_refs.borrow_mut(); proxy_constructor_refs.insert(self.get_class_name(), constructor_ref.clone()); log::trace!("install_class_prop done"); Ok(constructor_ref) } } pub fn get_proxy_instance_proxy_and_instance_id_q( q_ctx: &QuickJsRealmAdapter, obj: &QuickJsValueAdapter, ) -> Option<(Rc<Proxy>, usize)> { if !is_proxy_instance_q(q_ctx, obj) { None } else { let info = get_proxy_instance_info(obj.borrow_value()); let cn = info.class_name.as_str(); let registry = &*q_ctx.proxy_registry.borrow(); registry.get(cn).cloned().map(|proxy| (proxy, info.id)) } } pub fn get_proxy_instance_id_q( q_ctx: &QuickJsRealmAdapter, obj: &QuickJsValueAdapter, ) -> Option<usize> { if !is_proxy_instance_q(q_ctx, obj) { None } else { let info = get_proxy_instance_info(obj.borrow_value()); Some(info.id) } } /// Get the instance id of a proxy instance /// # Safety /// please make sure context is still valid pub unsafe fn get_proxy_instance_id( ctx: *mut libquickjs_sys::JSContext, obj: &QuickJsValueAdapter, ) -> Option<usize> { if !is_proxy_instance(ctx, obj) { None } else { let info = get_proxy_instance_info(obj.borrow_value()); Some(info.id) } } pub fn is_proxy_instance_q(q_ctx: &QuickJsRealmAdapter, obj: &QuickJsValueAdapter) -> bool { unsafe { is_proxy_instance(q_ctx.context, obj) } } /// check if an object is an instance of a Proxy class /// # Safety /// please make sure context is still valid pub unsafe fn is_proxy_instance(ctx: *mut q::JSContext, obj: &QuickJsValueAdapter) -> bool { if !obj.is_object() { false } else { // workaround for instanceof not yet working let prop_res = get_property(ctx, obj, "__proxy__"); if let Ok(prop) = prop_res { if prop.is_bool() && prop.to_bool() { return true; } } let class_id = PROXY_INSTANCE_CLASS_ID.with(|rc| *rc.borrow()); let proxy_class_proto: q::JSValue = q::JS_GetClassProto(ctx, class_id); //let proto_ref: JSValueRef = JSValueRef::new(ctx, proxy_class_proto, false, false, "proxy_class_proto"); let proxy_class_proto_obj = q::JS_GetPrototype(ctx, proxy_class_proto); let res = q::JS_IsInstanceOf(ctx, *obj.borrow_value(), proxy_class_proto_obj); if res == -1 { // log err if let Some(ex) = QuickJsRealmAdapter::get_exception(ctx) { log::error!("is_proxy_instance failed: {}", ex); } else { log::error!("is_proxy_instance failed"); } } res > 0 } } pub fn new_instance2( proxy: &Proxy, q_ctx: &QuickJsRealmAdapter, ) -> Result<(usize, QuickJsValueAdapter), JsError> { let instance_id = next_id(proxy); Ok((instance_id, new_instance3(proxy, instance_id, q_ctx)?)) } pub(crate) fn new_instance3( proxy: &Proxy, instance_id: usize, q_ctx: &QuickJsRealmAdapter, ) -> Result<QuickJsValueAdapter, JsError> { let ctx = q_ctx.context; let class_id = PROXY_INSTANCE_CLASS_ID.with(|rc| *rc.borrow()); let class_val: q::JSValue = unsafe { q::JS_NewObjectClass(ctx, class_id as _) }; let class_name = proxy.get_class_name(); trace!("creating new instance {} of {}", instance_id, class_name); let class_val_ref = QuickJsValueAdapter::new( q_ctx.context, class_val, false, true, format!("reflection::Proxy; cn={class_name}").as_str(), ); if class_val_ref.is_exception() { return if let Some(e) = q_ctx.get_exception_ctx() { Err(JsError::new_string(format!( "could not create class:{class_name} due to: {e}" ))) } else { Err(JsError::new_string(format!( "could not create class:{class_name}" ))) }; } let mappings = &mut *proxy.proxy_instance_id_mappings.borrow_mut(); assert!(!mappings.contains_key(&instance_id)); let mut bx = Box::new(ProxyInstanceInfo { id: instance_id, class_name: proxy.get_class_name(), context_id: q_ctx.id.clone(), }); let ibp: &mut ProxyInstanceInfo = &mut bx; let info_ptr = ibp as *mut _ as *mut c_void; mappings.insert(instance_id, bx); unsafe { q::JS_SetOpaque(*class_val_ref.borrow_value(), info_ptr) }; // todo this is a workaround.. i need to set a prototype for classes using JS_setClassProto per context on init.. set_property2_q( q_ctx, &class_val_ref, "__proxy__", &primitives::from_bool(true), 0, )?; let proxy_constructor_refs = &*q_ctx.proxy_constructor_refs.borrow(); let constructor = proxy_constructor_refs .get(&class_name) .expect("proxy was not installed properly"); set_property2_q(q_ctx, &class_val_ref, "constructor", constructor, 0)?; Ok(class_val_ref) } pub fn new_instance( class_name: &str, q_ctx: &QuickJsRealmAdapter, ) -> Result<(usize, QuickJsValueAdapter), JsError> { // todo let registry = &*q_ctx.proxy_registry.borrow(); if let Some(proxy) = registry.get(class_name) { // construct new_instance2(proxy, q_ctx) } else { Err(JsError::new_str("no such proxy")) } } #[allow(dead_code)] unsafe extern "C" fn constructor( context: *mut q::JSContext, this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { log::trace!("constructor called, this_tag={}", this_val.tag); // this is the function we created earlier (the constructor) // so classname = this.name; let this_ref = QuickJsValueAdapter::new( context, this_val, false, false, "reflection::constructor this_val", ); QuickJsRuntimeAdapter::do_with(|q_js_rt| { let name_ref = objects::get_property(context, &this_ref, "name").expect("name get failed"); let class_name =
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
true
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/jsutils/modules.rs
src/jsutils/modules.rs
use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use std::sync::Arc; pub trait ScriptModuleLoader { fn normalize_path( &self, realm: &QuickJsRealmAdapter, ref_path: &str, path: &str, ) -> Option<String>; fn load_module(&self, realm: &QuickJsRealmAdapter, absolute_path: &str) -> String; } pub trait CompiledModuleLoader { fn normalize_path( &self, realm: &QuickJsRealmAdapter, ref_path: &str, path: &str, ) -> Option<String>; fn load_module(&self, realm: &QuickJsRealmAdapter, absolute_path: &str) -> Arc<Vec<u8>>; } pub trait NativeModuleLoader { fn has_module(&self, realm: &QuickJsRealmAdapter, module_name: &str) -> bool; fn get_module_export_names(&self, realm: &QuickJsRealmAdapter, module_name: &str) -> Vec<&str>; fn get_module_exports( &self, realm: &QuickJsRealmAdapter, module_name: &str, ) -> Vec<(&str, QuickJsValueAdapter)>; }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/jsutils/mod.rs
src/jsutils/mod.rs
//! This contains abstract traits and structs for use with different javascript runtimes //! the Adapter traits are use in the worker thread (EventLoop) of the Runtime and thus are not Send, they should never leave the thread //! The facade classes are for use outside the worker thread, they are Send //! use crate::values::JsValueFacade; use backtrace::Backtrace; use std::fmt::{Debug, Display, Error, Formatter}; pub mod helper_tasks; pub mod jsproxies; pub mod modules; pub mod promises; pub trait ScriptPreProcessor { fn process(&self, script: &mut Script) -> Result<(), JsError>; } /// the JsValueType represents the type of value for a JSValue #[derive(PartialEq, Copy, Clone, Eq)] pub enum JsValueType { I32, F64, String, Boolean, Object, Function, BigInt, Promise, Date, Null, Undefined, Array, Error, } impl Display for JsValueType { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { JsValueType::I32 => f.write_str("I32"), JsValueType::F64 => f.write_str("F64"), JsValueType::String => f.write_str("String"), JsValueType::Boolean => f.write_str("Boolean"), JsValueType::Object => f.write_str("Object"), JsValueType::Function => f.write_str("Function"), JsValueType::BigInt => f.write_str("BigInt"), JsValueType::Promise => f.write_str("Promise"), JsValueType::Date => f.write_str("Date"), JsValueType::Null => f.write_str("Null"), JsValueType::Undefined => f.write_str("Undefined"), JsValueType::Array => f.write_str("Array"), JsValueType::Error => f.write_str("Error"), } } } #[derive(Debug)] pub struct JsError { name: String, message: String, stack: String, cause: Option<Box<JsValueFacade>>, } impl JsError { pub fn new(name: String, message: String, stack: String) -> Self { Self { name, message, stack, cause: None, } } pub fn new2(name: String, message: String, stack: String, cause: JsValueFacade) -> Self { Self { name, message, stack, cause: Some(Box::new(cause)), } } pub fn new_str(err: &str) -> Self { Self::new_string(err.to_string()) } pub fn new_string(err: String) -> Self { let bt = Backtrace::new(); JsError { name: "Error".to_string(), message: err, stack: format!("{bt:?}"), cause: None, } } pub fn get_message(&self) -> &str { self.message.as_str() } pub fn get_stack(&self) -> &str { self.stack.as_str() } pub fn get_name(&self) -> &str { self.name.as_str() } pub fn get_cause(&self) -> &Option<Box<JsValueFacade>> { &self.cause } } impl std::error::Error for JsError { fn description(&self) -> &str { self.get_message() } } impl From<anyhow::Error> for JsError { fn from(err: anyhow::Error) -> Self { JsError::new_string(format!("{err:?}")) } } impl std::fmt::Display for JsError { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let e = format!("{}: {}\n{}", self.name, self.message, self.stack); f.write_str(e.as_str()) } } impl From<Error> for JsError { fn from(e: Error) -> Self { JsError::new_string(format!("{e:?}")) } } pub struct Script { path: String, code: String, transpiled_code: Option<String>, map: Option<String>, } impl Debug for Script { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(format!("Script:{}", self.path.as_str()).as_str()) } } impl Script { pub fn new(absolute_path: &str, script_code: &str) -> Self { Self { path: absolute_path.to_string(), code: script_code.to_string(), transpiled_code: None, map: None, } } pub fn get_path(&self) -> &str { self.path.as_str() } pub fn get_code(&self) -> &str { self.code.as_str() } pub fn get_runnable_code(&self) -> &str { if let Some(t_code) = self.transpiled_code.as_ref() { t_code.as_str() } else { self.code.as_str() } } pub fn set_code(&mut self, code: String) { self.code = code; } pub fn set_transpiled_code(&mut self, transpiled_code: String, map: Option<String>) { self.transpiled_code = Some(transpiled_code); self.map = map; } pub fn get_map(&self) -> Option<&str> { self.map.as_deref() } } impl Clone for Script { fn clone(&self) -> Self { Self { path: self.path.clone(), code: self.code.clone(), transpiled_code: self.transpiled_code.clone(), map: self.map.clone(), } } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/jsutils/jsproxies.rs
src/jsutils/jsproxies.rs
use crate::reflection::Proxy; pub type JsProxy = Proxy; pub type JsProxyInstanceId = usize;
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/jsutils/promises.rs
src/jsutils/promises.rs
use crate::jsutils::helper_tasks::{add_helper_task, add_helper_task_async}; use crate::jsutils::JsError; use crate::quickjs_utils::promises::QuickJsPromiseAdapter; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use futures::Future; #[allow(clippy::type_complexity)] /// create a new promise with a producer and a mapper /// the producer will run in a helper thread(in the tokio thread pool) and thus get a result asynchronously /// the resulting value will then be mapped to a JSValueRef by the mapper in the EventQueue thread /// the promise which was returned is then resolved with the value which is returned by the mapper pub fn new_resolving_promise<P, R, M>( realm: &QuickJsRealmAdapter, producer: P, mapper: M, ) -> Result<QuickJsValueAdapter, JsError> where R: Send + 'static, P: FnOnce() -> Result<R, JsError> + Send + 'static, M: FnOnce(&QuickJsRealmAdapter, R) -> Result<QuickJsValueAdapter, JsError> + Send + 'static, { // create promise let promise_ref = realm.create_promise()?; let return_ref = promise_ref.js_promise_get_value(realm); // add to map and keep id let id = realm.cache_promise(promise_ref); let rti_ref = realm.get_runtime_facade_inner(); let realm_id = realm.get_realm_id().to_string(); // go async add_helper_task(move || { // in helper thread, produce result let produced_result = producer(); if let Some(rti) = rti_ref.upgrade() { rti.add_rt_task_to_event_loop_void(move |rt| { if let Some(realm) = rt.get_realm(realm_id.as_str()) { // in q_js_rt worker thread, resolve promise // retrieve promise let prom_ref_opt: Option<QuickJsPromiseAdapter> = realm.consume_cached_promise(id); if let Some(prom_ref) = prom_ref_opt { //let prom_ref = realm.js_promise_cache_consume(id); match produced_result { Ok(ok_res) => { // map result to JSValueRef let raw_res = mapper(realm, ok_res); // resolve or reject promise match raw_res { Ok(val_ref) => { if let Err(e) = prom_ref.js_promise_resolve(realm, &val_ref) { log::error!( "[{}] could not resolve promise5: {}", realm.get_realm_id(), e ); } } Err(err) => { let err_ref = realm .create_error( err.get_name(), err.get_message(), err.get_stack(), ) .expect("could not create error"); if let Err(e) = prom_ref.js_promise_reject(realm, &err_ref) { log::error!( "[{}] could not reject promise4: {}", realm.get_realm_id(), e ); } } } } Err(err) => { // todo use error:new_error(err) let err_ref = realm .create_error( err.get_name(), err.get_message(), err.get_stack(), ) .expect("could not create error"); if let Err(e) = prom_ref.js_promise_reject(realm, &err_ref) { log::error!( "[{}] could not reject promise3: {}", realm.get_realm_id(), e ); } } } } else { log::error!( "async promise running for dropped realm: {} promise_id:{}", realm_id, id ); } } else { log::error!("async promise running for dropped realm: {}", realm_id); } }); } else { log::error!("async promise running for dropped runtime"); } }); Ok(return_ref) } #[allow(clippy::type_complexity)] /// create a new promise with an async producer and a mapper /// the producer will be awaited asynchronously and /// the resulting value will then be mapped to a JSValueRef by the mapper in the EventQueue thread /// the promise which was returned is then resolved with the value which is returned by the mapper pub(crate) fn new_resolving_promise_async<P, R, M>( realm: &QuickJsRealmAdapter, producer: P, mapper: M, ) -> Result<QuickJsValueAdapter, JsError> where R: Send + 'static, P: Future<Output = Result<R, JsError>> + Send + 'static, M: FnOnce(&QuickJsRealmAdapter, R) -> Result<QuickJsValueAdapter, JsError> + Send + 'static, { // create promise let promise_ref = realm.create_promise()?; let return_ref = promise_ref.js_promise_get_value(realm); // add to map and keep id let id = realm.cache_promise(promise_ref); let rti_ref = realm.get_runtime_facade_inner(); let realm_id = realm.get_realm_id().to_string(); // go async let _ignore_result = add_helper_task_async(async move { // in helper thread, produce result let produced_result = producer.await; if let Some(rti) = rti_ref.upgrade() { rti.add_rt_task_to_event_loop_void(move |rt| { if let Some(realm) = rt.get_realm(realm_id.as_str()) { // in q_js_rt worker thread, resolve promise // retrieve promise let prom_ref_opt: Option<QuickJsPromiseAdapter> = realm.consume_cached_promise(id); if let Some(prom_ref) = prom_ref_opt { //let prom_ref = realm.js_promise_cache_consume(id); match produced_result { Ok(ok_res) => { // map result to JSValueRef let raw_res = mapper(realm, ok_res); // resolve or reject promise match raw_res { Ok(val_ref) => { if let Err(e) = prom_ref.js_promise_resolve(realm, &val_ref) { log::error!( "[{}] could not resolve promise: {}", realm.get_realm_id(), e ); } } Err(err) => { let err_ref = realm .create_error( err.get_name(), err.get_message(), err.get_stack(), ) .expect("could not create err"); if let Err(e) = prom_ref.js_promise_reject(realm, &err_ref) { log::error!( "[{}] could not reject promise: {}", realm.get_realm_id(), e ); } } } } Err(err) => { // todo use error:new_error(err) let err_ref = realm .create_error( err.get_name(), err.get_message(), err.get_stack(), ) .expect("could not create str"); if let Err(e) = prom_ref.js_promise_reject(realm, &err_ref) { log::error!( "[{}] could not reject promise2: {}", realm.get_realm_id(), e ); } } } } else { log::error!( "async promise running on dropped realm: {} promise_id:{}", realm_id, id ); } } else { log::error!("async promise running on dropped realm: {}", realm_id); } }); } else { log::error!("async promise running on dropped runtime"); } }); Ok(return_ref) }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/jsutils/helper_tasks.rs
src/jsutils/helper_tasks.rs
use futures::Future; use hirofa_utils::task_manager::TaskManager; use lazy_static::lazy_static; use tokio::task::JoinError; lazy_static! { /// a static Multithreaded task manager used to run rust ops async and multithreaded ( in at least 2 threads) static ref HELPER_TASKS: TaskManager = TaskManager::new(std::cmp::max(2, num_cpus::get())); } /// add a task the the "helper" thread pool pub fn add_helper_task<T>(task: T) where T: FnOnce() + Send + 'static, { log::trace!("adding a helper task"); HELPER_TASKS.add_task(task); } /// add an async task the the "helper" thread pool pub fn add_helper_task_async<R: Send + 'static, T: Future<Output = R> + Send + 'static>( task: T, ) -> impl Future<Output = Result<R, JoinError>> { log::trace!("adding an async helper task"); HELPER_TASKS.add_task_async(task) }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/features/set_timeout.rs
src/features/set_timeout.rs
use crate::jsutils::JsError; use crate::quickjs_utils; use crate::quickjs_utils::{functions, get_global, objects, parse_args, primitives}; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use hirofa_utils::eventloop::EventLoop; use libquickjs_sys as q; use std::time::Duration; /// provides the setImmediate methods for the runtime /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use std::time::Duration; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.eval_sync(None, Script::new("test_timeout.es", "setTimeout(() => {console.log('timed logging')}, 1000);")).expect("script failed"); /// std::thread::sleep(Duration::from_secs(2)); /// ``` pub fn init(q_js_rt: &QuickJsRuntimeAdapter) -> Result<(), JsError> { log::trace!("set_timeout::init"); q_js_rt.add_context_init_hook(|_q_js_rt, q_ctx| { let global = unsafe { get_global(q_ctx.context) }; #[cfg(feature = "settimeout")] { let set_timeout_func = functions::new_native_function_q(q_ctx, "setTimeout", Some(set_timeout), 2, false)?; let clear_timeout_func = functions::new_native_function_q( q_ctx, "clearTimeout", Some(clear_timeout), 1, false, )?; objects::set_property2_q(q_ctx, &global, "setTimeout", &set_timeout_func, 0)?; objects::set_property2_q(q_ctx, &global, "clearTimeout", &clear_timeout_func, 0)?; } #[cfg(feature = "setinterval")] { let set_interval_func = functions::new_native_function_q( q_ctx, "setInterval", Some(set_interval), 2, false, )?; let clear_interval_func = functions::new_native_function_q( q_ctx, "clearInterval", Some(clear_interval), 1, false, )?; objects::set_property2_q(q_ctx, &global, "setInterval", &set_interval_func, 0)?; objects::set_property2_q(q_ctx, &global, "clearInterval", &clear_interval_func, 0)?; } Ok(()) })?; Ok(()) } #[cfg(feature = "settimeout")] unsafe extern "C" fn set_timeout( context: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { log::trace!("> set_timeout"); let args = parse_args(context, argc, argv); QuickJsRuntimeAdapter::do_with(move |q_js_rt| { let q_ctx = q_js_rt.get_quickjs_context(context); if args.is_empty() { return q_ctx.report_ex("setTimeout requires at least one argument"); } if !functions::is_function(context, &args[0]) { return q_ctx.report_ex("setTimeout requires a function as first arg"); } if args.len() >= 2 && !args[1].is_i32() && !args[1].is_f64() { return q_ctx.report_ex("setTimeout requires a number as second arg"); } let delay_ms = if args.len() >= 2 { let delay_ref = &args[1]; if delay_ref.is_i32() { primitives::to_i32(delay_ref).ok().unwrap() as u64 } else { primitives::to_f64(delay_ref).ok().unwrap() as u64 } } else { 0 }; let q_ctx_id = q_ctx.id.clone(); let id = EventLoop::add_timeout( move || { QuickJsRuntimeAdapter::do_with(|q_js_rt| { let func = &args[0]; if let Some(q_ctx) = q_js_rt.opt_context(q_ctx_id.as_str()) { match functions::call_function_q(q_ctx, func, &args[2..], None) { Ok(_) => {} Err(e) => { log::error!("setTimeout func failed: {}", e); } }; } else { log::error!("setTimeout func failed: no such context: {}", q_ctx_id); } q_js_rt.run_pending_jobs_if_any(); }) }, Duration::from_millis(delay_ms), ); log::trace!("set_timeout: {}", id); primitives::from_i32(id).clone_value_incr_rc() }) } #[cfg(feature = "setinterval")] unsafe extern "C" fn set_interval( context: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { log::trace!("> set_interval"); let args = parse_args(context, argc, argv); QuickJsRuntimeAdapter::do_with(|q_js_rt| { let q_ctx = q_js_rt.get_quickjs_context(context); if args.is_empty() { return q_ctx.report_ex("setInterval requires at least one argument"); } if !functions::is_function(context, &args[0]) { return q_ctx.report_ex("setInterval requires a functions as first arg"); } if args.len() >= 2 && !args[1].is_i32() && !args[1].is_f64() { return q_ctx.report_ex("setInterval requires a number as second arg"); } let delay_ms = if args.len() >= 2 { let delay_ref = &args[1]; if delay_ref.is_i32() { primitives::to_i32(delay_ref).ok().unwrap() as u64 } else { primitives::to_f64(delay_ref).ok().unwrap() as u64 } } else { 0 }; let q_ctx_id = q_ctx.id.clone(); let id = EventLoop::add_interval( move || { QuickJsRuntimeAdapter::do_with(|q_js_rt| { if let Some(q_ctx) = q_js_rt.opt_context(q_ctx_id.as_str()) { let func = &args[0]; match functions::call_function_q(q_ctx, func, &args[2..], None) { Ok(_) => {} Err(e) => { log::error!("setInterval func failed: {}", e); } }; } else { log::error!("setInterval func failed: no such context: {}", q_ctx_id); } q_js_rt.run_pending_jobs_if_any(); }) }, Duration::from_millis(delay_ms), Duration::from_millis(delay_ms), ); log::trace!("set_interval: {}", id); primitives::from_i32(id).clone_value_incr_rc() }) } #[cfg(feature = "setinterval")] unsafe extern "C" fn clear_interval( context: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { log::trace!("> clear_interval"); let args = parse_args(context, argc, argv); QuickJsRuntimeAdapter::do_with(|q_js_rt| { let q_ctx = q_js_rt.get_quickjs_context(context); if args.is_empty() { return q_ctx.report_ex("clearInterval requires at least one argument"); } if !&args[0].is_i32() { return q_ctx.report_ex("clearInterval requires a number as first arg"); } let id = primitives::to_i32(&args[0]).ok().unwrap(); log::trace!("clear_interval: {}", id); EventLoop::clear_interval(id); quickjs_utils::new_null() }) } #[cfg(feature = "settimeout")] unsafe extern "C" fn clear_timeout( context: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { log::trace!("> clear_timeout"); let args = parse_args(context, argc, argv); QuickJsRuntimeAdapter::do_with(move |q_js_rt| { let q_ctx = q_js_rt.get_quickjs_context(context); if args.is_empty() { return q_ctx.report_ex("clearTimeout requires at least one argument"); } if !&args[0].is_i32() { return q_ctx.report_ex("clearTimeout requires a number as first arg"); } let id = primitives::to_i32(&args[0]).ok().unwrap(); log::trace!("clear_timeout: {}", id); EventLoop::clear_timeout(id); quickjs_utils::new_null() }) } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::Script; use crate::quickjs_utils::get_global_q; use crate::quickjs_utils::objects::get_property_q; use crate::quickjs_utils::primitives::to_i32; use crate::values::JsValueFacade; use std::time::Duration; #[test] fn test_set_timeout_prom_res() { let rt = init_test_rt(); let esvf = rt .eval_sync( None, Script::new( "test_set_timeout_prom_res.es", "new Promise((resolve, reject) => {\ setTimeout(() => {resolve(123);}, 1000);\ }).then((res) => {\ console.log(\"got %s\", res);\ return res + \"abc\";\ }).catch((ex) => {\ throw Error(\"\" + ex);\ });\ ", ), ) .expect("script failed"); assert!(esvf.is_js_promise()); let res = match esvf { JsValueFacade::JsPromise { cached_promise } => { cached_promise.get_promise_result_sync().expect("timed out") } _ => Err(JsValueFacade::new_str("poof")), }; assert!(res.is_ok()); let res_str_esvf = res.ok().unwrap(); let res_str = res_str_esvf.get_str(); assert_eq!(res_str, "123abc"); log::info!("done"); } #[test] fn test_set_timeout_prom_res_nested() { let rt = init_test_rt(); let esvf = rt .eval_sync( None, Script::new( "test_set_timeout_prom_res_nested.es", "new Promise((resolve, reject) => {\ setTimeout(() => {setTimeout(() => {resolve(123);}, 1000);}, 1000);\ }).then((res) => {\ console.log(\"got %s\", res);\ return res + \"abc\";\ }).catch((ex) => {\ throw Error(\"\" + ex);\ });\ ", ), ) .expect("script failed"); assert!(esvf.is_js_promise()); match esvf { JsValueFacade::JsPromise { cached_promise } => { let res = cached_promise.get_promise_result_sync().expect("timed out"); assert!(res.is_ok()); let res_str_esvf = res.ok().unwrap(); let res_str = res_str_esvf.get_str(); assert_eq!(res_str, "123abc"); } _ => {} } log::info!("done"); } #[test] fn test_set_timeout() { let rt = init_test_rt(); rt.eval_sync(None, Script::new("test_set_interval.es", "let t_id1 = setInterval((a, b) => {console.log('setInterval invoked with %s and %s', a, b);}, 500, 123, 456);")).expect("fail a"); rt.eval_sync(None, Script::new("test_set_timeout.es", "let t_id2 = setTimeout((a, b) => {console.log('setTimeout1 invoked with %s and %s', a, b);}, 500, 123, 456);")).expect("fail b"); rt.eval_sync(None, Script::new("test_set_timeout.es", "let t_id3 = setTimeout((a, b) => {console.log('setTimeout2 invoked with %s and %s', a, b);}, 600, 123, 456);")).expect("fail b"); rt.eval_sync(None, Script::new("test_set_timeout.es", "let t_id4 = setTimeout((a, b) => {console.log('setTimeout3 invoked with %s and %s', a, b);}, 900, 123, 456);")).expect("fail b"); std::thread::sleep(Duration::from_secs(3)); rt.eval_sync( None, Script::new("test_clearInterval.es", "clearInterval(t_id1);"), ) .expect("fail c"); rt.eval_sync( None, Script::new("test_clearTimeout2.es", "clearTimeout(t_id2);"), ) .expect("fail d"); rt.eval_sync( None, Script::new("test_set_timeout2.es", "this.__ti_num__ = 0;"), ) .expect("fail qewr"); rt.eval_sync( None, Script::new("test_set_timeout2.es", "this.__it_num__ = 0;"), ) .expect("fail qewr"); rt.eval_sync( None, Script::new( "test_set_timeout3.es", "setTimeout(() => {console.log('seto1');this.__ti_num__++;}, 455);", ), ) .expect("fail a1"); rt.eval_sync( None, Script::new( "test_set_timeout3.es", "setTimeout(() => {console.log('seto2');this.__ti_num__++;}, 366);", ), ) .expect("fail a2"); rt.eval_sync( None, Script::new( "test_set_timeout3.es", "setTimeout(() => {console.log('seto3');this.__ti_num__++;}, 1001);", ), ) .expect("fail a3"); rt.eval_sync( None, Script::new( "test_set_timeout3.es", "setTimeout(() => {console.log('seto4');this.__ti_num__++;}, 2002);", ), ) .expect("fail a4"); rt.eval_sync( None, Script::new( "test_set_interval.es", "setInterval(() => {this.__it_num__++;}, 1600);", ), ) .expect("fail a"); rt.eval_sync( None, Script::new( "test_set_interval.es", "setInterval(() => {this.__it_num__++;}, 2500);", ), ) .expect("fail a"); std::thread::sleep(Duration::from_secs(6)); let i = rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let global = get_global_q(q_ctx); let ti_num = get_property_q(q_ctx, &global, "__ti_num__") .ok() .expect("could not get ti num prop from global"); let it_num = get_property_q(q_ctx, &global, "__it_num__") .ok() .expect("could not get it num prop from global"); ( to_i32(&ti_num) .ok() .expect("could not convert ti num to num"), to_i32(&it_num) .ok() .expect("could not convert it num to num"), ) }); assert_eq!(i.1, 5); assert_eq!(i.0, 4); rt.gc_sync(); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/features/mod.rs
src/features/mod.rs
//! contains engine features like console, setTimeout, setInterval and setImmediate use crate::facades::QuickJsRuntimeFacade; use crate::jsutils::JsError; #[cfg(feature = "console")] pub mod console; #[cfg(any(feature = "settimeout", feature = "setinterval"))] pub mod set_timeout; #[cfg(feature = "setimmediate")] pub mod setimmediate; #[cfg(any( feature = "settimeout", feature = "setinterval", feature = "console", feature = "setimmediate" ))] pub fn init(es_rt: &QuickJsRuntimeFacade) -> Result<(), JsError> { log::trace!("features::init"); es_rt.exe_rt_task_in_event_loop(move |q_js_rt| { #[cfg(feature = "console")] console::init(q_js_rt)?; #[cfg(feature = "setimmediate")] setimmediate::init(q_js_rt)?; #[cfg(any(feature = "settimeout", feature = "setinterval"))] set_timeout::init(q_js_rt)?; Ok(()) }) }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/features/console.rs
src/features/console.rs
//! the console feature enables the script to use various cansole.log variants //! see also: [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Console) //! the following methods are available //! * console.log() //! * console.info() //! * console.error() //! * console.warning() //! * console.trace() //! //! The methods use rust's log crate to output messages. e.g. console.info() uses the log::info!() macro //! so the console messages should appear in the log you initialized from rust //! //! All methods accept a single message string and optional substitution values //! //! e.g. //! ```javascript //! console.log('Oh dear %s totaly failed %i times because of a %.4f variance in the space time continuum', 'some guy', 12, 2.46) //! ``` //! will output 'Oh dear some guy totaly failed 12 times because of a 2.4600 variance in the space time continuum' //! //! The string substitution you can use are //! * %o or %O Outputs a JavaScript object (serialized) //! * %d or %i Outputs an integer. Number formatting is supported, for example console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01 //! * %s Outputs a string (will attempt to call .toString() on objects, use %o to output a serialized JSON string) //! * %f Outputs a floating-point value. Formatting is supported, for example console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10 //! # Example //! ```rust //! use quickjs_runtime::builder::QuickJsRuntimeBuilder; //! use log::LevelFilter; //! use quickjs_runtime::jsutils::Script; //! simple_logging::log_to_file("console_test.log", LevelFilter::max()) //! .ok() //! .expect("could not init logger"); //! let rt = QuickJsRuntimeBuilder::new().build(); //! rt.eval_sync(None, Script::new( //! "console.es", //! "console.log('the %s %s %s jumped over %i fences with a accuracy of %.2f', 'quick', 'brown', 'fox', 32, 0.512);" //! )).expect("script failed"); //! ``` //! //! which will result in a log entry like //! ```[00:00:00.012] (7f44e7d24700) INFO the quick brown fox jumped over 32 fences with a accuracy of 0.51``` use crate::jsutils::{JsError, JsValueType}; use crate::quickjs_utils; use crate::quickjs_utils::functions::call_to_string; use crate::quickjs_utils::json::stringify; use crate::quickjs_utils::{functions, json, parse_args, primitives}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use crate::reflection::Proxy; use libquickjs_sys as q; use log::LevelFilter; use std::str::FromStr; pub fn init(q_js_rt: &QuickJsRuntimeAdapter) -> Result<(), JsError> { q_js_rt.add_context_init_hook(|_q_js_rt, q_ctx| init_ctx(q_ctx)) } pub(crate) fn init_ctx(q_ctx: &QuickJsRealmAdapter) -> Result<(), JsError> { Proxy::new() .name("console") .static_native_method("log", Some(console_log)) .static_native_method("trace", Some(console_trace)) .static_native_method("info", Some(console_info)) .static_native_method("warn", Some(console_warn)) .static_native_method("error", Some(console_error)) //.static_native_method("assert", Some(console_assert)) // todo .static_native_method("debug", Some(console_debug)) .install(q_ctx, true) .map(|_| {}) } #[allow(clippy::or_fun_call)] unsafe fn parse_field_value( ctx: *mut q::JSContext, field: &str, value: &QuickJsValueAdapter, ) -> String { // format ints // only support ,2 / .3 to declare the number of digits to display, e.g. $.3i turns 3 to 003 // format floats // only support ,2 / .3 to declare the number of decimals to display, e.g. $.3f turns 3.1 to 3.100 if field.eq(&"%.0f".to_string()) { return parse_field_value(ctx, "%i", value); } if field.ends_with('d') || field.ends_with('i') { let mut i_val: String = call_to_string(ctx, value).unwrap_or_default(); // remove chars behind . if let Some(i) = i_val.find('.') { let _ = i_val.split_off(i); } if let Some(dot_in_field_idx) = field.find('.') { let mut m_field = field.to_string(); // get part behind dot let mut num_decimals_str = m_field.split_off(dot_in_field_idx + 1); // remove d or i at end let _ = num_decimals_str.split_off(num_decimals_str.len() - 1); // see if we have a number if !num_decimals_str.is_empty() { let ct_res = usize::from_str(num_decimals_str.as_str()); // check if we can parse the number to a usize if let Ok(ct) = ct_res { // and if so, make i_val longer while i_val.len() < ct { i_val = format!("0{i_val}"); } } } } return i_val; } else if field.ends_with('f') { let mut f_val: String = call_to_string(ctx, value).unwrap_or_default(); if let Some(dot_in_field_idx) = field.find('.') { let mut m_field = field.to_string(); // get part behind dot let mut num_decimals_str = m_field.split_off(dot_in_field_idx + 1); // remove d or i at end let _ = num_decimals_str.split_off(num_decimals_str.len() - 1); // see if we have a number if !num_decimals_str.is_empty() { let ct_res = usize::from_str(num_decimals_str.as_str()); // check if we can parse the number to a usize if let Ok(ct) = ct_res { // and if so, make i_val longer if ct > 0 { if !f_val.contains('.') { f_val.push('.'); } let dot_idx = f_val.find('.').unwrap(); while f_val.len() - dot_idx <= ct { f_val.push('0'); } if f_val.len() - dot_idx > ct { let _ = f_val.split_off(dot_idx + ct + 1); } } } } return f_val; } } else if field.ends_with('o') || field.ends_with('O') { let json_str_res = json::stringify(ctx, value, None); let json = match json_str_res { Ok(json_str) => { if json_str.is_undefined() { // if undefined is passed tp json.stringify it returns undefined, else always a string "undefined".to_string() } else { primitives::to_string(ctx, &json_str).unwrap_or_default() } } Err(_e) => "".to_string(), }; return json; } call_to_string(ctx, value).unwrap_or_default() } unsafe fn stringify_log_obj(ctx: *mut q::JSContext, arg: &QuickJsValueAdapter) -> String { match stringify(ctx, arg, None) { Ok(r) => match primitives::to_string(ctx, &r) { Ok(s) => s, Err(e) => format!("Error: {e}"), }, Err(e) => format!("Error: {e}"), } } #[allow(clippy::or_fun_call)] unsafe fn parse_line(ctx: *mut q::JSContext, args: Vec<QuickJsValueAdapter>) -> String { let mut output = String::new(); output.push_str("JS_REALM:"); QuickJsRealmAdapter::with_context(ctx, |realm| { output.push('['); output.push_str(realm.id.as_str()); output.push_str("]["); if let Ok(script_or_module_name) = quickjs_utils::get_script_or_module_name_q(realm) { output.push_str(script_or_module_name.as_str()); } output.push_str("]: "); }); if args.is_empty() { return output; } let message = match &args[0].get_js_type() { JsValueType::Object => stringify_log_obj(ctx, &args[0]), JsValueType::Function => stringify_log_obj(ctx, &args[0]), JsValueType::Array => stringify_log_obj(ctx, &args[0]), _ => functions::call_to_string(ctx, &args[0]).unwrap_or_default(), }; let mut field_code = String::new(); let mut in_field = false; let mut x = 1; let mut filled = 1; if args[0].is_string() { for chr in message.chars() { if in_field { field_code.push(chr); if chr.eq(&'s') || chr.eq(&'d') || chr.eq(&'f') || chr.eq(&'o') || chr.eq(&'i') { // end field if x < args.len() { output.push_str( parse_field_value(ctx, field_code.as_str(), &args[x]).as_str(), ); x += 1; filled += 1; } in_field = false; field_code = String::new(); } } else if chr.eq(&'%') { in_field = true; } else { output.push(chr); } } } else { output.push_str(message.as_str()); } for arg in args.iter().skip(filled) { // add args which we're not filled in str output.push(' '); let tail_arg = match arg.get_js_type() { JsValueType::Object => stringify_log_obj(ctx, arg), JsValueType::Function => stringify_log_obj(ctx, arg), JsValueType::Array => stringify_log_obj(ctx, arg), _ => call_to_string(ctx, arg).unwrap_or_default(), }; output.push_str(tail_arg.as_str()); } output } unsafe extern "C" fn console_log( ctx: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { if log::max_level() >= LevelFilter::Info { let args = parse_args(ctx, argc, argv); log::info!("{}", parse_line(ctx, args)); } quickjs_utils::new_null() } unsafe extern "C" fn console_trace( ctx: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { if log::max_level() >= LevelFilter::Trace { let args = parse_args(ctx, argc, argv); log::trace!("{}", parse_line(ctx, args)); } quickjs_utils::new_null() } unsafe extern "C" fn console_debug( ctx: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { if log::max_level() >= LevelFilter::Debug { let args = parse_args(ctx, argc, argv); log::debug!("{}", parse_line(ctx, args)); } quickjs_utils::new_null() } unsafe extern "C" fn console_info( ctx: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { if log::max_level() >= LevelFilter::Info { let args = parse_args(ctx, argc, argv); log::info!("{}", parse_line(ctx, args)); } quickjs_utils::new_null() } unsafe extern "C" fn console_warn( ctx: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { if log::max_level() >= LevelFilter::Warn { let args = parse_args(ctx, argc, argv); log::warn!("{}", parse_line(ctx, args)); } quickjs_utils::new_null() } unsafe extern "C" fn console_error( ctx: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { if log::max_level() >= LevelFilter::Error { let args = parse_args(ctx, argc, argv); log::error!("{}", parse_line(ctx, args)); } quickjs_utils::new_null() } #[cfg(test)] pub mod tests { use crate::builder::QuickJsRuntimeBuilder; use crate::jsutils::Script; use std::thread; use std::time::Duration; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] pub async fn test_console() { eprintln!("> test_console"); /* let loglevel = log::LevelFilter::Info; tracing_log::LogTracer::builder() //.ignore_crate("swc_ecma_codegen") //.ignore_crate("swc_ecma_transforms_base") .with_max_level(loglevel) .init() .expect("could not init LogTracer"); // Graylog address let address = format!("{}:{}", "192.168.10.43", 12201); // Start tracing let mut conn_handle = tracing_gelf::Logger::builder() .init_udp(address) .expect("could not init udp con for logger"); // Spawn background task // Any futures executor can be used println!("> init"); tokio::runtime::Handle::current().spawn(async move { // conn_handle.connect().await // }); println!("< init"); log::error!("Logger initialized"); tracing::error!("via tracing"); */ // Send log using a macro defined in the create log log::info!("> test_console"); let rt = QuickJsRuntimeBuilder::new().build(); rt.eval_sync( None, Script::new( "test_console.es", "console.log('one %s', 'two', 3);\ console.error('two %s %s', 'two', 3);\ console.error('date:', new Date());\ console.error('err:', new Error('testpoof'));\ console.error('array:', [1, 2, true, {a: 1}]);\ console.error('obj: %o', {a: 1});\ console.error({obj: true}, {obj: false});", ), ) .expect("test_console.es failed"); log::info!("< test_console"); thread::sleep(Duration::from_secs(1)); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/features/setimmediate.rs
src/features/setimmediate.rs
use crate::facades::QuickJsRuntimeFacade; use crate::jsutils::JsError; use crate::quickjs_utils; use crate::quickjs_utils::{functions, get_global_q, objects, parse_args}; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use libquickjs_sys as q; /// provides the setImmediate methods for the runtime /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use std::time::Duration; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.eval_sync(None, Script::new("test_immediate.es", "setImmediate(() => {console.log('immediate logging')});")).expect("script failed"); /// std::thread::sleep(Duration::from_secs(1)); /// ``` pub fn init(q_js_rt: &QuickJsRuntimeAdapter) -> Result<(), JsError> { log::trace!("setimmediate::init"); q_js_rt.add_context_init_hook(|_q_js_rt, q_ctx| { let set_immediate_func = functions::new_native_function_q(q_ctx, "setImmediate", Some(set_immediate), 1, false)?; let global = get_global_q(q_ctx); objects::set_property2_q(q_ctx, &global, "setImmediate", &set_immediate_func, 0)?; Ok(()) })?; Ok(()) } unsafe extern "C" fn set_immediate( context: *mut q::JSContext, _this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> q::JSValue { log::trace!("> set_immediate"); let args = parse_args(context, argc, argv); QuickJsRuntimeAdapter::do_with(move |q_js_rt| { let q_ctx = q_js_rt.get_quickjs_context(context); if args.is_empty() { return q_ctx.report_ex("setImmediate requires at least one argument"); } if !functions::is_function(context, &args[0]) { return q_ctx.report_ex("setImmediate requires a functions as first arg"); } QuickJsRuntimeFacade::add_local_task_to_event_loop(move |_q_js_rt| { let func = &args[0]; match functions::call_function(context, func, &args[1..], None) { Ok(_) => {} Err(e) => { log::error!("setImmediate failed: {}", e); } }; }); quickjs_utils::new_null() }) }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/typescript/mod.rs
src/typescript/mod.rs
// public transpile function which can also be used by gcs to transpile clientside ts use crate::jsutils::JsError; use crate::jsutils::Script; use crate::quickjs_utils::modules::detect_module; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use std::cell::RefCell; use std::collections::HashMap; use std::io; use std::str::FromStr; use std::sync::Arc; use swc::Compiler; use swc_common::errors::{ColorConfig, Handler}; use swc_common::{FileName, SourceMap}; pub enum TargetVersion { Es3, Es5, Es2016, Es2020, Es2021, Es2022, } impl TargetVersion { fn as_str(&self) -> &str { match self { TargetVersion::Es3 => "es3", TargetVersion::Es5 => "es5", TargetVersion::Es2016 => "es2016", TargetVersion::Es2020 => "es2020", TargetVersion::Es2021 => "es2021", TargetVersion::Es2022 => "es2022", } } } pub struct TypeScriptTranspiler { minify: bool, mangle: bool, external_helpers: bool, target: TargetVersion, compiler: Compiler, source_map: Arc<SourceMap>, } impl TypeScriptTranspiler { pub fn new(target: TargetVersion, minify: bool, external_helpers: bool, mangle: bool) -> Self { let source_map = Arc::<SourceMap>::default(); let compiler = swc::Compiler::new(source_map.clone()); Self { minify, mangle, external_helpers, target, source_map, compiler, } } // todo custom target pub fn transpile( &self, code: &str, file_name: &str, is_module: bool, ) -> Result<(String, Option<String>), JsError> { let globals = swc_common::Globals::new(); let code = code.to_string(); swc_common::GLOBALS.set(&globals, || { let handler = Handler::with_tty_emitter( ColorConfig::Auto, true, false, Some(self.source_map.clone()), ); let fm = self .source_map .new_source_file(Arc::new(FileName::Custom(file_name.into())), code); let mangle_config = if self.mangle { r#" { "topLevel": false, "keepClassNames": true } "# } else { "false" }; let minify_options = if self.minify { format!( r#" "minify": {{ "compress": {{ "unused": true }}, "format": {{ "comments": false }}, "mangle": {mangle_config} }}, "# ) } else { r#" "minify": { "format": { "comments": false } }, "# .to_string() }; let module = if is_module { r#" "module": { "type": "es6", "strict": true, "strictMode": true, "lazy": false, "noInterop": false, "ignoreDynamic": true }, "# } else { "" }; let cfg_json = format!( r#" {{ "minify": {}, "sourceMaps": true, {} "jsc": {{ {} "externalHelpers": {}, "parser": {{ "syntax": "typescript", "jsx": true, "tsx": true, "decorators": true, "decoratorsBeforeExport": true, "dynamicImport": true, "preserveAllComments": false }}, "transform": {{ "legacyDecorator": true, "decoratorMetadata": true, "react": {{ "runtime": "classic", "useBuiltins": true, "refresh": true }} }}, "target": "{}", "keepClassNames": true }} }} "#, self.minify, module, minify_options, self.external_helpers, self.target.as_str() ); log::trace!("using config {}", cfg_json); let cfg = serde_json::from_str(cfg_json.as_str()) .map_err(|e| JsError::new_string(format!("{e}")))?; let ops = swc::config::Options { config: cfg, ..Default::default() }; // todo see https://github.com/swc-project/swc/discussions/4126 // for better example let res = self.compiler.process_js_file(fm, &handler, &ops); match res { Ok(to) => Ok((to.code, to.map)), Err(e) => Err(JsError::new_string(format!("transpile failed: {e}"))), } }) } pub fn transpile_script(&self, script: &mut Script) -> Result<(), JsError> { if script.get_path().ends_with(".ts") { let code = script.get_code(); let is_module = detect_module(code); let js = self.transpile(code, script.get_path(), is_module)?; log::debug!("map: {:?}", js.1); script.set_transpiled_code(js.0, js.1); } log::debug!( "TypeScriptPreProcessor:process file={} result = {}", script.get_path(), script.get_runnable_code() ); Ok(()) } } impl Default for TypeScriptTranspiler { fn default() -> Self { Self::new(TargetVersion::Es2020, false, false, false) } } thread_local! { // we store this in a thread local inb the worker thread so they are dropped when the runtimefacade is dropped static SOURCE_MAPS: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new()); static TRANSPILER: RefCell<TypeScriptTranspiler> = RefCell::new(TypeScriptTranspiler::new(TargetVersion::Es2020, false, false, false)); } // fix stacktrace method pub(crate) fn transpile_serverside( _rt: &QuickJsRuntimeAdapter, script: &mut Script, ) -> Result<(), JsError> { // transpile and store map in qjsrt // transpile TRANSPILER.with(|rc| { let transpiler: &TypeScriptTranspiler = &rc.borrow(); transpiler.transpile_script(script) })?; // register in source_maps so fix_stack can use it later if let Some(map_str) = script.get_map() { SOURCE_MAPS.with(|rc| { let maps = &mut *rc.borrow_mut(); maps.insert(script.get_path().to_string(), map_str.to_string()); }) } Ok(()) } #[derive(Debug)] struct StackEntry { function_name: String, file_name: String, line_number: Option<u32>, column_number: Option<u32>, } impl FromStr for StackEntry { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { // remove 'at ' let s = &s[3..]; let mut parts = s.splitn(2, ' '); let function_name = parts.next().unwrap_or("unnamed").to_string(); let mut file_name = parts.next().unwrap_or("(unknown)").to_string(); if file_name.starts_with('(') { file_name = file_name.as_str()[1..].to_string(); } if file_name.ends_with(')') { file_name = file_name.as_str()[..file_name.len() - 1].to_string(); } file_name = file_name.replace("://", "_double_point_placeholder_//"); let parts: Vec<&str> = file_name.split(':').collect(); let file_name = parts[0] .to_string() .replace("_double_point_placeholder_//", "://"); let line_number = parts.get(1).and_then(|s| s.parse::<u32>().ok()); let column_number = parts.get(2).and_then(|s| s.parse::<u32>().ok()); Ok(StackEntry { function_name, file_name, column_number, line_number, }) } } fn parse_stack_trace(stack_trace: &str) -> Result<Vec<StackEntry>, String> { let entries: Vec<StackEntry> = stack_trace .lines() .map(|line| line.trim()) .filter(|line| !line.is_empty()) .map(|line| line.parse::<StackEntry>()) .collect::<Result<Vec<_>, _>>()?; Ok(entries) } fn serialize_stack(entries: &[StackEntry]) -> String { let mut result = String::new(); for entry in entries { let fname_lnum = if let Some(line_number) = entry.line_number { if let Some(column_number) = entry.column_number { format!("{}:{line_number}:{column_number}", entry.file_name) } else { format!("{}:{line_number}", entry.file_name) } } else { entry.file_name.clone() }; result.push_str(&format!(" at {} ({fname_lnum})", entry.function_name)); result.push('\n'); } result } pub(crate) fn unmap_stack_trace(stack_trace: &str) -> String { // todo: not the fastest way to impl this.. should I keep instances of source map instead of string? what does that do to mem consumtion? SOURCE_MAPS.with(|rc| fix_stack_trace(stack_trace, &rc.borrow())) } pub fn fix_stack_trace(stack_trace: &str, maps: &HashMap<String, String>) -> String { log::trace!("fix_stack_trace:\n{stack_trace}"); match parse_stack_trace(stack_trace) { Ok(mut parsed_stack) => { for stack_trace_entry in parsed_stack.iter_mut() { if let Some(map_str) = maps.get(stack_trace_entry.file_name.as_str()) { log::trace!( "fix_stack_trace:found map for file {}:\n{map_str}", stack_trace_entry.file_name.as_str() ); if let Some(line_number) = stack_trace_entry.line_number { log::trace!("lookup line number:{line_number}"); match swc::sourcemap::SourceMap::from_reader(io::Cursor::new(map_str)) { Ok(source_map) => { if let Some(original_location) = source_map.lookup_token( line_number - 1, stack_trace_entry.column_number.unwrap_or(1) - 1, ) { let original_line = original_location.get_src_line(); let original_column = original_location.get_src_col(); log::trace!("lookup original_line:{original_line}"); stack_trace_entry.line_number = Some(original_line + 1); stack_trace_entry.column_number = Some(original_column + 1); } } Err(_) => { log::trace!( "could not parse source_map for {}", stack_trace_entry.file_name.as_str() ); } } } } else { log::trace!("no map found for {}", stack_trace_entry.file_name.as_str()); } // Now you have the original filename and line number // You can use them as needed } let ret = serialize_stack(&parsed_stack); log::trace!("fix_stack_trace ret:\n{ret}"); ret } Err(_) => { log::error!("could not parse stack: \n{}", stack_trace); stack_trace.to_string() } } } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::{JsValueType, Script}; use crate::typescript::{parse_stack_trace, serialize_stack}; #[test] fn test_ts() { let rt = init_test_rt(); println!("testing ts"); let script = Script::new( "test.ts", r#" // hi // ho function t_ts(a: string, b: num): boolean { return true; } t_ts("hello", 1337); "#, ); let res = rt.eval_sync(None, script).expect("script failed"); assert!(res.get_value_type() == JsValueType::Boolean); } #[test] fn test_stack_map() { let rt = init_test_rt(); println!("testing ts"); let script = Script::new( "test.ts", r#" type Nonsense = { hello: string }; function t_ts(a: string, b: num): boolean { return a.a.a === "hi"; } t_ts("hello", 1337); "#, ); let res = rt .eval_sync(None, script) .expect_err("script passed.. which it shouldnt"); // far from perfect test, also line numbers don't yet realy match.. // check again after https://github.com/HiRoFa/quickjs_es_runtime/issues/77 println!("stack:{}", res.get_stack()); // bellard is actually better as it points at the actual issue, not the start of the function #[cfg(feature = "bellard")] assert!(res.get_stack().contains("t_ts (test.ts:8")); #[cfg(feature = "quickjs-ng")] assert!(res.get_stack().contains("t_ts (test.ts:7")); } #[test] fn test_stack_parse() { // just to init logging; let _rt = init_test_rt(); let stack = r#" at func (file.ts:88:12) at doWriteTransactioned (gcsproject:///gcs_objectstore/ObjectStore.ts:170) "#; match parse_stack_trace(stack) { Ok(a) => { assert_eq!(a[0].file_name, "file.ts"); assert_eq!(a[0].line_number, Some(88)); assert_eq!(a[0].column_number, Some(12)); assert_eq!(a[0].function_name, "func"); assert_eq!( a[1].file_name, "gcsproject:///gcs_objectstore/ObjectStore.ts" ); assert_eq!(a[1].line_number, Some(170)); assert_eq!(a[1].column_number, None); assert_eq!(a[1].function_name, "doWriteTransactioned"); assert_eq!( serialize_stack(&a).as_str(), r#" at func (file.ts:88:12) at doWriteTransactioned (gcsproject:///gcs_objectstore/ObjectStore.ts:170) "# ); } Err(e) => { panic!("{}", e); } } } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/class_ids.rs
src/quickjs_utils/class_ids.rs
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/errors.rs
src/quickjs_utils/errors.rs
//! utils for getting and reporting exceptions use crate::jsutils::JsError; use crate::quickjs_utils::{objects, primitives}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::{QuickJsValueAdapter, TAG_EXCEPTION}; use libquickjs_sys as q; /// Get the last exception from the runtime, and if present, convert it to an JsError. /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_exception(context: *mut q::JSContext) -> Option<JsError> { log::trace!("get_exception"); let exception_val = q::JS_GetException(context); log::trace!("get_exception / 2"); let exception_ref = QuickJsValueAdapter::new(context, exception_val, false, true, "errors::get_exception"); if exception_ref.is_null() { None } else { let err = if exception_ref.is_exception() { JsError::new_str("Could not get exception from runtime") } else if exception_ref.is_object() { error_to_js_error(context, &exception_ref) } else { match exception_ref.to_string() { Ok(s) => JsError::new_string(s), Err(ex) => { JsError::new_string(format!("Could not determine error due to error: {ex:?}")) } } }; Some(err) } } /// convert an instance of Error to JsError /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn error_to_js_error( context: *mut q::JSContext, exception_ref: &QuickJsValueAdapter, ) -> JsError { log::trace!("error_to_js_error"); let name_ref = objects::get_property(context, exception_ref, "name") .ok() .unwrap(); let name_string = primitives::to_string(context, &name_ref).ok().unwrap(); let message_ref = objects::get_property(context, exception_ref, "message") .ok() .unwrap(); let message_string = primitives::to_string(context, &message_ref).ok().unwrap(); let stack_ref = objects::get_property(context, exception_ref, "stack") .ok() .unwrap(); let mut stack_string = "".to_string(); let stack2_ref = objects::get_property(context, exception_ref, "stack2") .ok() .unwrap(); if stack2_ref.is_string() { stack_string.push_str( primitives::to_string(context, &stack2_ref) .ok() .unwrap() .as_str(), ); } if stack_ref.is_string() { let stack_str = primitives::to_string(context, &stack_ref).ok().unwrap(); #[cfg(feature = "typescript")] let stack_str = crate::typescript::unmap_stack_trace(stack_str.as_str()); stack_string.push_str(stack_str.as_str()); } let cause_ref = objects::get_property(context, exception_ref, "cause") .ok() .unwrap(); // add cause as cause but also extend the stack trace with the cause stack trace if cause_ref.is_null_or_undefined() { JsError::new(name_string, message_string, stack_string) } else { QuickJsRealmAdapter::with_context(context, |realm| { let cause_str = cause_ref.to_string().ok().unwrap(); let cause_jsvf = realm.to_js_value_facade(&cause_ref).ok().unwrap(); stack_string.push_str("Caused by: "); stack_string.push_str(cause_str.as_str()); JsError::new2(name_string, message_string, stack_string, cause_jsvf) }) } } /// Create a new Error object /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn new_error( context: *mut q::JSContext, name: &str, message: &str, stack: &str, ) -> Result<QuickJsValueAdapter, JsError> { let obj = q::JS_NewError(context); let obj_ref = QuickJsValueAdapter::new( context, obj, false, true, format!("new_error {name}").as_str(), ); objects::set_property( context, &obj_ref, "message", &primitives::from_string(context, message)?, )?; objects::set_property( context, &obj_ref, "name", &primitives::from_string(context, name)?, )?; objects::set_property( context, &obj_ref, "stack2", &primitives::from_string(context, stack)?, )?; Ok(obj_ref) } /// See if a JSValueRef is an Error object pub fn is_error_q(q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter) -> bool { unsafe { is_error(q_ctx.context, obj_ref) } } /// See if a JSValueRef is an Error object /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid #[allow(unused_variables)] pub unsafe fn is_error(context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter) -> bool { if obj_ref.is_object() { #[cfg(feature = "bellard")] { let res = q::JS_IsError(context, *obj_ref.borrow_value()); res != 0 } #[cfg(feature = "quickjs-ng")] { q::JS_IsError(*obj_ref.borrow_value()) } } else { false } } pub fn get_stack(realm: &QuickJsRealmAdapter) -> Result<QuickJsValueAdapter, JsError> { let e = realm.invoke_function_by_name(&[], "Error", &[])?; realm.get_object_property(&e, "stack") } /// Throw an error and get an Exception JSValue to return from native methods /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn throw(context: *mut q::JSContext, error: QuickJsValueAdapter) -> q::JSValue { assert!(is_error(context, &error)); q::JS_Throw(context, error.clone_value_incr_rc()); q::JSValue { u: q::JSValueUnion { int32: 0 }, tag: TAG_EXCEPTION, } } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::{JsError, Script}; use crate::quickjs_utils::functions; use crate::values::{JsValueConvertable, JsValueFacade}; use std::thread; use std::time::Duration; #[test] fn test_ex_nat() { // check if stacktrace is preserved when invoking native methods let rt = init_test_rt(); let res = rt.eval_sync( None, Script::new( "ex.js", "console.log('foo');\nconsole.log('bar');let a = __c_v__ * 7;", ), ); let ex = res.expect_err("script should have failed;"); #[cfg(feature = "bellard")] assert_eq!(ex.get_message(), "'__c_v__' is not defined"); #[cfg(feature = "quickjs-ng")] assert_eq!(ex.get_message(), "__c_v__ is not defined"); } #[test] fn test_ex_cause() { // check if stacktrace is preserved when invoking native methods let rt = init_test_rt(); let res = rt.eval_sync( None, Script::new( "ex.ts", r#" let a = 2; let b = 3; function f1(a, b) { throw new Error('Could not f1', { cause: 'Sabotage here' }); } function f2() { try { let r = f1(a, b); } catch(ex) { throw new Error('could not f2', { cause: ex}); } } f2() "#, ), ); let ex = res.expect_err("script should have failed;"); assert_eq!(ex.get_message(), "could not f2"); let complete_err = format!("{ex}"); assert!(complete_err.contains("Caused by: Error: Could not f1")); assert!(complete_err.contains("Caused by: Sabotage here")); } #[test] fn test_ex0() { // check if stacktrace is preserved when invoking native methods let rt = init_test_rt(); let res = rt.eval_sync( None, Script::new( "ex.js", "console.log('foo');\nconsole.log('bar');let a = __c_v__ * 7;", ), ); let ex = res.expect_err("script should have failed;"); #[cfg(feature = "bellard")] assert_eq!(ex.get_message(), "'__c_v__' is not defined"); #[cfg(feature = "quickjs-ng")] assert_eq!(ex.get_message(), "__c_v__ is not defined"); } #[test] fn test_ex1() { // check if stacktrace is preserved when invoking native methods let rt = init_test_rt(); rt.set_function(&[], "test_consume", move |_realm, args| { // args[0] is a function i'll want to call let func_jsvf = &args[0]; match func_jsvf { JsValueFacade::JsFunction { cached_function } => { let _ = cached_function.invoke_function_sync(vec![12.to_js_value_facade()])?; Ok(0.to_js_value_facade()) } _ => Err(JsError::new_str("poof")), } }) .expect("could not set function"); let s_res = rt.eval_sync( None, Script::new( "test_ex34245.js", "let consumer = function() { console.log('consuming'); throw new Error('oh dear stuff failed at line 3 in consumer'); }; console.log('calling consume from line 6'); let a = test_consume(consumer); console.log('should never reach line 7 %s', a)", ), ); match s_res { Ok(o) => { log::info!("o = {}", o.stringify()); } Err(e) => { log::error!("script failed: {}", e); log::error!("{}", e); } } std::thread::sleep(Duration::from_secs(1)); } #[test] fn test_ex3() { let rt = init_test_rt(); rt.eval_sync( None, Script::new( "test_ex3.js", r#" async function a() { await b(); } async function b() { //await 1; throw Error("poof"); } a().catch((ex) => { console.error(ex); }); "#, ), ) .expect("script failed"); thread::sleep(Duration::from_secs(1)); } #[test] fn test_ex_stack() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|rt| { let realm = rt.get_main_realm(); realm .install_closure( &[], "myFunc", |_rt, realm, _this, _args| crate::quickjs_utils::errors::get_stack(realm), 0, ) .expect("could not install func"); let res = realm .eval(Script::new( "runMyFunc.js", r#" function a(){ return b(); } function b(){ return myFunc(); } a() "#, )) .expect("script failed"); log::info!("test_ex_stack res = {}", res.to_string().unwrap()); }); } #[test] fn test_ex2() { // check if stacktrace is preserved when invoking native methods //simple_logging::log_to_stderr(LevelFilter::Info); let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); q_ctx .eval(Script::new( "test_ex2_pre.es", "console.log('before ex test');", )) .expect("test_ex2_pre failed"); { let func_ref1 = q_ctx .eval(Script::new( "test_ex2f1.es", "(function(){\nconsole.log('running f1');});", )) .expect("script failed"); assert!(functions::is_function_q(q_ctx, &func_ref1)); let res = functions::call_function_q(q_ctx, &func_ref1, &[], None); match res { Ok(_) => {} Err(e) => { log::error!("func1 failed: {}", e); } } } // why the f does this fail with a stack overflow if i remove the block above? let func_ref2 = q_ctx .eval(Script::new( "test_ex2.es", r#" const f = function(){ throw Error('poof'); }; f "#, )) .expect("script failed"); assert!(functions::is_function_q(q_ctx, &func_ref2)); let res = functions::call_function_q(q_ctx, &func_ref2, &[], None); match res { Ok(_) => {} Err(e) => { log::error!("func2 failed: {}", e); } } }); #[cfg(feature = "bellard")] { let mjsvf = rt .eval_module_sync( None, Script::new( "test_ex2.es", r#" throw Error('poof'); "#, ), ) .map_err(|e| { log::error!("script compilation failed: {e}"); e }) .expect("script compilation failed"); match mjsvf { JsValueFacade::JsPromise { cached_promise } => { let pres = cached_promise .get_promise_result_sync() .expect("promise timed out"); match pres { Ok(m) => { log::info!("prom resolved to {}", m.stringify()) } Err(e) => { log::info!("prom rejected to {}", e.stringify()) } } } _ => { panic!("not a prom") } } } std::thread::sleep(Duration::from_secs(1)); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/dates.rs
src/quickjs_utils/dates.rs
//! Utils for working with Date objects use crate::jsutils::JsError; use crate::quickjs_utils; #[cfg(feature = "bellard")] use crate::quickjs_utils::class_ids::JS_CLASS_DATE; use crate::quickjs_utils::{functions, primitives}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; #[cfg(feature = "bellard")] use libquickjs_sys::JS_GetClassID; #[cfg(feature = "quickjs-ng")] use libquickjs_sys::JS_IsDate; /// create a new instance of a Date object pub fn new_date_q(context: &QuickJsRealmAdapter) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_date(context.context) } } /// create a new instance of a Date object /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn new_date(context: *mut q::JSContext) -> Result<QuickJsValueAdapter, JsError> { let constructor = quickjs_utils::get_constructor(context, "Date")?; let date_ref = functions::call_constructor(context, &constructor, &[])?; Ok(date_ref) } /// check if a JSValueRef is an instance of Date pub fn is_date_q(context: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter) -> bool { unsafe { is_date(context.context, obj_ref) } } /// check if a JSValueRef is an instance of Date /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid #[allow(unused_variables)] pub unsafe fn is_date(ctx: *mut q::JSContext, obj: &QuickJsValueAdapter) -> bool { #[cfg(feature = "bellard")] { JS_GetClassID(*obj.borrow_value()) == JS_CLASS_DATE } #[cfg(feature = "quickjs-ng")] { JS_IsDate(*obj.borrow_value()) } } /// set the timestamp for a Date object pub fn set_time_q( context: &QuickJsRealmAdapter, date_ref: &QuickJsValueAdapter, timestamp: f64, ) -> Result<(), JsError> { unsafe { set_time(context.context, date_ref, timestamp) } } /// set the timestamp for a Date object /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn set_time( context: *mut q::JSContext, date_ref: &QuickJsValueAdapter, timestamp: f64, ) -> Result<(), JsError> { functions::invoke_member_function( context, date_ref, "setTime", &[primitives::from_f64(timestamp)], )?; Ok(()) } /// get the timestamp from a Date object pub fn get_time_q( context: &QuickJsRealmAdapter, date_ref: &QuickJsValueAdapter, ) -> Result<f64, JsError> { unsafe { get_time(context.context, date_ref) } } /// get the timestamp from a Date object /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_time( context: *mut q::JSContext, date_ref: &QuickJsValueAdapter, ) -> Result<f64, JsError> { let time_ref = functions::invoke_member_function(context, date_ref, "getTime", &[])?; if time_ref.is_f64() { primitives::to_f64(&time_ref) } else if time_ref.is_i32() { primitives::to_i32(&time_ref).map(|i| i as f64) } else { Err(JsError::new_string(format!( "could not get time, val was a {}", time_ref.get_js_type() ))) } } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::quickjs_utils::dates; use crate::quickjs_utils::dates::{get_time_q, is_date_q, set_time_q}; #[test] fn test_date() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let date_ref = dates::new_date_q(q_ctx).expect("new_date failed"); assert!(is_date_q(q_ctx, &date_ref)); set_time_q(q_ctx, &date_ref, 1746776901898f64).expect("could not set time"); log::info!( "date_str={}", date_ref.to_string().expect("could not get date_ref string") ); let gt_res = get_time_q(q_ctx, &date_ref); match gt_res { Ok(t) => { assert_eq!(t, 1746776901898f64); } Err(e) => { panic!("get time failed: {}", e); } } set_time_q(q_ctx, &date_ref, 2f64).expect("could not set time"); let gt_res = get_time_q(q_ctx, &date_ref); match gt_res { Ok(t) => { assert_eq!(t, 2f64); } Err(e) => { panic!("get time 2 failed: {}", e); } } }); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/objects.rs
src/quickjs_utils/objects.rs
//! Utils for working with objects use crate::jsutils::JsError; use crate::quickjs_utils::properties::JSPropertyEnumRef; use crate::quickjs_utils::{atoms, functions, get_constructor, get_global}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::{make_cstring, QuickJsRuntimeAdapter}; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; /// get a namespace object /// this is used to get nested object properties which are used as namespaces /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::objects::get_namespace_q; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let ns_obj = get_namespace_q(q_ctx, &["com", "hirofa", "examplepackage"], true).ok().unwrap(); /// assert!(ns_obj.is_object()) /// }) /// ``` pub fn get_namespace_q( context: &QuickJsRealmAdapter, namespace: &[&str], create_if_absent: bool, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { get_namespace(context.context, namespace, create_if_absent) } } /// # Safety /// when passing a context ptr please be sure that the corresponding QuickJsContext is still active pub unsafe fn get_namespace( context: *mut q::JSContext, namespace: &[&str], create_if_absent: bool, ) -> Result<QuickJsValueAdapter, JsError> { log::trace!("objects::get_namespace({})", namespace.join(".")); let mut obj = get_global(context); for p_name in namespace { log::trace!("objects::get_namespace -> {}", p_name); let mut sub = get_property(context, &obj, p_name)?; if sub.is_null_or_undefined() { log::trace!("objects::get_namespace -> is null"); if create_if_absent { log::trace!("objects::get_namespace -> is null, creating"); // create sub = create_object(context)?; set_property2(context, &obj, p_name, &sub, 0)?; } else { log::trace!("objects::get_namespace -> is null -> err"); return Err(JsError::new_string(format!( "could not find namespace part: {p_name}" ))); } } else { log::trace!("objects::get_namespace -> found"); } obj = sub; } Ok(obj) } #[allow(dead_code)] /// construct a new instance of a constructor /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn construct_object( ctx: *mut q::JSContext, constructor_ref: &QuickJsValueAdapter, args: &[&QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> { let arg_count = args.len() as i32; let mut qargs = args.iter().map(|a| *a.borrow_value()).collect::<Vec<_>>(); let res = q::JS_CallConstructor( ctx, *constructor_ref.borrow_value(), arg_count, qargs.as_mut_ptr(), ); let res_ref = QuickJsValueAdapter::new(ctx, res, false, true, "construct_object result"); if res_ref.is_exception() { if let Some(ex) = QuickJsRealmAdapter::get_exception(ctx) { Err(ex) } else { Err(JsError::new_str( "construct_object failed but could not get ex", )) } } else { Ok(res_ref) } } /// create a new simple object, e.g. `let obj = {};` pub fn create_object_q(q_ctx: &QuickJsRealmAdapter) -> Result<QuickJsValueAdapter, JsError> { unsafe { create_object(q_ctx.context) } } /// create a new simple object, e.g. `let obj = {};` /// # Safety /// when passing a context ptr please be sure that the corresponding QuickJsContext is still active pub unsafe fn create_object(context: *mut q::JSContext) -> Result<QuickJsValueAdapter, JsError> { let obj = q::JS_NewObject(context); let obj_ref = QuickJsValueAdapter::new(context, obj, false, true, "objects::create_object"); if obj_ref.is_exception() { return Err(JsError::new_str("Could not create object")); } Ok(obj_ref) } /// set a property in an object, like `obj[propName] = val;` pub fn set_property_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, prop_name: &str, prop_ref: &QuickJsValueAdapter, ) -> Result<(), JsError> { unsafe { set_property(q_ctx.context, obj_ref, prop_name, prop_ref) } } /// set a property in an object, like `obj[propName] = val;` /// # Safety /// when passing a context ptr please be sure that the corresponding QuickJsContext is still active pub unsafe fn set_property( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, prop_name: &str, prop_ref: &QuickJsValueAdapter, ) -> Result<(), JsError> { set_property2( context, obj_ref, prop_name, prop_ref, q::JS_PROP_C_W_E as i32, ) } /// set a property with specific flags /// set_property applies the default flag JS_PROP_C_W_E (Configurable, Writable, Enumerable) /// flags you can use here are /// * q::JS_PROP_CONFIGURABLE /// * q::JS_PROP_WRITABLE /// * q::JS_PROP_ENUMERABLE /// * q::JS_PROP_C_W_E /// * q::JS_PROP_LENGTH /// * q::JS_PROP_TMASK /// * q::JS_PROP_NORMAL /// * q::JS_PROP_GETSET /// * q::JS_PROP_VARREF /// * q::JS_PROP_AUTOINIT /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::objects::{create_object_q, set_property2_q}; /// use quickjs_runtime::quickjs_utils::primitives::from_i32; /// use libquickjs_sys as q; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let obj = create_object_q(q_ctx).ok().unwrap(); /// let prop = from_i32(785); /// // not enumerable /// set_property2_q(q_ctx, &obj, "someProp", &prop, (q::JS_PROP_CONFIGURABLE | q::JS_PROP_WRITABLE) as i32).ok().unwrap(); /// }) /// ``` pub fn set_property2_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, prop_name: &str, prop_ref: &QuickJsValueAdapter, flags: i32, ) -> Result<(), JsError> { unsafe { set_property2(q_ctx.context, obj_ref, prop_name, prop_ref, flags) } } /// set a property with specific flags /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn set_property2( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, prop_name: &str, prop_ref: &QuickJsValueAdapter, flags: i32, ) -> Result<(), JsError> { log::trace!("set_property2: {}", prop_name); let ckey = make_cstring(prop_name)?; /* pub const JS_PROP_CONFIGURABLE: u32 = 1; pub const JS_PROP_WRITABLE: u32 = 2; pub const JS_PROP_ENUMERABLE: u32 = 4; pub const JS_PROP_C_W_E: u32 = 7; pub const JS_PROP_LENGTH: u32 = 8; pub const JS_PROP_TMASK: u32 = 48; pub const JS_PROP_NORMAL: u32 = 0; pub const JS_PROP_GETSET: u32 = 16; pub const JS_PROP_VARREF: u32 = 32; pub const JS_PROP_AUTOINIT: u32 = 48; */ log::trace!("set_property2 / 2"); let ret = q::JS_DefinePropertyValueStr( context, *obj_ref.borrow_value(), ckey.as_ptr(), prop_ref.clone_value_incr_rc(), flags, ); log::trace!("set_property2 / 3"); if ret < 0 { return Err(JsError::new_str("Could not add property to object")); } log::trace!("set_property2 / 4"); Ok(()) } /// define a getter/setter property /// # Example /// ```dontrun /// use quickjs_runtime::esruntimebuilder::EsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::objects::{create_object_q, define_getter_setter_q, set_property_q}; /// use quickjs_runtime::quickjs_utils::functions::new_function_q; /// use quickjs_runtime::quickjs_utils::primitives::from_i32; /// use quickjs_runtime::quickjs_utils::{new_null_ref, get_global_q}; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::JsError::JsError; /// let rt = EsRuntimeBuilder::new().build(); /// rt.add_to_event_queue_sync(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_context(); /// let obj = create_object_q(q_ctx).ok().expect("create obj failed"); /// let getter_func = new_function_q(q_ctx, "getter", |_q_ctx, _this_ref, _args| {Ok(from_i32(13))}, 0).ok().expect("new_function_q getter failed"); /// let setter_func = new_function_q(q_ctx, "setter", |_q_ctx, _this_ref, args| { /// log::debug!("setting someProperty to {:?}", &args[0]); /// Ok(new_null_ref()) /// }, 1).ok().expect("new_function_q setter failed"); /// let res = define_getter_setter_q(q_ctx, &obj, "someProperty", &getter_func, &setter_func); /// match res { /// Ok(_) => {}, /// Err(e) => {panic!("define_getter_setter_q fail: {}", e)}} /// let global = get_global_q(q_ctx); /// set_property_q(q_ctx, &global, "testObj431", &obj).ok().expect("set prop on global failed"); /// }); /// rt.eval_sync(Script::new("define_getter_setter_q.es", "testObj431.someProperty = 'hello prop';")).ok().expect("script failed"); /// ``` pub fn define_getter_setter_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, prop_name: &str, getter_func_ref: &QuickJsValueAdapter, setter_func_ref: &QuickJsValueAdapter, ) -> Result<(), JsError> { unsafe { define_getter_setter( q_ctx.context, obj_ref, prop_name, getter_func_ref, setter_func_ref, ) } } #[allow(dead_code)] /// define a getter/setter property /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn define_getter_setter( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, prop_name: &str, getter_func_ref: &QuickJsValueAdapter, setter_func_ref: &QuickJsValueAdapter, ) -> Result<(), JsError> { /* pub fn JS_DefinePropertyGetSet( ctx: *mut JSContext, this_obj: JSValue, prop: JSAtom, getter: JSValue, setter: JSValue, flags: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int; */ log::trace!("objects::define_getter_setter 1"); debug_assert!(functions::is_function(context, getter_func_ref)); log::trace!("objects::define_getter_setter 2"); debug_assert!(functions::is_function(context, setter_func_ref)); log::trace!("objects::define_getter_setter 3"); let prop_atom = atoms::from_string(context, prop_name)?; log::trace!("objects::define_getter_setter 4"); let res = q::JS_DefinePropertyGetSet( context, *obj_ref.borrow_value(), prop_atom.get_atom(), getter_func_ref.clone_value_incr_rc(), setter_func_ref.clone_value_incr_rc(), q::JS_PROP_C_W_E as i32, ); log::trace!("objects::define_getter_setter 5 {}", res); if res != 0 { if let Some(err) = QuickJsRealmAdapter::get_exception(context) { Err(err) } else { Err(JsError::new_str( "Unknown error while creating getter setter", )) } } else { Ok(()) } } /// get a property from an object by name pub fn get_property_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, prop_name: &str, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { get_property(q_ctx.context, obj_ref, prop_name) } } /// get a property from an object by name /// # Safety /// when passing a context please ensure the corresponding QuickJsContext is still valid pub unsafe fn get_property( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, prop_name: &str, ) -> Result<QuickJsValueAdapter, JsError> { if obj_ref.is_null() || obj_ref.is_undefined() { return Err(JsError::new_str( "could not get prop from null or undefined", )); } let c_prop_name = make_cstring(prop_name)?; log::trace!("objects::get_property {}", prop_name); let prop_val = q::JS_GetPropertyStr(context, *obj_ref.borrow_value(), c_prop_name.as_ptr()); let prop_ref = QuickJsValueAdapter::new( context, prop_val, false, true, format!("object::get_property result: {prop_name}").as_str(), ); Ok(prop_ref) } /// get the property names of an object pub fn get_own_property_names_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, ) -> Result<JSPropertyEnumRef, JsError> { unsafe { get_own_property_names(q_ctx.context, obj_ref) } } /// get the property names of an object /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_own_property_names( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, ) -> Result<JSPropertyEnumRef, JsError> { let mut properties: *mut q::JSPropertyEnum = std::ptr::null_mut(); let mut count: u32 = 0; let flags = (q::JS_GPN_STRING_MASK | q::JS_GPN_SYMBOL_MASK | q::JS_GPN_ENUM_ONLY) as i32; let ret = q::JS_GetOwnPropertyNames( context, &mut properties, &mut count, *obj_ref.borrow_value(), flags, ); if ret != 0 { return Err(JsError::new_str("Could not get object properties")); } let enum_ref = JSPropertyEnumRef::new(context, properties, count); Ok(enum_ref) } /// get the names of all properties of an object pub fn get_property_names_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, ) -> Result<Vec<String>, JsError> { unsafe { get_property_names(q_ctx.context, obj_ref) } } /// get the names of all properties of an object /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_property_names( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, ) -> Result<Vec<String>, JsError> { let enum_ref = get_own_property_names(context, obj_ref)?; let mut names = vec![]; for index in 0..enum_ref.len() { let name = enum_ref.get_name(index)?; names.push(name); } Ok(names) } pub fn traverse_properties_q<V, R>( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, visitor: V, ) -> Result<Vec<R>, JsError> where V: Fn(&str, &QuickJsValueAdapter) -> Result<R, JsError>, { unsafe { traverse_properties(q_ctx.context, obj_ref, visitor) } } pub fn traverse_properties_q_mut<V, R>( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, visitor: V, ) -> Result<(), JsError> where V: FnMut(&str, &QuickJsValueAdapter) -> Result<R, JsError>, { unsafe { traverse_properties_mut(q_ctx.context, obj_ref, visitor) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn traverse_properties<V, R>( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, visitor: V, ) -> Result<Vec<R>, JsError> where V: Fn(&str, &QuickJsValueAdapter) -> Result<R, JsError>, { let enum_ref = get_own_property_names(context, obj_ref)?; let mut result = vec![]; for index in 0..enum_ref.len() { let atom = enum_ref.get_atom_raw(index) as q::JSAtom; let prop_name = atoms::to_string2(context, &atom)?; #[cfg(feature = "bellard")] let raw_value = q::JS_GetPropertyInternal( context, *obj_ref.borrow_value(), atom, *obj_ref.borrow_value(), 0, ); #[cfg(feature = "quickjs-ng")] let raw_value = q::JS_GetProperty(context, *obj_ref.borrow_value(), atom); let prop_val_ref = QuickJsValueAdapter::new( context, raw_value, false, true, "objects::traverse_properties raw_value", ); if prop_val_ref.is_exception() { return Err(JsError::new_str("Could not get object property")); } let r = visitor(prop_name.as_str(), &prop_val_ref)?; result.push(r); } Ok(result) } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn traverse_properties_mut<V, R>( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, mut visitor: V, ) -> Result<(), JsError> where V: FnMut(&str, &QuickJsValueAdapter) -> Result<R, JsError>, { let enum_ref = get_own_property_names(context, obj_ref)?; for index in 0..enum_ref.len() { let atom = enum_ref.get_atom_raw(index) as q::JSAtom; let prop_name = atoms::to_string2(context, &atom)?; #[cfg(feature = "bellard")] let raw_value = q::JS_GetPropertyInternal( context, *obj_ref.borrow_value(), atom, *obj_ref.borrow_value(), 0, ); #[cfg(feature = "quickjs-ng")] let raw_value = q::JS_GetProperty(context, *obj_ref.borrow_value(), atom); let prop_val_ref = QuickJsValueAdapter::new( context, raw_value, false, true, "objects::traverse_properties raw_value", ); if prop_val_ref.is_exception() { return Err(JsError::new_str("Could not get object property")); } visitor(prop_name.as_str(), &prop_val_ref)?; } Ok(()) } pub fn get_prototype_of_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { get_prototype_of(q_ctx.context, obj_ref) } } /// Object.prototypeOf /// # Safety /// please ensure the JSContext is valid and remains valid while using this function pub unsafe fn get_prototype_of( ctx: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { let raw = q::JS_GetPrototype(ctx, *obj_ref.borrow_value()); let pt_ref = QuickJsValueAdapter::new(ctx, raw, false, true, "object::get_prototype_of_q"); if pt_ref.is_exception() { if let Some(ex) = QuickJsRealmAdapter::get_exception(ctx) { Err(ex) } else { Err(JsError::new_str( "get_prototype_of_q failed but could not get ex", )) } } else { Ok(pt_ref) } } pub fn is_instance_of_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, constructor_ref: &QuickJsValueAdapter, ) -> bool { unsafe { is_instance_of(q_ctx.context, obj_ref, constructor_ref) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn is_instance_of( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, constructor_ref: &QuickJsValueAdapter, ) -> bool { if !obj_ref.is_object() { return false; } q::JS_IsInstanceOf( context, *obj_ref.borrow_value(), *constructor_ref.borrow_value(), ) > 0 } pub fn is_instance_of_by_name_q( context: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, constructor_name: &str, ) -> Result<bool, JsError> { unsafe { is_instance_of_by_name(context.context, obj_ref, constructor_name) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn is_instance_of_by_name( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, constructor_name: &str, ) -> Result<bool, JsError> { if !obj_ref.is_object() { return Ok(false); } let constructor_ref = get_constructor(context, constructor_name)?; if !constructor_ref.is_object() { return Ok(false); } if is_instance_of(context, obj_ref, &constructor_ref) { Ok(true) } else { // todo check if context is not __main__ QuickJsRuntimeAdapter::do_with(|q_js_rt| { let main_ctx = q_js_rt.get_main_realm(); let main_constructor_ref = get_constructor(main_ctx.context, constructor_name)?; if is_instance_of(main_ctx.context, obj_ref, &main_constructor_ref) { Ok(true) } else { Ok(false) } }) } } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::Script; use crate::quickjs_utils::objects::{ create_object_q, get_property_names_q, get_property_q, set_property_q, }; use crate::quickjs_utils::primitives::{from_i32, to_i32}; use crate::quickjs_utils::{get_global_q, primitives}; #[test] fn test_get_refs() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let obj = create_object_q(q_ctx).ok().expect("a"); let prop_ref = create_object_q(q_ctx).ok().expect("b"); let prop2_ref = create_object_q(q_ctx).ok().expect("c"); #[cfg(feature = "bellard")] assert_eq!(obj.get_ref_count(), 1); #[cfg(feature = "bellard")] assert_eq!(prop_ref.get_ref_count(), 1); set_property_q(q_ctx, &obj, "a", &prop_ref).ok().expect("d"); #[cfg(feature = "bellard")] assert_eq!(prop_ref.get_ref_count(), 2); set_property_q(q_ctx, &obj, "b", &prop_ref).ok().expect("e"); #[cfg(feature = "bellard")] assert_eq!(prop_ref.get_ref_count(), 3); set_property_q(q_ctx, &obj, "b", &prop2_ref) .ok() .expect("f"); #[cfg(feature = "bellard")] assert_eq!(prop_ref.get_ref_count(), 2); #[cfg(feature = "bellard")] assert_eq!(prop2_ref.get_ref_count(), 2); let p3 = get_property_q(q_ctx, &obj, "b").ok().expect("g"); #[cfg(feature = "bellard")] assert_eq!(p3.get_ref_count(), 3); #[cfg(feature = "bellard")] assert_eq!(prop2_ref.get_ref_count(), 3); drop(p3); #[cfg(feature = "bellard")] assert_eq!(prop2_ref.get_ref_count(), 2); drop(obj); q_js_rt.gc(); }); } #[test] fn test_get_n_drop() { log::info!("> test_get_n_drop"); let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let obj_a = create_object_q(q_ctx).ok().unwrap(); let obj_b = create_object_q(q_ctx).ok().unwrap(); set_property_q(q_ctx, &obj_a, "b", &obj_b).ok().unwrap(); let b1 = get_property_q(q_ctx, &obj_a, "b").ok().unwrap(); set_property_q(q_ctx, &b1, "i", &primitives::from_i32(123)) .ok() .unwrap(); drop(b1); q_js_rt.gc(); let b2 = get_property_q(q_ctx, &obj_a, "b").ok().unwrap(); let i_ref = get_property_q(q_ctx, &b2, "i").ok().unwrap(); let i = to_i32(&i_ref).ok().unwrap(); drop(i_ref); q_js_rt.gc(); let i_ref2 = get_property_q(q_ctx, &b2, "i").ok().unwrap(); let i2 = to_i32(&i_ref2).ok().unwrap(); assert_eq!(i, 123); assert_eq!(i2, 123); }); log::info!("< test_get_n_drop"); } #[test] fn test_propnames() { log::info!("> test_propnames"); let rt = init_test_rt(); let io = rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let obj_ref = q_ctx .eval(Script::new("test_propnames.es", "({one: 1, two: 2});")) .ok() .expect("could not get test obj"); let prop_names = get_property_names_q(q_ctx, &obj_ref) .ok() .expect("could not get prop names"); assert_eq!(prop_names.len(), 2); assert!(prop_names.contains(&"one".to_string())); assert!(prop_names.contains(&"two".to_string())); true }); assert!(io); log::info!("< test_propnames"); } #[test] fn test_set_prop() { log::info!("> test_set_prop"); let rt = init_test_rt(); let io = rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let obj_ref = create_object_q(q_ctx).ok().unwrap(); #[cfg(feature = "bellard")] assert_eq!(obj_ref.get_ref_count(), 1); let global_ref = get_global_q(q_ctx); set_property_q(q_ctx, &global_ref, "test_obj", &obj_ref) .ok() .expect("could not set property 1"); #[cfg(feature = "bellard")] assert_eq!(obj_ref.get_ref_count(), 2); let prop_ref = from_i32(123); let obj_ref = get_property_q(q_ctx, &global_ref, "test_obj") .ok() .expect("could not get test_obj"); set_property_q(q_ctx, &obj_ref, "test_prop", &prop_ref) .ok() .expect("could not set property 2"); drop(global_ref); q_js_rt.gc(); let a = q_ctx .eval(Script::new("test_set_prop.es", "(test_obj);")) .ok() .unwrap() .is_object(); assert!(a); let b = q_ctx .eval(Script::new("test_set_prop.es", "(test_obj.test_prop);")) .ok() .unwrap() .is_i32(); assert!(b); a && b }); assert!(io); log::info!("< test_set_prop"); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/properties.rs
src/quickjs_utils/properties.rs
use crate::jsutils::JsError; use crate::quickjs_utils::atoms; use crate::quickjs_utils::atoms::JSAtomRef; use libquickjs_sys as q; #[cfg(feature = "bellard")] use std::os::raw::c_int; #[allow(clippy::upper_case_acronyms)] /// this is a wrapper struct for JSPropertyEnum struct in quickjs /// it used primarily as a result of objects::get_own_property_names() pub struct JSPropertyEnumRef { context: *mut q::JSContext, property_enum: *mut q::JSPropertyEnum, length: u32, } impl JSPropertyEnumRef { pub fn new( context: *mut q::JSContext, property_enum: *mut q::JSPropertyEnum, length: u32, ) -> Self { Self { context, property_enum, length, } } /// get a raw ptr to an Atom /// # Safety /// do not drop the JSPropertyEnumRef while still using the ptr pub unsafe fn get_atom_raw(&self, index: u32) -> *mut q::JSAtom { if index >= self.length { panic!("index out of bounds"); } let prop: *mut q::JSPropertyEnum = self.property_enum.offset(index as isize); let atom: *mut q::JSAtom = (*prop).atom as *mut q::JSAtom; atom } pub fn get_atom(&self, index: u32) -> JSAtomRef { let atom: *mut q::JSAtom = unsafe { self.get_atom_raw(index) }; let atom_ref = JSAtomRef::new(self.context, atom as q::JSAtom); atom_ref.increment_ref_ct(); atom_ref } pub fn get_name(&self, index: u32) -> Result<String, JsError> { let atom: *mut q::JSAtom = unsafe { self.get_atom_raw(index) }; let atom = atom as q::JSAtom; unsafe { atoms::to_string2(self.context, &atom) } } pub fn is_enumerable(&self, index: u32) -> bool { if index >= self.length { panic!("index out of bounds"); } unsafe { let prop: *mut q::JSPropertyEnum = self.property_enum.offset(index as isize); #[cfg(feature = "bellard")] { let is_enumerable: c_int = (*prop).is_enumerable; is_enumerable != 0 } #[cfg(feature = "quickjs-ng")] (*prop).is_enumerable } } pub fn len(&self) -> u32 { self.length } pub fn is_empty(&self) -> bool { self.length == 0 } } impl Drop for JSPropertyEnumRef { fn drop(&mut self) { unsafe { for index in 0..self.length { let prop: *mut q::JSPropertyEnum = self.property_enum.offset(index as isize); q::JS_FreeAtom(self.context, (*prop).atom); } q::js_free(self.context, self.property_enum as *mut std::ffi::c_void); } } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/arrays.rs
src/quickjs_utils/arrays.rs
use crate::jsutils::JsError; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; /// Check whether an object is an array /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::arrays; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let obj_ref = q_ctx.eval(Script::new("is_array_test.es", "([1, 2, 3]);")).ok().expect("script failed"); /// let is_array = arrays::is_array_q(q_ctx, &obj_ref); /// assert!(is_array); /// }); /// ``` pub fn is_array_q(q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter) -> bool { unsafe { is_array(q_ctx.context, obj_ref) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid #[allow(unused_variables)] pub unsafe fn is_array(context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter) -> bool { let r = obj_ref.borrow_value(); #[cfg(feature = "bellard")] { let val = q::JS_IsArray(context, *r); val > 0 } #[cfg(feature = "quickjs-ng")] { q::JS_IsArray(*r) } } /// Get the length of an Array /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::arrays; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let obj_ref = q_ctx.eval(Script::new("get_length_test.es", "([1, 2, 3]);")).ok().expect("script failed"); /// let len = arrays::get_length_q(q_ctx, &obj_ref).ok().expect("could not get length"); /// assert_eq!(len, 3); /// }); /// ``` pub fn get_length_q( q_ctx: &QuickJsRealmAdapter, arr_ref: &QuickJsValueAdapter, ) -> Result<u32, JsError> { unsafe { get_length(q_ctx.context, arr_ref) } } /// Get the length of an Array /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_length( context: *mut q::JSContext, arr_ref: &QuickJsValueAdapter, ) -> Result<u32, JsError> { let len_ref = crate::quickjs_utils::objects::get_property(context, arr_ref, "length")?; let len = crate::quickjs_utils::primitives::to_i32(&len_ref)?; Ok(len as u32) } /// Create a new Array /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::{arrays, primitives, functions}; /// use quickjs_runtime::quickjs_utils; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// // create a method to pass our new array to /// q_ctx.eval(Script::new("create_array_test.es", "this.create_array_func = function(arr){return arr.length;};")).ok().expect("script failed"); /// // create a new array /// let arr_ref = arrays::create_array_q(q_ctx).ok().expect("could not create array"); /// // add some values /// let val0 = primitives::from_i32(12); /// let val1 = primitives::from_i32(17); /// arrays::set_element_q(q_ctx, &arr_ref, 0, &val0).expect("could not set element"); /// arrays::set_element_q(q_ctx, &arr_ref, 1, &val1).expect("could not set element"); /// // call the function /// let result_ref = functions::invoke_member_function_q(q_ctx, &quickjs_utils::get_global_q(q_ctx), "create_array_func", &[arr_ref]).ok().expect("could not invoke function"); /// let len = primitives::to_i32(&result_ref).ok().unwrap(); /// assert_eq!(len, 2); /// }); /// ``` pub fn create_array_q(q_ctx: &QuickJsRealmAdapter) -> Result<QuickJsValueAdapter, JsError> { unsafe { create_array(q_ctx.context) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn create_array(context: *mut q::JSContext) -> Result<QuickJsValueAdapter, JsError> { let arr = q::JS_NewArray(context); let arr_ref = QuickJsValueAdapter::new(context, arr, false, true, "create_array"); if arr_ref.is_exception() { return Err(JsError::new_str("Could not create array in runtime")); } Ok(arr_ref) } /// Set a single element in an array /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::{arrays, primitives}; /// use quickjs_runtime::quickjs_utils; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// // get an Array from script /// let arr_ref = q_ctx.eval(Script::new("set_element_test.es", "([1, 2, 3]);")).ok().expect("script failed"); /// // add some values /// arrays::set_element_q(q_ctx, &arr_ref, 3, &primitives::from_i32(12)).expect("could not set element"); /// arrays::set_element_q(q_ctx, &arr_ref, 4, &primitives::from_i32(17)).expect("could not set element"); /// // get the length /// let len = arrays::get_length_q(q_ctx, &arr_ref).ok().unwrap(); /// assert_eq!(len, 5); /// }); /// ``` pub fn set_element_q( q_ctx: &QuickJsRealmAdapter, array_ref: &QuickJsValueAdapter, index: u32, entry_value_ref: &QuickJsValueAdapter, ) -> Result<(), JsError> { unsafe { set_element(q_ctx.context, array_ref, index, entry_value_ref) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn set_element( context: *mut q::JSContext, array_ref: &QuickJsValueAdapter, index: u32, entry_value_ref: &QuickJsValueAdapter, ) -> Result<(), JsError> { let ret = q::JS_DefinePropertyValueUint32( context, *array_ref.borrow_value(), index, entry_value_ref.clone_value_incr_rc(), q::JS_PROP_C_W_E as i32, ); if ret < 0 { return Err(JsError::new_str("Could not append element to array")); } Ok(()) } /// Get a single element from an array /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::{arrays, primitives}; /// use quickjs_runtime::quickjs_utils; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// // get an Array from script /// let arr_ref = q_ctx.eval(Script::new("get_element_test.es", "([1, 2, 3]);")).ok().expect("script failed"); /// // get a value, the 3 in this case /// let val_ref = arrays::get_element_q(q_ctx, &arr_ref, 2).ok().unwrap(); /// let val_i32 = primitives::to_i32(&val_ref).ok().unwrap(); /// // get the length /// assert_eq!(val_i32, 3); /// }); /// ``` pub fn get_element_q( q_ctx: &QuickJsRealmAdapter, array_ref: &QuickJsValueAdapter, index: u32, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { get_element(q_ctx.context, array_ref, index) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_element( context: *mut q::JSContext, array_ref: &QuickJsValueAdapter, index: u32, ) -> Result<QuickJsValueAdapter, JsError> { let value_raw = q::JS_GetPropertyUint32(context, *array_ref.borrow_value(), index); let ret = QuickJsValueAdapter::new( context, value_raw, false, true, format!("get_element[{index}]").as_str(), ); if ret.is_exception() { return Err(JsError::new_str("Could not build array")); } Ok(ret) } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::quickjs_utils::arrays::{create_array_q, get_element_q, set_element_q}; use crate::quickjs_utils::objects; #[test] fn test_array() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let arr = create_array_q(q_ctx).ok().unwrap(); #[cfg(feature = "bellard")] assert_eq!(arr.get_ref_count(), 1); let a = objects::create_object_q(q_ctx).ok().unwrap(); #[cfg(feature = "bellard")] assert_eq!(1, a.get_ref_count()); set_element_q(q_ctx, &arr, 0, &a).ok().unwrap(); #[cfg(feature = "bellard")] assert_eq!(2, a.get_ref_count()); let _a2 = get_element_q(q_ctx, &arr, 0).ok().unwrap(); #[cfg(feature = "bellard")] assert_eq!(3, a.get_ref_count()); #[cfg(feature = "bellard")] assert_eq!(3, _a2.get_ref_count()); }); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/compile.rs
src/quickjs_utils/compile.rs
//! Utils to compile script to bytecode and run script from bytecode use crate::jsutils::JsError; use crate::jsutils::Script; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::make_cstring; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; use std::os::raw::c_void; /// compile a script, will result in a JSValueRef with tag JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE. /// It can be executed with run_compiled_function(). /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::quickjs_utils::compile::{compile, run_compiled_function}; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// unsafe { /// let q_ctx = q_js_rt.get_main_realm(); /// let func_res = compile(q_ctx.context, Script::new("test_func.es", "let a = 7; let b = 5; a * b;")); /// let func = func_res.ok().expect("func compile failed"); /// let run_res = run_compiled_function(q_ctx.context, &func); /// let res = run_res.ok().expect("run_compiled_function failed"); /// let i_res = primitives::to_i32(&res); /// let i = i_res.ok().expect("could not convert to i32"); /// assert_eq!(i, 7*5); /// } /// }); /// ``` /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn compile( context: *mut q::JSContext, script: Script, ) -> Result<QuickJsValueAdapter, JsError> { let filename_c = make_cstring(script.get_path())?; let code_str = script.get_runnable_code(); let code_c = make_cstring(code_str)?; log::debug!("q_js_rt.compile file {}", script.get_path()); let value_raw = q::JS_Eval( context, code_c.as_ptr(), code_str.len() as _, filename_c.as_ptr(), q::JS_EVAL_FLAG_COMPILE_ONLY as i32, ); log::trace!("after compile, checking error"); // check for error let ret = QuickJsValueAdapter::new( context, value_raw, false, true, format!("eval result of {}", script.get_path()).as_str(), ); if ret.is_exception() { let ex_opt = QuickJsRealmAdapter::get_exception(context); if let Some(ex) = ex_opt { Err(ex) } else { Err(JsError::new_str( "compile failed and could not get exception", )) } } else { Ok(ret) } } /// run a compiled function, see compile for an example /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn run_compiled_function( context: *mut q::JSContext, compiled_func: &QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { assert!(compiled_func.is_compiled_function()); let val = q::JS_EvalFunction(context, compiled_func.clone_value_incr_rc()); let val_ref = QuickJsValueAdapter::new(context, val, false, true, "run_compiled_function result"); if val_ref.is_exception() { let ex_opt = QuickJsRealmAdapter::get_exception(context); if let Some(ex) = ex_opt { Err(ex) } else { Err(JsError::new_str( "run_compiled_function failed and could not get exception", )) } } else { Ok(val_ref) } } /// write a function to bytecode /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::quickjs_utils::compile::{compile, run_compiled_function, to_bytecode, from_bytecode}; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// unsafe { /// let q_ctx = q_js_rt.get_main_realm(); /// let func_res = compile(q_ctx.context, Script::new("test_func.es", "let a = 7; let b = 5; a * b;")); /// let func = func_res.ok().expect("func compile failed"); /// let bytecode: Vec<u8> = to_bytecode(q_ctx.context, &func); /// drop(func); /// assert!(!bytecode.is_empty()); /// let func2_res = from_bytecode(q_ctx.context, &bytecode); /// let func2 = func2_res.ok().expect("could not read bytecode"); /// let run_res = run_compiled_function(q_ctx.context, &func2); /// let res = run_res.ok().expect("run_compiled_function failed"); /// let i_res = primitives::to_i32(&res); /// let i = i_res.ok().expect("could not convert to i32"); /// assert_eq!(i, 7*5); /// } /// }); /// ``` /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn to_bytecode( context: *mut q::JSContext, compiled_func: &QuickJsValueAdapter, ) -> Vec<u8> { assert!(compiled_func.is_compiled_function() || compiled_func.is_module()); let mut len = 0; let slice_u8 = q::JS_WriteObject( context, &mut len, *compiled_func.borrow_value(), q::JS_WRITE_OBJ_BYTECODE as i32, ); let slice = std::slice::from_raw_parts(slice_u8, len as _); // it's a shame to copy the vec here but the alternative is to create a wrapping struct which free's the ptr on drop let ret = slice.to_vec(); q::js_free(context, slice_u8 as *mut c_void); ret } /// read a compiled function from bytecode, see to_bytecode for an example /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn from_bytecode( context: *mut q::JSContext, bytecode: &[u8], ) -> Result<QuickJsValueAdapter, JsError> { assert!(!bytecode.is_empty()); { let len = bytecode.len(); let buf = bytecode.as_ptr(); let raw = q::JS_ReadObject(context, buf, len as _, q::JS_READ_OBJ_BYTECODE as i32); let func_ref = QuickJsValueAdapter::new(context, raw, false, true, "from_bytecode result"); if func_ref.is_exception() { let ex_opt = QuickJsRealmAdapter::get_exception(context); if let Some(ex) = ex_opt { Err(ex) } else { Err(JsError::new_str( "from_bytecode failed and could not get exception", )) } } else { Ok(func_ref) } } } #[cfg(test)] pub mod tests { use crate::builder::QuickJsRuntimeBuilder; use crate::facades::tests::init_test_rt; use crate::jsutils::modules::CompiledModuleLoader; use crate::jsutils::Script; use crate::quickjs_utils::compile::{ compile, from_bytecode, run_compiled_function, to_bytecode, }; use crate::quickjs_utils::modules::compile_module; use crate::quickjs_utils::primitives; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::values::JsValueFacade; //use backtrace::Backtrace; use futures::executor::block_on; use std::panic; use std::sync::Arc; #[test] fn test_compile() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let func_res = unsafe { compile( q_ctx.context, Script::new( "test_func.es", "let a_tb3 = 7; let b_tb3 = 5; a_tb3 * b_tb3;", ), ) }; let func = func_res.expect("func compile failed"); let bytecode: Vec<u8> = unsafe { to_bytecode(q_ctx.context, &func) }; drop(func); assert!(!bytecode.is_empty()); let func2_res = unsafe { from_bytecode(q_ctx.context, &bytecode) }; let func2 = func2_res.expect("could not read bytecode"); let run_res = unsafe { run_compiled_function(q_ctx.context, &func2) }; match run_res { Ok(res) => { let i_res = primitives::to_i32(&res); let i = i_res.expect("could not convert to i32"); assert_eq!(i, 7 * 5); } Err(e) => { panic!("run failed1: {}", e); } } }); } #[test] fn test_bytecode() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| unsafe { let q_ctx = q_js_rt.get_main_realm(); let func_res = compile( q_ctx.context, Script::new( "test_func.es", "let a_tb4 = 7; let b_tb4 = 5; a_tb4 * b_tb4;", ), ); let func = func_res.expect("func compile failed"); let bytecode: Vec<u8> = to_bytecode(q_ctx.context, &func); drop(func); assert!(!bytecode.is_empty()); let func2_res = from_bytecode(q_ctx.context, &bytecode); let func2 = func2_res.expect("could not read bytecode"); let run_res = run_compiled_function(q_ctx.context, &func2); match run_res { Ok(res) => { let i_res = primitives::to_i32(&res); let i = i_res.expect("could not convert to i32"); assert_eq!(i, 7 * 5); } Err(e) => { panic!("run failed: {}", e); } } }); } #[test] fn test_bytecode_bad_compile() { let rt = QuickJsRuntimeBuilder::new().build(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let func_res = unsafe { compile( q_ctx.context, Script::new( "test_func_fail.es", "{the changes of me compil1ng a're slim to 0-0}", ), ) }; func_res.expect_err("func compiled unexpectedly"); }) } #[test] fn test_bytecode_bad_run() { let rt = QuickJsRuntimeBuilder::new().build(); rt.exe_rt_task_in_event_loop(|q_js_rt| unsafe { let q_ctx = q_js_rt.get_main_realm(); let func_res = compile( q_ctx.context, Script::new("test_func_runfail.es", "let abcdef = 1;"), ); let func = func_res.expect("func compile failed"); #[cfg(feature = "bellard")] assert_eq!(1, func.get_ref_count()); let bytecode: Vec<u8> = to_bytecode(q_ctx.context, &func); #[cfg(feature = "bellard")] assert_eq!(1, func.get_ref_count()); drop(func); #[cfg(feature = "bellard")] assert!(!bytecode.is_empty()); let func2_res = from_bytecode(q_ctx.context, &bytecode); let func2 = func2_res.expect("could not read bytecode"); //should fail the second time you run this because abcdef is already defined #[cfg(feature = "bellard")] assert_eq!(1, func2.get_ref_count()); let run_res1 = run_compiled_function(q_ctx.context, &func2).expect("run 1 failed unexpectedly"); drop(run_res1); #[cfg(feature = "bellard")] assert_eq!(1, func2.get_ref_count()); let _run_res2 = run_compiled_function(q_ctx.context, &func2) .expect_err("run 2 succeeded unexpectedly"); #[cfg(feature = "bellard")] assert_eq!(1, func2.get_ref_count()); }); } lazy_static! { static ref COMPILED_BYTES: Arc<Vec<u8>> = init_bytes(); } fn init_bytes() -> Arc<Vec<u8>> { // in order to init our bytes fgor our module we lazy init a rt let rt = QuickJsRuntimeBuilder::new().build(); rt.loop_realm_sync(None, |_rt, realm| unsafe { let script = Script::new( "test_module.js", "export function someFunction(a, b){return a*b;};", ); let module = compile_module(realm.context, script).expect("compile failed"); Arc::new(to_bytecode(realm.context, &module)) }) } struct Cml {} impl CompiledModuleLoader for Cml { fn normalize_path( &self, _q_ctx: &QuickJsRealmAdapter, _ref_path: &str, path: &str, ) -> Option<String> { Some(path.to_string()) } fn load_module(&self, _q_ctx: &QuickJsRealmAdapter, _absolute_path: &str) -> Arc<Vec<u8>> { COMPILED_BYTES.clone() } } #[test] fn test_bytecode_module() { /*panic::set_hook(Box::new(|panic_info| { let backtrace = Backtrace::new(); println!("thread panic occurred: {panic_info}\nbacktrace: {backtrace:?}"); log::error!( "thread panic occurred: {}\nbacktrace: {:?}", panic_info, backtrace ); }));*/ //simple_logging::log_to_file("quickjs_runtime.log", LevelFilter::max()) // .expect("could not init logger"); let rt = QuickJsRuntimeBuilder::new() .compiled_module_loader(Cml {}) .build(); let test_script = Script::new( "test_bytecode_module.js", "import('testcompiledmodule').then((mod) => {return mod.someFunction(3, 5);})", ); let res_fut = rt.eval(None, test_script); let res_prom = block_on(res_fut).expect("script failed"); if let JsValueFacade::JsPromise { cached_promise } = res_prom { let prom_res_fut = cached_promise.get_promise_result(); let prom_res = block_on(prom_res_fut) .expect("prom failed") .expect("prom was rejected"); assert!(prom_res.is_i32()); assert_eq!(prom_res.get_i32(), 15); } else { panic!("did not get a prom"); } } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/modules.rs
src/quickjs_utils/modules.rs
//! utils for working with ES6 Modules use crate::jsutils::{JsError, Script}; use crate::quickjs_utils::atoms; use crate::quickjs_utils::atoms::JSAtomRef; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use core::ptr; use libquickjs_sys as q; use std::ffi::{CStr, CString}; /// compile a module, used for module loading /// # Safety /// please ensure the corresponding QuickJSContext is still valid pub unsafe fn compile_module( context: *mut q::JSContext, script: Script, ) -> Result<QuickJsValueAdapter, JsError> { let code_str = script.get_runnable_code(); let code_c = CString::new(code_str).ok().unwrap(); let filename_c = CString::new(script.get_path()).ok().unwrap(); let value_raw = q::JS_Eval( context, code_c.as_ptr(), code_str.len() as _, filename_c.as_ptr(), (q::JS_EVAL_TYPE_MODULE | q::JS_EVAL_FLAG_COMPILE_ONLY) as i32, ); // check for error let ret = QuickJsValueAdapter::new( context, value_raw, false, true, format!("compile_module result of {}", script.get_path()).as_str(), ); log::trace!("compile module yielded a {}", ret.borrow_value().tag); if ret.is_exception() { let ex_opt = QuickJsRealmAdapter::get_exception(context); if let Some(ex) = ex_opt { Err(ex) } else { Err(JsError::new_str( "compile_module failed and could not get exception", )) } } else { Ok(ret) } } // get the ModuleDef obj from a JSValue, this is used for module loading pub fn get_module_def(value: &QuickJsValueAdapter) -> *mut q::JSModuleDef { log::trace!("get_module_def"); assert!(value.is_module()); log::trace!("get_module_def / 2"); unsafe { value.borrow_value().u.ptr as *mut q::JSModuleDef } } #[allow(dead_code)] pub fn set_module_loader(q_js_rt: &QuickJsRuntimeAdapter) { log::trace!("setting up module loader"); let module_normalize: q::JSModuleNormalizeFunc = Some(js_module_normalize); let module_loader: q::JSModuleLoaderFunc = Some(js_module_loader); let opaque = std::ptr::null_mut(); unsafe { q::JS_SetModuleLoaderFunc(q_js_rt.runtime, module_normalize, module_loader, opaque) } } /// detect if a script is module (contains import or export statements) pub fn detect_module(source: &str) -> bool { // own impl since detectmodule in quickjs-ng is different since 0.7.0 // https://github.com/quickjs-ng/quickjs/issues/767 // Check for static `import` statements #[cfg(feature = "quickjs-ng")] { for line in source.lines() { let trimmed = line.trim(); if trimmed.starts_with("import ") && !trimmed.contains("(") { return true; } if trimmed.starts_with("export ") { return true; } } false } #[cfg(feature = "bellard")] { let cstr = CString::new(source).expect("could not create CString due to null term in source"); let res = unsafe { q::JS_DetectModule(cstr.as_ptr(), source.len() as _) }; //println!("res for {} = {}", source, res); res != 0 } } /// create new Module (JSModuleDef struct) which can be populated with exports after (and from) the init_func /// # Safety /// Please ensure the context passed is still valid pub unsafe fn new_module( ctx: *mut q::JSContext, name: &str, init_func: q::JSModuleInitFunc, ) -> Result<*mut q::JSModuleDef, JsError> { let name_cstr = CString::new(name).map_err(|_e| JsError::new_str("CString failed"))?; Ok(q::JS_NewCModule(ctx, name_cstr.as_ptr(), init_func)) } /// set an export in a JSModuleDef, this should be called AFTER the init_func(as passed to new_module()) is called /// please note that you always need to use this in combination with add_module_export() /// # Safety /// Please ensure the context passed is still valid pub unsafe fn set_module_export( ctx: *mut q::JSContext, module: *mut q::JSModuleDef, export_name: &str, js_val: QuickJsValueAdapter, ) -> Result<(), JsError> { let name_cstr = CString::new(export_name).map_err(|_e| JsError::new_str("CString failed"))?; let res = q::JS_SetModuleExport( ctx, module, name_cstr.as_ptr(), js_val.clone_value_incr_rc(), ); if res == 0 { Ok(()) } else { Err(JsError::new_str("JS_SetModuleExport failed")) } } /// set an export in a JSModuleDef, this should be called BEFORE this init_func(as passed to new_module()) is called /// # Safety /// Please ensure the context passed is still valid pub unsafe fn add_module_export( ctx: *mut q::JSContext, module: *mut q::JSModuleDef, export_name: &str, ) -> Result<(), JsError> { let name_cstr = CString::new(export_name).map_err(|_e| JsError::new_str("CString failed"))?; let res = q::JS_AddModuleExport(ctx, module, name_cstr.as_ptr()); if res == 0 { Ok(()) } else { Err(JsError::new_str("JS_SetModuleExport failed")) } } /// get the name of an JSModuleDef struct /// # Safety /// Please ensure the context passed is still valid pub unsafe fn get_module_name( ctx: *mut q::JSContext, module: *mut q::JSModuleDef, ) -> Result<String, JsError> { let atom_raw = q::JS_GetModuleName(ctx, module); let atom_ref = JSAtomRef::new(ctx, atom_raw); atoms::to_string(ctx, &atom_ref) } unsafe extern "C" fn js_module_normalize( ctx: *mut q::JSContext, module_base_name: *const ::std::os::raw::c_char, module_name: *const ::std::os::raw::c_char, _opaque: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_char { log::trace!("js_module_normalize called."); let base_c = CStr::from_ptr(module_base_name); let base_str = base_c .to_str() .expect("could not convert module_base_name to str"); let name_c = CStr::from_ptr(module_name); let name_str = name_c .to_str() .expect("could not convert module_name to str"); log::trace!( "js_module_normalize called. base: {}. name: {}", base_str, name_str ); QuickJsRuntimeAdapter::do_with(|q_js_rt| { let q_ctx = q_js_rt.get_quickjs_context(ctx); if let Some(res) = q_js_rt.with_all_module_loaders(|loader| { if let Some(normalized_path) = loader.normalize_path(q_ctx, base_str, name_str) { let c_absolute_path = CString::new(normalized_path.as_str()).expect("fail"); Some(c_absolute_path.into_raw()) } else { None } }) { res } else { q_ctx.report_ex(format!("Module {name_str} was not found").as_str()); ptr::null_mut() } }) } unsafe extern "C" fn js_module_loader( ctx: *mut q::JSContext, module_name_raw: *const ::std::os::raw::c_char, _opaque: *mut ::std::os::raw::c_void, ) -> *mut q::JSModuleDef { log::trace!("js_module_loader called."); let module_name_c = CStr::from_ptr(module_name_raw); let module_name = module_name_c.to_str().expect("could not get module name"); log::trace!("js_module_loader called: {}", module_name); QuickJsRuntimeAdapter::do_with(|q_js_rt| { QuickJsRealmAdapter::with_context(ctx, |q_ctx| { if let Some(res) = q_js_rt.with_all_module_loaders(|module_loader| { if module_loader.has_module(q_ctx, module_name) { let mod_val_res = module_loader.load_module(q_ctx, module_name); return match mod_val_res { Ok(mod_val) => Some(mod_val), Err(e) => { let err = format!("Module load failed for {module_name} because of: {e}"); log::error!("{}", err); q_ctx.report_ex(err.as_str()); Some(std::ptr::null_mut()) } }; } None }) { res } else { std::ptr::null_mut() } }) }) } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::Script; use crate::quickjs_utils::modules::detect_module; use crate::values::JsValueFacade; use std::time::Duration; #[test] fn test_native_modules() { let rt = init_test_rt(); let mres = rt.eval_module_sync(None, Script::new( "test.mes", "import {a, b, c} from 'greco://testmodule1';\nconsole.log('testmodule1.a = %s, testmodule1.b = %s, testmodule1.c = %s', a, b, c);", )); match mres { Ok(_module_res) => {} Err(e) => panic!("test_native_modules failed: {}", e), } let res_prom = rt.eval_sync(None, Script::new("test_mod_nat_async.es", "(import('greco://someMod').then((module) => {return {a: module.a, b: module.b, c: module.c};}));")).ok().unwrap(); assert!(res_prom.is_js_promise()); match res_prom { JsValueFacade::JsPromise { cached_promise } => { let res = cached_promise .get_promise_result_sync() .expect("prom timed out"); let obj = res.expect("prom failed"); assert!(obj.is_js_object()); match obj { JsValueFacade::JsObject { cached_object } => { let map = cached_object.get_object_sync().expect("esvf to map failed"); let a = map.get("a").expect("obj did not have a"); assert_eq!(a.get_i32(), 1234); let b = map.get("b").expect("obj did not have b"); assert_eq!(b.get_i32(), 64834); } _ => {} } } _ => {} } } #[test] fn test_detect() { assert!(detect_module("import {} from 'foo.js';")); assert!(detect_module("export function a(){};")); assert!(!detect_module("//hi")); assert!(!detect_module("let a = 1;")); assert!(!detect_module("import('foo.js').then((a) = {});")); } #[test] fn test_module_sandbox() { log::info!("> test_module_sandbox"); let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let res = q_ctx.eval_module(Script::new( "test1.mes", "export const name = 'foobar';\nconsole.log('evalling module');", )); if res.is_err() { panic!("parse module failed: {}", res.err().unwrap()) } res.ok().expect("parse module failed"); }); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let res = q_ctx.eval_module(Script::new( "test2.mes", "import {name} from 'test1.mes';\n\nconsole.log('imported name: ' + name);", )); if res.is_err() { panic!("parse module2 failed: {}", res.err().unwrap()) } res.ok().expect("parse module2 failed"); }); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let res = q_ctx.eval_module(Script::new( "test3.mes", "import {name} from 'notfound.mes';\n\nconsole.log('imported name: ' + name);", )); assert!(res.is_err()); assert!(res .err() .unwrap() .get_message() .contains("Module notfound.mes was not found")); }); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let res = q_ctx.eval_module(Script::new( "test4.mes", "import {name} from 'invalid.mes';\n\nconsole.log('imported name: ' + name);", )); assert!(res.is_err()); assert!(res .err() .unwrap() .get_message() .contains("Module load failed for invalid.mes")); }); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let res = q_ctx.eval_module(Script::new( "test2.mes", "import {name} from 'test1.mes';\n\nconsole.log('imported name: ' + name);", )); if res.is_err() { panic!("parse module2 failed: {}", res.err().unwrap()) } res.ok().expect("parse module2 failed"); }); std::thread::sleep(Duration::from_secs(1)); log::info!("< test_module_sandbox"); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/functions.rs
src/quickjs_utils/functions.rs
//! utils to create and invoke functions use crate::jsutils::JsError; use crate::jsutils::Script; use crate::quickjs_utils::errors::error_to_js_error; use crate::quickjs_utils::{atoms, errors, objects, parse_args, primitives}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::{make_cstring, QuickJsRuntimeAdapter}; use crate::quickjsvalueadapter::QuickJsValueAdapter; use hirofa_utils::auto_id_map::AutoIdMap; use libquickjs_sys as q; use log::trace; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::os::raw::{c_char, c_int, c_void}; use std::rc::Rc; /// parse a function body and its arg_names into a JSValueRef which is a Function /// # Example /// ```dontrun /// use quickjs_runtime::esruntimebuilder::EsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::functions::{parse_function, call_function}; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::JsError::JsError; /// use quickjs_runtime::valueref::JSValueRef; /// let rt = EsRuntimeBuilder::new().build(); /// rt.add_to_event_queue_sync(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_context(); /// let func_res = parse_function(q_ctx.context, false, "my_func", "console.log('running my_func'); return(a * b);", vec!["a", "b"]); /// let func = match func_res { /// Ok(func) => func, /// Err(e) => { /// panic!("could not get func: {}", e); /// } /// }; /// let a = primitives::from_i32(7); /// let b = primitives::from_i32(9); /// let res = call_function(q_ctx.context, &func, vec![a, b], None).ok().unwrap(); /// let res_i32 = primitives::to_i32(&res).ok().unwrap(); /// assert_eq!(res_i32, 63); /// }); /// ``` /// # Safety /// when passing a context ptr please be sure that the corresponding QuickJsContext is still active pub unsafe fn parse_function( context: *mut q::JSContext, async_fn: bool, name: &str, body: &str, arg_names: Vec<&str>, ) -> Result<QuickJsValueAdapter, JsError> { // todo validate argNames // todo validate body let as_pfx = if async_fn { "async " } else { "" }; let args_str = arg_names.join(", "); let src = format!("({as_pfx}function {name}({args_str}) {{\n{body}\n}});"); let file_name = format!("compile_func_{name}.es"); let ret = QuickJsRealmAdapter::eval_ctx(context, Script::new(&file_name, &src), None)?; debug_assert!(is_function(context, &ret)); Ok(ret) } /// call a function pub fn call_function_q_ref_args( q_ctx: &QuickJsRealmAdapter, function_ref: &QuickJsValueAdapter, arguments: &[&QuickJsValueAdapter], this_ref_opt: Option<&QuickJsValueAdapter>, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { call_function_ref_args(q_ctx.context, function_ref, arguments, this_ref_opt) } } /// call a function pub fn call_function_q( q_ctx: &QuickJsRealmAdapter, function_ref: &QuickJsValueAdapter, arguments: &[QuickJsValueAdapter], this_ref_opt: Option<&QuickJsValueAdapter>, ) -> Result<QuickJsValueAdapter, JsError> { let r: Vec<&QuickJsValueAdapter> = arguments.iter().collect(); unsafe { call_function_ref_args(q_ctx.context, function_ref, &r, this_ref_opt) } } /// call a function /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn call_function( context: *mut q::JSContext, function_ref: &QuickJsValueAdapter, arguments: &[QuickJsValueAdapter], this_ref_opt: Option<&QuickJsValueAdapter>, ) -> Result<QuickJsValueAdapter, JsError> { let r: Vec<&QuickJsValueAdapter> = arguments.iter().collect(); call_function_ref_args(context, function_ref, &r, this_ref_opt) } /// call a function /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn call_function_ref_args( context: *mut q::JSContext, function_ref: &QuickJsValueAdapter, arguments: &[&QuickJsValueAdapter], this_ref_opt: Option<&QuickJsValueAdapter>, ) -> Result<QuickJsValueAdapter, JsError> { log::trace!("functions::call_function()"); debug_assert!(is_function(context, function_ref)); let arg_count = arguments.len() as i32; let mut qargs = arguments .iter() .map(|a| *a.borrow_value()) .collect::<Vec<_>>(); let this_val = if let Some(this_ref) = this_ref_opt { *this_ref.borrow_value() } else { crate::quickjs_utils::new_null() }; let res = q::JS_Call( context, *function_ref.borrow_value(), this_val, arg_count, qargs.as_mut_ptr(), ); let res_ref = QuickJsValueAdapter::new(context, res, false, true, "call_function result"); if res_ref.is_exception() { if let Some(ex) = QuickJsRealmAdapter::get_exception(context) { Err(ex) } else { Err(JsError::new_str( "function invocation failed but could not get ex", )) } } else { Ok(res_ref) } } /* pub fn JS_Invoke( ctx: *mut JSContext, this_val: JSValue, atom: JSAtom, argc: ::std::os::raw::c_int, argv: *mut JSValue, ) -> JSValue; */ pub fn invoke_member_function_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, function_name: &str, arguments: &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> { unsafe { invoke_member_function(q_ctx.context, obj_ref, function_name, arguments) } } #[allow(dead_code)] /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn invoke_member_function( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, function_name: &str, arguments: &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> { //let member = get_property(context, obj_ref, function_name)?; //call_function(context, &member, arguments, Some(obj_ref)) let arg_count = arguments.len() as i32; let atom_ref = atoms::from_string(context, function_name)?; atom_ref.increment_ref_ct(); let mut qargs = arguments .iter() .map(|a| *a.borrow_value()) .collect::<Vec<_>>(); let res_val = q::JS_Invoke( context, *obj_ref.borrow_value(), atom_ref.get_atom(), arg_count, qargs.as_mut_ptr(), ); let res_ref = QuickJsValueAdapter::new( context, res_val, false, true, format!("functions::invoke_member_function res: {function_name}").as_str(), ); if res_ref.is_exception() { if let Some(ex) = QuickJsRealmAdapter::get_exception(context) { Err(ex) } else { Err(JsError::new_str( "invoke_member_function failed but could not get ex", )) } } else { Ok(res_ref) } } /// call an objects to_String method or convert a value to string pub fn call_to_string_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter, ) -> Result<String, JsError> { unsafe { call_to_string(q_ctx.context, obj_ref) } } /// call an objects to_String method or convert a value to string /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn call_to_string( context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter, ) -> Result<String, JsError> { if obj_ref.is_string() { primitives::to_string(context, obj_ref) } else if obj_ref.is_null() { Ok("null".to_string()) } else if obj_ref.is_undefined() { Ok("undefined".to_string()) } else if obj_ref.is_i32() { let i = primitives::to_i32(obj_ref).expect("could not get i32"); Ok(i.to_string()) } else if obj_ref.is_f64() { let i = primitives::to_f64(obj_ref).expect("could not get f64"); Ok(i.to_string()) } else if obj_ref.is_bool() { let i = primitives::to_bool(obj_ref).expect("could not get bool"); Ok(i.to_string()) } else if errors::is_error(context, obj_ref) { let pretty_err = error_to_js_error(context, obj_ref); Ok(format!("{pretty_err}")) } else { log::trace!("calling JS_ToString on a {}", obj_ref.borrow_value().tag); // todo better for Errors (plus stack) let res = q::JS_ToString(context, *obj_ref.borrow_value()); let res_ref = QuickJsValueAdapter::new(context, res, false, true, "call_to_string result"); log::trace!("called JS_ToString got a {}", res_ref.borrow_value().tag); if !res_ref.is_string() { return Err(JsError::new_str("Could not convert value to string")); } primitives::to_string(context, &res_ref) } } /// see if an Object is an instance of Function pub fn is_function_q(q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter) -> bool { unsafe { is_function(q_ctx.context, obj_ref) } } #[allow(dead_code)] /// see if an Object is an instance of Function /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn is_function(context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter) -> bool { if obj_ref.is_object() { #[cfg(feature = "bellard")] { let res = q::JS_IsFunction(context, *obj_ref.borrow_value()); res != 0 } #[cfg(feature = "quickjs-ng")] q::JS_IsFunction(context, *obj_ref.borrow_value()) } else { false } } /// see if an Object is an instance of Function and is a constructor (can be instantiated with new keyword) pub fn is_constructor_q(q_ctx: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter) -> bool { unsafe { is_constructor(q_ctx.context, obj_ref) } } /// see if an Object is an instance of Function and is a constructor (can be instantiated with new keyword) /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn is_constructor(context: *mut q::JSContext, obj_ref: &QuickJsValueAdapter) -> bool { if obj_ref.is_object() { #[cfg(feature = "bellard")] { let res = q::JS_IsConstructor(context, *obj_ref.borrow_value()); res != 0 } #[cfg(feature = "quickjs-ng")] q::JS_IsConstructor(context, *obj_ref.borrow_value()) } else { false } } /// call a constructor (instantiate an Object) pub fn call_constructor_q( q_ctx: &QuickJsRealmAdapter, constructor_ref: &QuickJsValueAdapter, arguments: &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> { unsafe { call_constructor(q_ctx.context, constructor_ref, arguments) } } /// call a constructor (instantiate an Object) /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn call_constructor( context: *mut q::JSContext, constructor_ref: &QuickJsValueAdapter, arguments: &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> { //extern "C" { // pub fn JS_CallConstructor( // ctx: *mut JSContext, // func_obj: JSValue, // argc: ::std::os::raw::c_int, // argv: *mut JSValue, // ) -> JSValue; // } let arg_count = arguments.len() as i32; let mut qargs = arguments .iter() .map(|arg| *arg.borrow_value()) .collect::<Vec<_>>(); let ret_val = q::JS_CallConstructor( context, *constructor_ref.borrow_value(), arg_count, qargs.as_mut_ptr(), ); let res_ref = QuickJsValueAdapter::new( context, ret_val, false, true, "functions::call_constructor result", ); if res_ref.is_exception() { if let Some(ex) = QuickJsRealmAdapter::get_exception(context) { Err(ex) } else { Err(JsError::new_str( "call_constructor failed but could not get ex", )) } } else { Ok(res_ref) } } /// create a new Function object which calls a native method pub fn new_native_function_q( q_ctx: &QuickJsRealmAdapter, name: &str, func: q::JSCFunction, arg_count: i32, is_constructor: bool, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_native_function(q_ctx.context, name, func, arg_count, is_constructor) } } /// create a new Function object which calls a native method /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn new_native_function( context: *mut q::JSContext, name: &str, func: q::JSCFunction, arg_count: i32, is_constructor: bool, ) -> Result<QuickJsValueAdapter, JsError> { log::trace!("functions::new_native_function / 0 : {}", name); let cname = make_cstring(name)?; let magic: i32 = 1; log::trace!("functions::new_native_function / 1"); let cproto = if is_constructor { q::JSCFunctionEnum_JS_CFUNC_constructor } else { q::JSCFunctionEnum_JS_CFUNC_generic }; log::trace!("functions::new_native_function / 2"); let func_val = q::JS_NewCFunction2( context, func, cname.as_ptr(), arg_count as c_int, cproto, magic as c_int, ); log::trace!("functions::new_native_function / 3"); let func_ref = QuickJsValueAdapter::new( context, func_val, false, true, format!("functions::new_native_function {name}").as_str(), ); log::trace!("functions::new_native_function / 4"); if !func_ref.is_object() { Err(JsError::new_str("Could not create new_native_function")) } else { Ok(func_ref) } } /// create a new Function object which calls a native method (with data) pub fn new_native_function_data_q( q_ctx: &QuickJsRealmAdapter, func: q::JSCFunctionData, name: &str, arg_count: i32, data: QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_native_function_data(q_ctx.context, func, name, arg_count, data) } } /// create a new Function object which calls a native method (with data) /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn new_native_function_data( context: *mut q::JSContext, func: q::JSCFunctionData, name: &str, arg_count: i32, mut data: QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { let magic = 1; let data_len = 1; let func_val = q::JS_NewCFunctionData( context, func, magic, arg_count as c_int, data_len, data.borrow_value_mut(), ); let func_ref = QuickJsValueAdapter::new( context, func_val, false, true, format!("functions::new_native_function_data {name}").as_str(), ); if !func_ref.is_object() { Err(JsError::new_str("Could not create new_native_function")) } else { let name_ref = primitives::from_string(context, name)?; objects::set_property2(context, &func_ref, "name", &name_ref, 0)?; Ok(func_ref) } } static CNAME: &str = "CallbackClass\0"; type Callback = dyn Fn( *mut q::JSContext, &QuickJsValueAdapter, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> + 'static; thread_local! { static INSTANCE_ID_MAPPINGS: RefCell<HashMap<usize, Box<(usize, String)>>> = RefCell::new(HashMap::new()); #[cfg(feature = "quickjs-ng")] static CALLBACK_EXOTIC: RefCell<q::JSClassExoticMethods> = RefCell::new(q::JSClassExoticMethods { get_own_property: None, get_own_property_names: None, delete_property: None, define_own_property: None, has_property: None, get_property: None, set_property: None, }); #[cfg(feature = "bellard")] static CALLBACK_EXOTIC: RefCell<q::JSClassExoticMethods> = RefCell::new(q::JSClassExoticMethods { get_own_property: None, get_own_property_names: None, delete_property: None, define_own_property: None, has_property: None, get_property: None, set_property: None, get_prototype: None, is_extensible: None, prevent_extensions: None, set_prototype: None }); static CALLBACK_CLASS_DEF: RefCell<q::JSClassDef> = { CALLBACK_EXOTIC.with(|e_rc|{ let exotic = &mut *e_rc.borrow_mut(); RefCell::new(q::JSClassDef { class_name: CNAME.as_ptr() as *const c_char, finalizer: Some(callback_finalizer), gc_mark: None, call: None, exotic, }) }) }; static CALLBACK_CLASS_ID: RefCell<u32> = { let class_id: u32 = QuickJsRuntimeAdapter::do_with(|q_js_rt| { q_js_rt.new_class_id() }); log::trace!("got class id {}", class_id); CALLBACK_CLASS_DEF.with(|cd_rc| { let class_def = &*cd_rc.borrow(); QuickJsRuntimeAdapter::do_with(|q_js_rt| { let res = unsafe { q::JS_NewClass(q_js_rt.runtime, class_id, class_def) }; log::trace!("callback: new class res {}", res); // todo res should be 0 for ok }); }); RefCell::new(class_id) }; pub static CALLBACK_REGISTRY: RefCell<AutoIdMap<(String, Rc<Callback>)>> = { RefCell::new(AutoIdMap::new_with_max_size(i32::MAX as usize)) }; pub static CALLBACK_IDS: RefCell<HashSet<Box<i32>>> = RefCell::new(HashSet::new()); } pub(crate) fn init_statics() { CALLBACK_CLASS_ID.with(|_rc| { // }); } /// create a new Function which is backed by a closure /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::jsutils::Script; /// use quickjs_runtime::quickjs_utils::functions::new_function_q; /// use quickjs_runtime::quickjs_utils::primitives::from_i32; /// use quickjs_runtime::quickjs_utils::get_global_q; /// use quickjs_runtime::quickjs_utils::objects::set_property_q; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// // create a function which always returns 1253 /// let func_obj = new_function_q(q_ctx, "myFunc7654", |_q_ctx, _this, _args|{Ok(from_i32(1253))}, 0).ok().unwrap(); /// // store as a global member so script can call it /// let global = get_global_q(q_ctx); /// set_property_q(q_ctx, &global, "myFunc7654", &func_obj).expect("set prop failed /// "); /// }); /// rt.eval_sync(None, Script::new("new_function_q.es", "let a = myFunc7654(); if (a !== 1253) {throw Error('a was not 1253')}")).ok().expect("script failed"); /// ``` pub fn new_function_q<F>( q_ctx: &QuickJsRealmAdapter, name: &str, func: F, arg_count: u32, ) -> Result<QuickJsValueAdapter, JsError> where F: Fn( &QuickJsRealmAdapter, &QuickJsValueAdapter, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> + 'static, { let func_raw = move |ctx: *mut q::JSContext, this: &QuickJsValueAdapter, args: &[QuickJsValueAdapter]| { log::trace!("new_function_q outer"); QuickJsRuntimeAdapter::do_with(|q_js_rt| { log::trace!("new_function_q inner"); func(unsafe { q_js_rt.get_quickjs_context(ctx) }, this, args) }) }; unsafe { new_function(q_ctx.context, name, func_raw, arg_count) } } /// create a new Function which is backed by a closure /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn new_function<F>( context: *mut q::JSContext, name: &str, func: F, arg_count: u32, ) -> Result<QuickJsValueAdapter, JsError> where F: Fn( *mut q::JSContext, &QuickJsValueAdapter, &[QuickJsValueAdapter], ) -> Result<QuickJsValueAdapter, JsError> + 'static, { // put func in map, retrieve on call.. delete on destroy // create a new class_def for callbacks, with a finalize // use setproto to bind class to function // use autoidmap to store callbacks and generate ID's // create function with newCFunctionData and put id in data let callback_id = CALLBACK_REGISTRY.with(|registry_rc| { let registry = &mut *registry_rc.borrow_mut(); registry.insert((name.to_string(), Rc::new(func))) }); log::trace!("new_function callback_id = {}", callback_id); let data = primitives::from_i32(callback_id as i32); let func_ref = new_native_function_data( context, Some(callback_function), name, arg_count as i32, data, )?; let callback_class_id = CALLBACK_CLASS_ID.with(|rc| *rc.borrow()); let class_val: q::JSValue = q::JS_NewObjectClass(context, callback_class_id as _); let class_val_ref = QuickJsValueAdapter::new( context, class_val, false, true, "functions::new_function class_val", ); if class_val_ref.is_exception() { return if let Some(e) = QuickJsRealmAdapter::get_exception(context) { Err(e) } else { Err(JsError::new_str("could not create callback class")) }; } CALLBACK_IDS.with(|rc| { let ids = &mut *rc.borrow_mut(); let mut bx = Box::new(callback_id as i32); let ibp: &mut i32 = &mut bx; let info_ptr = ibp as *mut _ as *mut c_void; q::JS_SetOpaque(*class_val_ref.borrow_value(), info_ptr); ids.insert(bx); }); objects::set_property2(context, &func_ref, "_cb_fin_marker_", &class_val_ref, 0) .expect("could not set cb marker"); Ok(func_ref) } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::quickjs_utils::functions::{ call_function_q, call_to_string_q, invoke_member_function_q, new_function_q, }; use crate::quickjs_utils::{functions, objects, primitives}; use crate::jsutils::{JsError, Script}; use std::time::Duration; #[test] pub fn test_invoke() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let obj_ref = q_ctx .eval(Script::new( "test_to_invoke.es", "({func: function(a, b) {return a*b}});", )) .expect("test_to_invoke.es failed"); let res = invoke_member_function_q( q_ctx, &obj_ref, "func", &[primitives::from_i32(12), primitives::from_i32(14)], ) .expect("func failed"); q_js_rt.gc(); log::info!("invoke_res = {}", res.get_tag()); assert!(res.is_i32()); assert_eq!(primitives::to_i32(&res).expect("wtf?"), (12 * 14)); }); rt.gc_sync(); } #[test] pub fn test_ret_refcount() { let rt = init_test_rt(); let io = rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let func_ref = q_ctx .eval(Script::new( "test_ret_refcount.es", "this.test = {q: {}}; let global = this; (function(a, b){global.test.a = a; return {a: 1};});", )) .expect("aa"); #[cfg(feature = "bellard")] assert_eq!(func_ref.get_ref_count(), 1); let a = objects::create_object_q(q_ctx).ok().unwrap(); let b = objects::create_object_q(q_ctx).ok().unwrap(); #[cfg(feature = "bellard")] assert_eq!(1, a.get_ref_count()); #[cfg(feature = "bellard")] assert_eq!(1, b.get_ref_count()); let i_res = call_function_q(q_ctx, &func_ref, &[a.clone(), b.clone()], None) .expect("a"); assert!(i_res.is_object()); #[cfg(feature = "bellard")] assert_eq!(i_res.get_ref_count(), 1); #[cfg(feature = "bellard")] assert_eq!(2, a.get_ref_count()); #[cfg(feature = "bellard")] assert_eq!(1, b.get_ref_count()); let q_ref = q_ctx.eval(Script::new("test_ret_refcount2.es", "test.q;")).expect("get q failed"); #[cfg(feature = "bellard")] assert_eq!(2, q_ref.get_ref_count()); let _ = call_function_q(q_ctx, &func_ref, &[primitives::from_i32(123), q_ref], None) .expect("b"); let q_ref = q_ctx.eval(Script::new("test_ret_refcount2.es", "test.q;")).expect("get q failed"); #[cfg(feature = "bellard")] assert_eq!(2, q_ref.get_ref_count()); let _ = call_function_q(q_ctx, &func_ref, &[q_ref, primitives::from_i32(123)], None) .expect("b"); let _q_ref = q_ctx.eval(Script::new("test_ret_refcount2.es", "test.q;")).expect("get q failed"); #[cfg(feature = "bellard")] assert_eq!(3, _q_ref.get_ref_count()); // cleanup q_ctx.eval(Script::new("cleanup.es", "this.test = null;")).ok().unwrap(); true }); assert!(io); rt.gc_sync(); } #[test] pub fn test_to_string() { let rt = init_test_rt(); let io = rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let i = primitives::from_i32(480); let i_s = call_to_string_q(q_ctx, &i) .ok() .expect("to_string failed on i"); assert_eq!(i_s.as_str(), "480"); let b = primitives::from_bool(true); let b_s = call_to_string_q(q_ctx, &b) .ok() .expect("to_string failed on b"); assert_eq!(b_s.as_str(), "true"); true }); assert!(io); rt.gc_sync(); } #[test] pub fn test_call() { let rt = init_test_rt(); let io = rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let func_ref = q_ctx .eval(Script::new( "test_call.es", "(function(a, b){return ((a || 7)*(b || 7));});", )) .ok() .expect("could not get func obj"); let res = call_function_q( q_ctx, &func_ref, &[primitives::from_i32(8), primitives::from_i32(6)], None, ); if res.is_err() { panic!("test_call failed: {}", res.err().unwrap()); } let res_val = res.ok().unwrap(); q_js_rt.gc(); assert!(res_val.is_i32()); assert_eq!(primitives::to_i32(&res_val).ok().unwrap(), 6 * 8); true }); assert!(io) } #[test] fn test_callback() { let rt = init_test_rt(); rt.eval_sync(None, Script::new("test_callback1.es", "let test_callback_563 = function(cb){console.log('before invoke cb');let result = cb(1, true, 'foobar');console.log('after invoke cb. got:' + result);};")).ok().expect("script failed"); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let mut cb_ref = new_function_q( q_ctx, "cb", |_q_ctx, _this_ref, _args| { log::trace!("native callback invoked"); Ok(primitives::from_i32(983)) }, 3, ) .ok() .expect("could not create function"); #[cfg(feature = "bellard")] assert_eq!(1, cb_ref.get_ref_count()); cb_ref.label("cb_ref at test_callback"); let func_ref = q_ctx .eval(Script::new("", "(test_callback_563);")) .ok() .expect("could not get function"); #[cfg(feature = "bellard")] assert_eq!(2, func_ref.get_ref_count()); let res = call_function_q(q_ctx, &func_ref, &[cb_ref], None); if res.is_err() { let err = res.err().unwrap(); log::error!("could not invoke test_callback_563: {}", err); panic!("could not invoke test_callback_563: {}", err); } res.expect("could not invoke test_callback_563"); }); log::trace!("done with cb"); rt.gc_sync(); std::thread::sleep(Duration::from_secs(1)); } #[test] fn test_callback_arg_ref_ct() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let func_ref = q_ctx.eval(Script::new( "test_callback845.es", "let test_callback_845 = function(cb){let obj = {}; cb(obj);cb(obj);cb(obj);}; test_callback_845;", )) .expect("script failed"); let cb_ref = new_function_q( q_ctx, "cb", |_q_ctx, _this_ref, _args| { log::trace!("native callback invoked"); #[cfg(feature = "bellard")] assert_eq!(_args[0].get_ref_count(), 3); Ok(primitives::from_i32(983)) }, 3, ) .expect("could not create function"); log::debug!("calling js func test_callback_845"); let res = functions::call_function_q(q_ctx, &func_ref, &[cb_ref], None); if res.is_err() { let e = format!("test_callback_845 failed: {}", res.err().unwrap()); log::error!("{}", e); panic!("{}", e); } }); log::trace!("done with cb"); std::thread::sleep(Duration::from_secs(1)); rt.exe_rt_task_in_event_loop(|q_js_rt| { q_js_rt.gc(); }); std::thread::sleep(Duration::from_secs(1)); } #[test] fn test_ex() { let rt = init_test_rt(); let err = rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); q_ctx .install_function( &["test_927"], "testMe", |_rt, _q_ctx, _this_ref, _args| { log::trace!("native callback invoked"); Err(JsError::new_str("poof")) }, 0, ) .expect("could not install func"); let err = q_ctx .eval(Script::new( "test_927.es", "console.log('foo');test_927.testMe();", )) .expect_err("did not get err"); format!("{err}") }); assert!(err.contains("[testMe]")); assert!(err.contains("test_927.es")); } } unsafe extern "C" fn callback_finalizer(_rt: *mut q::JSRuntime, val: q::JSValue) { trace!("callback_finalizer called"); let callback_class_id = CALLBACK_CLASS_ID.with(|rc| *rc.borrow()); let info_ptr: *mut c_void = q::JS_GetOpaque(val, callback_class_id); let callback_id: i32 = *(info_ptr as *mut i32); trace!("callback_finalizer called, id={}", callback_id); let _ = CALLBACK_IDS.try_with(|rc| { let ids = &mut *rc.borrow_mut(); ids.remove(&callback_id); }); let _ = CALLBACK_REGISTRY.try_with(|rc| { let registry = &mut *rc.borrow_mut(); let rid = callback_id as usize; trace!("callback_finalizer remove id={}", rid); let _ = registry.remove(&rid); }); } unsafe extern "C" fn callback_function( ctx: *mut q::JSContext, this_val: q::JSValue, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, _magic: ::std::os::raw::c_int, func_data: *mut q::JSValue, ) -> q::JSValue { trace!("callback_function called"); // todo run multiple times and check refcount not growing for data, this and args
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
true
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/json.rs
src/quickjs_utils/json.rs
//! serialize and stringify JavaScript objects use crate::jsutils::JsError; use crate::quickjs_utils; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; use std::ffi::CString; /// Parse a JSON string into an Object /// please note that JSON.parse requires member names to be enclosed in double quotes /// so {a: 1} and {'a': 1} will both fail /// {"a": 1} will parse ok /// # Example /// ```dontrun /// use quickjs_runtime::esruntimebuilder::EsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::{json, objects, primitives}; /// use quickjs_runtime::quickjs_utils::json::parse; /// let rt = EsRuntimeBuilder::new().build(); /// rt.add_to_event_queue_sync(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_context(); /// let parse_res = json::parse_q(q_ctx, "{\"aaa\": 165}"); /// if parse_res.is_err() { /// panic!("could not parse: {}", parse_res.err().unwrap()); /// } /// let obj_ref = parse_res.ok().unwrap(); /// let a_ref = objects::get_property(q_ctx.context, &obj_ref, "aaa").ok().unwrap(); /// let i = primitives::to_i32(&a_ref).ok().unwrap(); /// assert_eq!(165, i); /// }); /// rt.gc_sync(); /// ``` pub fn parse_q(q_ctx: &QuickJsRealmAdapter, input: &str) -> Result<QuickJsValueAdapter, JsError> { unsafe { parse(q_ctx.context, input) } } /// Parse a JSON string into an Object /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn parse( context: *mut q::JSContext, input: &str, ) -> Result<QuickJsValueAdapter, JsError> { let s = CString::new(input).ok().unwrap(); let f_n = CString::new("JSON.parse").ok().unwrap(); let len = input.len(); let val = q::JS_ParseJSON(context, s.as_ptr(), len as _, f_n.as_ptr()); let ret = QuickJsValueAdapter::new(context, val, false, true, "json::parse result"); if ret.is_exception() { if let Some(ex) = QuickJsRealmAdapter::get_exception(context) { Err(ex) } else { Err(JsError::new_str("unknown error while parsing json")) } } else { Ok(ret) } } /// Stringify an Object in script /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::{json, objects, primitives}; /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let obj_ref = objects::create_object_q(q_ctx).ok().unwrap(); /// objects::set_property_q(q_ctx, &obj_ref, "a", &primitives::from_i32(741)).ok().unwrap(); /// let str_ref = json::stringify_q(q_ctx, &obj_ref, None).ok().unwrap(); /// let str_str = primitives::to_string_q(q_ctx, &str_ref).ok().unwrap(); /// assert_eq!("{\"a\":741}", str_str); /// }); /// rt.gc_sync(); /// ``` pub fn stringify_q( q_ctx: &QuickJsRealmAdapter, input: &QuickJsValueAdapter, opt_space: Option<QuickJsValueAdapter>, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { stringify(q_ctx.context, input, opt_space) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn stringify( context: *mut q::JSContext, input: &QuickJsValueAdapter, opt_space: Option<QuickJsValueAdapter>, ) -> Result<QuickJsValueAdapter, JsError> { //pub fn JS_JSONStringify( // ctx: *mut JSContext, // obj: JSValue, // replacer: JSValue, // space0: JSValue, // ) -> JSValue; let space_ref = match opt_space { None => quickjs_utils::new_null_ref(), Some(s) => s, }; let val = q::JS_JSONStringify( context, *input.borrow_value(), quickjs_utils::new_null(), *space_ref.borrow_value(), ); let ret = QuickJsValueAdapter::new(context, val, false, true, "json::stringify result"); if ret.is_exception() { if let Some(ex) = QuickJsRealmAdapter::get_exception(context) { Err(ex) } else { Err(JsError::new_str("unknown error in json::stringify")) } } else { Ok(ret) } } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::Script; use crate::quickjs_utils::json::parse_q; use crate::quickjs_utils::{get_global_q, json, objects, primitives}; use crate::values::JsValueFacade; use std::collections::HashMap; #[test] fn test_json() { let rt = init_test_rt(); log::info!("Starting json test"); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let obj = objects::create_object_q(q_ctx).ok().unwrap(); objects::set_property_q(q_ctx, &obj, "a", &primitives::from_i32(532)) .ok() .unwrap(); objects::set_property_q(q_ctx, &obj, "b", &primitives::from_bool(true)) .ok() .unwrap(); objects::set_property_q( q_ctx, &obj, "c", &primitives::from_string_q(q_ctx, "abcdË").ok().unwrap(), ) .ok() .unwrap(); let str_res = json::stringify_q(q_ctx, &obj, None).ok().unwrap(); #[cfg(feature = "bellard")] assert_eq!(str_res.get_ref_count(), 1); let json = str_res.to_string().ok().unwrap(); assert_eq!(json, "{\"a\":532,\"b\":true,\"c\":\"abcdË\"}"); let obj2 = parse_q(q_ctx, json.as_str()).ok().unwrap(); let prop_c = objects::get_property_q(q_ctx, &obj2, "c").ok().unwrap(); assert_eq!("abcdË", prop_c.to_string().ok().unwrap()); }); } #[tokio::test] async fn test_json_arg() { let rt = init_test_rt(); // init my javascript function rt.eval( None, Script::new( "myFunc.js", r#" function myFunction(argObj) { console.log("I got an %s", typeof argObj); console.log("It looks like this %s", argObj); return "hello " + argObj["key"]; } "#, ), ) .await .ok() .expect("myFunc failed to parse"); // parse my obj to json let mut my_json_deserable_object = HashMap::new(); my_json_deserable_object.insert("key", "value"); let json = serde_json::to_string(&my_json_deserable_object) .ok() .expect("serializing failed"); let func_res = rt .loop_realm(None, move |_rt, realm| { // this runs in the worker thread for the EventLoop so json String needs to be moved here // now we parse the json to a JsValueRef let js_obj = parse_q(realm, json.as_str()) .ok() .expect("parsing json failed"); // then we can invoke the function with that js_obj as input // get the global obj as function container let global = get_global_q(realm); // invoke the function let func_res = crate::quickjs_utils::functions::invoke_member_function_q( realm, &global, "myFunction", &[js_obj], ); //return the value out of the worker thread as JsValueFacade realm.to_js_value_facade(&func_res.ok().expect("func failed")) }) .await; let jsv = func_res.ok().expect("got err"); assert_eq!(jsv.stringify(), "String: hello value"); } #[tokio::test] async fn test_json_arg2() { let rt = init_test_rt(); // init my javascript function rt.eval( None, Script::new( "myFunc.js", r#" function myFunction(argObj) { console.log("I got an %s", typeof argObj); console.log("It looks like this %s", argObj); return "hello " + argObj["key"]; } "#, ), ) .await .ok() .expect("myFunc failed to parse"); // parse my obj to json let mut my_json_deserable_object = HashMap::new(); my_json_deserable_object.insert("key", "value"); let json = serde_json::to_string(&my_json_deserable_object) .ok() .expect("serializing failed"); let json_js_value_facade = JsValueFacade::JsonStr { json }; let func_res = rt .invoke_function(None, &[], "myFunction", vec![json_js_value_facade]) .await; let jsv = func_res.ok().expect("got err"); assert_eq!(jsv.stringify(), "String: hello value"); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/primitives.rs
src/quickjs_utils/primitives.rs
use crate::jsutils::JsError; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use core::ptr; use libquickjs_sys as q; use std::os::raw::c_char; pub fn to_bool(value_ref: &QuickJsValueAdapter) -> Result<bool, JsError> { if value_ref.is_bool() { let r = value_ref.borrow_value(); let raw = unsafe { r.u.int32 }; let val: bool = raw > 0; Ok(val) } else { Err(JsError::new_str("value is not a boolean")) } } pub fn from_bool(b: bool) -> QuickJsValueAdapter { let raw = unsafe { q::JS_NewBool(ptr::null_mut(), b) }; QuickJsValueAdapter::new_no_context(raw, "primitives::from_bool") } pub fn to_f64(value_ref: &QuickJsValueAdapter) -> Result<f64, JsError> { if value_ref.is_f64() { let r = value_ref.borrow_value(); let val = unsafe { r.u.float64 }; Ok(val) } else { Err(JsError::new_str("value was not a float64")) } } pub fn from_f64(f: f64) -> QuickJsValueAdapter { #[cfg(feature = "bellard")] let raw = unsafe { q::JS_NewFloat64(ptr::null_mut(), f) }; #[cfg(feature = "quickjs-ng")] let raw = unsafe { q::JS_NewNumber(ptr::null_mut(), f) }; QuickJsValueAdapter::new_no_context(raw, "primitives::from_f64") } pub fn to_i32(value_ref: &QuickJsValueAdapter) -> Result<i32, JsError> { if value_ref.is_i32() { let r = value_ref.borrow_value(); let val: i32 = unsafe { r.u.int32 }; Ok(val) } else { Err(JsError::new_str("val is not an int")) } } pub fn from_i32(i: i32) -> QuickJsValueAdapter { let raw = unsafe { q::JS_NewInt32(ptr::null_mut(), i) }; QuickJsValueAdapter::new_no_context(raw, "primitives::from_i32") } pub fn to_string_q( q_ctx: &QuickJsRealmAdapter, value_ref: &QuickJsValueAdapter, ) -> Result<String, JsError> { unsafe { to_string(q_ctx.context, value_ref) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn to_string( context: *mut q::JSContext, value_ref: &QuickJsValueAdapter, ) -> Result<String, JsError> { //log::trace!("primitives::to_string on {}", value_ref.borrow_value().tag); assert!(value_ref.is_string()); let mut len = 0; #[cfg(feature = "bellard")] let ptr: *const c_char = q::JS_ToCStringLen2(context, &mut len, *value_ref.borrow_value(), 0); #[cfg(feature = "quickjs-ng")] let ptr: *const c_char = q::JS_ToCStringLen2(context, &mut len, *value_ref.borrow_value(), false); if len == 0 { return Ok("".to_string()); } if ptr.is_null() { return Err(JsError::new_str( "Could not convert string: got a null pointer", )); } let bytes = std::slice::from_raw_parts(ptr as *const u8, len); // Convert to String (validate UTF-8). let s = String::from_utf8_lossy(bytes).into_owned(); // Free the c string. q::JS_FreeCString(context, ptr); Ok(s) } pub fn from_string_q(q_ctx: &QuickJsRealmAdapter, s: &str) -> Result<QuickJsValueAdapter, JsError> { unsafe { from_string(q_ctx.context, s) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn from_string( context: *mut q::JSContext, s: &str, ) -> Result<QuickJsValueAdapter, JsError> { let qval = q::JS_NewStringLen(context, s.as_ptr() as *const c_char, s.len() as _); let ret = QuickJsValueAdapter::new(context, qval, false, true, "primitives::from_string qval"); if ret.is_exception() { return Err(JsError::new_str("Could not create string in runtime")); } Ok(ret) } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::Script; #[tokio::test] async fn test_emoji() { let rt = init_test_rt(); let res = rt.eval(None, Script::new("testEmoji.js", "'hi'")).await; match res { Ok(fac) => { assert_eq!(fac.get_str(), "hi"); } Err(e) => { panic!("script failed: {}", e); } } let res = rt.eval(None, Script::new("testEmoji.js", "'👍'")).await; match res { Ok(fac) => { assert_eq!(fac.get_str(), "👍"); } Err(e) => { panic!("script failed: {}", e); } } let res = rt.eval(None, Script::new("testEmoji.js", "'pre👍'")).await; match res { Ok(fac) => { assert_eq!(fac.get_str(), "pre👍"); } Err(e) => { panic!("script failed: {}", e); } } let res = rt.eval(None, Script::new("testEmoji.js", "'👍post'")).await; match res { Ok(fac) => { assert_eq!(fac.get_str(), "👍post"); } Err(e) => { panic!("script failed: {}", e); } } let res = rt .eval(None, Script::new("testEmoji.js", "'pre👍post'")) .await; match res { Ok(fac) => { assert_eq!(fac.get_str(), "pre👍post"); } Err(e) => { panic!("script failed: {}", e); } } let res = rt .eval( None, Script::new("testEmoji.js", "JSON.stringify({c: '👍'})"), ) .await; match res { Ok(fac) => { assert_eq!(fac.get_str(), "{\"c\":\"👍\"}"); } Err(e) => { panic!("script failed: {}", e); } } } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/atoms.rs
src/quickjs_utils/atoms.rs
//JS_AtomToCString(ctx: *mut JSContext, atom: JSAtom) -> *const ::std::os::raw::c_char use crate::jsutils::JsError; use crate::quickjs_utils::primitives; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; use std::ffi::CString; #[allow(clippy::upper_case_acronyms)] pub struct JSAtomRef { context: *mut q::JSContext, atom: q::JSAtom, } impl JSAtomRef { pub fn new(context: *mut q::JSContext, atom: q::JSAtom) -> Self { Self { context, atom } } pub(crate) fn get_atom(&self) -> q::JSAtom { self.atom } pub(crate) fn increment_ref_ct(&self) { unsafe { q::JS_DupAtom(self.context, self.atom) }; } pub(crate) fn decrement_ref_ct(&self) { unsafe { q::JS_FreeAtom(self.context, self.atom) }; } } impl Drop for JSAtomRef { fn drop(&mut self) { // free self.decrement_ref_ct(); } } pub fn to_string_q(q_ctx: &QuickJsRealmAdapter, atom_ref: &JSAtomRef) -> Result<String, JsError> { unsafe { to_string(q_ctx.context, atom_ref) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn to_string( context: *mut q::JSContext, atom_ref: &JSAtomRef, ) -> Result<String, JsError> { let val = q::JS_AtomToString(context, atom_ref.atom); let val_ref = QuickJsValueAdapter::new(context, val, false, true, "atoms::to_string"); primitives::to_string(context, &val_ref) } pub fn to_string2_q(q_ctx: &QuickJsRealmAdapter, atom: &q::JSAtom) -> Result<String, JsError> { unsafe { to_string2(q_ctx.context, atom) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn to_string2(context: *mut q::JSContext, atom: &q::JSAtom) -> Result<String, JsError> { let val = q::JS_AtomToString(context, *atom); let val_ref = QuickJsValueAdapter::new(context, val, false, true, "atoms::to_string"); primitives::to_string(context, &val_ref) } pub fn from_string_q(q_ctx: &QuickJsRealmAdapter, string: &str) -> Result<JSAtomRef, JsError> { unsafe { from_string(q_ctx.context, string) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn from_string(context: *mut q::JSContext, string: &str) -> Result<JSAtomRef, JsError> { let s = CString::new(string).ok().unwrap(); let len = string.len(); let atom = q::JS_NewAtomLen(context, s.as_ptr(), len as _); Ok(JSAtomRef::new(context, atom)) }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/iterators.rs
src/quickjs_utils/iterators.rs
//! utils for the iterator protocol use crate::jsutils::JsError; use crate::quickjs_utils::{functions, objects, primitives}; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; /// iterate over an object conforming to the [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) protocol /// # Safety /// please ensure that the QuickjsContext corresponding to the passed JSContext is still valid pub unsafe fn iterate<C: Fn(QuickJsValueAdapter) -> Result<R, JsError>, R>( ctx: *mut q::JSContext, iterator_ref: &QuickJsValueAdapter, consumer_producer: C, ) -> Result<Vec<R>, JsError> { let mut res = vec![]; loop { let next_obj = functions::invoke_member_function(ctx, iterator_ref, "next", &[])?; if primitives::to_bool(&objects::get_property(ctx, &next_obj, "done")?)? { break; } else { let next_item = objects::get_property(ctx, &next_obj, "value")?; res.push(consumer_producer(next_item)?); } } Ok(res) }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/runtime.rs
src/quickjs_utils/runtime.rs
use libquickjs_sys as q; /// create new class id /// # Safety /// make sure the runtime param is from a live JsRuntimeAdapter instance pub unsafe fn new_class_id(_runtime: *mut q::JSRuntime) -> u32 { let mut c_id: u32 = 0; #[cfg(feature = "bellard")] let class_id: u32 = q::JS_NewClassID(&mut c_id); #[cfg(feature = "quickjs-ng")] let class_id: u32 = q::JS_NewClassID(_runtime, &mut c_id); log::trace!("got class id {}", class_id); class_id }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/mod.rs
src/quickjs_utils/mod.rs
//! low level contains utils for calling the quickjs api use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; #[cfg(feature = "bellard")] pub mod class_ids { pub const JS_CLASS_OBJECT: u32 = 1; pub const JS_CLASS_ARRAY: u32 = 2; pub const JS_CLASS_ERROR: u32 = 3; pub const JS_CLASS_NUMBER: u32 = 4; pub const JS_CLASS_STRING: u32 = 5; pub const JS_CLASS_BOOLEAN: u32 = 6; pub const JS_CLASS_SYMBOL: u32 = 7; pub const JS_CLASS_ARGUMENTS: u32 = 8; pub const JS_CLASS_MAPPED_ARGUMENTS: u32 = 9; pub const JS_CLASS_DATE: u32 = 10; pub const JS_CLASS_MODULE_NS: u32 = 11; pub const JS_CLASS_C_FUNCTION: u32 = 12; pub const JS_CLASS_BYTECODE_FUNCTION: u32 = 13; pub const JS_CLASS_BOUND_FUNCTION: u32 = 14; pub const JS_CLASS_C_FUNCTION_DATA: u32 = 15; pub const JS_CLASS_GENERATOR_FUNCTION: u32 = 16; pub const JS_CLASS_FOR_IN_ITERATOR: u32 = 17; pub const JS_CLASS_REGEXP: u32 = 18; pub const JS_CLASS_ARRAY_BUFFER: u32 = 19; pub const JS_CLASS_SHARED_ARRAY_BUFFER: u32 = 20; pub const JS_CLASS_UINT8C_ARRAY: u32 = 21; pub const JS_CLASS_INT8_ARRAY: u32 = 22; pub const JS_CLASS_UINT8_ARRAY: u32 = 23; pub const JS_CLASS_INT16_ARRAY: u32 = 24; pub const JS_CLASS_UINT16_ARRAY: u32 = 25; pub const JS_CLASS_INT32_ARRAY: u32 = 26; pub const JS_CLASS_UINT32_ARRAY: u32 = 27; pub const JS_CLASS_BIG_INT64_ARRAY: u32 = 28; pub const JS_CLASS_BIG_UINT64_ARRAY: u32 = 29; pub const JS_CLASS_FLOAT16_ARRAY: u32 = 30; pub const JS_CLASS_FLOAT32_ARRAY: u32 = 31; pub const JS_CLASS_FLOAT64_ARRAY: u32 = 32; pub const JS_CLASS_DATAVIEW: u32 = 33; pub const JS_CLASS_BIG_INT: u32 = 34; pub const JS_CLASS_MAP: u32 = 35; pub const JS_CLASS_SET: u32 = 36; pub const JS_CLASS_WEAKMAP: u32 = 37; pub const JS_CLASS_WEAKSET: u32 = 38; pub const JS_CLASS_MAP_ITERATOR: u32 = 39; pub const JS_CLASS_SET_ITERATOR: u32 = 40; pub const JS_CLASS_ARRAY_ITERATOR: u32 = 41; pub const JS_CLASS_STRING_ITERATOR: u32 = 42; pub const JS_CLASS_REGEXP_STRING_ITERATOR: u32 = 43; pub const JS_CLASS_GENERATOR: u32 = 44; pub const JS_CLASS_PROXY: u32 = 45; pub const JS_CLASS_PROMISE: u32 = 46; pub const JS_CLASS_PROMISE_RESOLVE_FUNCTION: u32 = 47; pub const JS_CLASS_PROMISE_REJECT_FUNCTION: u32 = 48; pub const JS_CLASS_ASYNC_FUNCTION: u32 = 49; pub const JS_CLASS_ASYNC_FUNCTION_RESOLVE: u32 = 50; pub const JS_CLASS_ASYNC_FUNCTION_REJECT: u32 = 51; pub const JS_CLASS_ASYNC_FROM_SYNC_ITERATOR: u32 = 52; pub const JS_CLASS_ASYNC_GENERATOR_FUNCTION: u32 = 53; pub const JS_CLASS_ASYNC_GENERATOR: u32 = 54; pub const JS_CLASS_WEAK_REF: u32 = 55; pub const JS_CLASS_FINALIZATION_REGISTRY: u32 = 56; pub const JS_CLASS_INIT_COUNT: u32 = 57; } #[cfg(feature = "quickjs-ng")] pub mod class_ids { pub const JS_CLASS_OBJECT: u32 = 1; pub const JS_CLASS_ARRAY: u32 = 2; pub const JS_CLASS_ERROR: u32 = 3; pub const JS_CLASS_NUMBER: u32 = 4; pub const JS_CLASS_STRING: u32 = 5; pub const JS_CLASS_BOOLEAN: u32 = 6; pub const JS_CLASS_SYMBOL: u32 = 7; pub const JS_CLASS_ARGUMENTS: u32 = 8; pub const JS_CLASS_MAPPED_ARGUMENTS: u32 = 9; pub const JS_CLASS_DATE: u32 = 10; pub const JS_CLASS_MODULE_NS: u32 = 11; pub const JS_CLASS_C_FUNCTION: u32 = 12; pub const JS_CLASS_BYTECODE_FUNCTION: u32 = 13; pub const JS_CLASS_BOUND_FUNCTION: u32 = 14; pub const JS_CLASS_C_FUNCTION_DATA: u32 = 15; pub const JS_CLASS_GENERATOR_FUNCTION: u32 = 16; pub const JS_CLASS_FOR_IN_ITERATOR: u32 = 17; pub const JS_CLASS_REGEXP: u32 = 18; pub const JS_CLASS_ARRAY_BUFFER: u32 = 19; pub const JS_CLASS_SHARED_ARRAY_BUFFER: u32 = 20; pub const JS_CLASS_UINT8C_ARRAY: u32 = 21; pub const JS_CLASS_INT8_ARRAY: u32 = 22; pub const JS_CLASS_UINT8_ARRAY: u32 = 23; pub const JS_CLASS_INT16_ARRAY: u32 = 24; pub const JS_CLASS_UINT16_ARRAY: u32 = 25; pub const JS_CLASS_INT32_ARRAY: u32 = 26; pub const JS_CLASS_UINT32_ARRAY: u32 = 27; pub const JS_CLASS_BIG_INT64_ARRAY: u32 = 28; pub const JS_CLASS_BIG_UINT64_ARRAY: u32 = 29; pub const JS_CLASS_FLOAT16_ARRAY: u32 = 30; pub const JS_CLASS_FLOAT32_ARRAY: u32 = 31; pub const JS_CLASS_FLOAT64_ARRAY: u32 = 32; pub const JS_CLASS_DATAVIEW: u32 = 33; pub const JS_CLASS_BIG_INT: u32 = 34; pub const JS_CLASS_MAP: u32 = 35; pub const JS_CLASS_SET: u32 = 36; pub const JS_CLASS_WEAKMAP: u32 = 37; pub const JS_CLASS_WEAKSET: u32 = 38; pub const JS_CLASS_ITERATOR: u32 = 39; pub const JS_CLASS_ITERATOR_HELPER: u32 = 40; pub const JS_CLASS_ITERATOR_WRAP: u32 = 41; pub const JS_CLASS_MAP_ITERATOR: u32 = 42; pub const JS_CLASS_SET_ITERATOR: u32 = 43; pub const JS_CLASS_ARRAY_ITERATOR: u32 = 44; pub const JS_CLASS_STRING_ITERATOR: u32 = 45; pub const JS_CLASS_REGEXP_STRING_ITERATOR: u32 = 46; pub const JS_CLASS_GENERATOR: u32 = 47; pub const JS_CLASS_PROXY: u32 = 48; pub const JS_CLASS_PROMISE: u32 = 49; pub const JS_CLASS_PROMISE_RESOLVE_FUNCTION: u32 = 50; pub const JS_CLASS_PROMISE_REJECT_FUNCTION: u32 = 51; pub const JS_CLASS_ASYNC_FUNCTION: u32 = 52; pub const JS_CLASS_ASYNC_FUNCTION_RESOLVE: u32 = 53; pub const JS_CLASS_ASYNC_FUNCTION_REJECT: u32 = 54; pub const JS_CLASS_ASYNC_FROM_SYNC_ITERATOR: u32 = 55; pub const JS_CLASS_ASYNC_GENERATOR_FUNCTION: u32 = 56; pub const JS_CLASS_ASYNC_GENERATOR: u32 = 57; pub const JS_CLASS_WEAK_REF: u32 = 58; pub const JS_CLASS_FINALIZATION_REGISTRY: u32 = 59; pub const JS_CLASS_CALL_SITE: u32 = 60; pub const JS_CLASS_INIT_COUNT: u32 = 61; } pub mod arrays; pub mod atoms; pub mod bigints; pub mod compile; pub mod dates; pub mod errors; pub mod functions; pub mod interrupthandler; pub mod iterators; pub mod json; pub mod maps; pub mod modules; pub mod objects; pub mod primitives; pub mod promises; pub mod properties; pub mod runtime; pub mod sets; pub mod typedarrays; use crate::jsutils::JsError; use crate::quickjs_utils::atoms::JSAtomRef; use crate::quickjs_utils::objects::get_property; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::{QuickJsValueAdapter, TAG_NULL, TAG_UNDEFINED}; use libquickjs_sys as q; // todo // runtime and context in thread_local here // all function (where applicable) get an Option<QuickJSRuntime> which if None will be gotten from the thread_local // every function which returns a q::JSValue will return a OwnedValueRef to ensure values are freed on drop pub fn gc(q_js_rt: &QuickJsRuntimeAdapter) { log::trace!("GC called"); unsafe { q::JS_RunGC(q_js_rt.runtime) } log::trace!("GC done"); } pub fn new_undefined_ref() -> QuickJsValueAdapter { QuickJsValueAdapter::new_no_context(new_undefined(), "new_undefined_ref") } pub fn new_null() -> q::JSValue { q::JSValue { u: q::JSValueUnion { int32: 0 }, tag: TAG_NULL, } } pub fn new_undefined() -> q::JSValue { q::JSValue { u: q::JSValueUnion { int32: 0 }, tag: TAG_UNDEFINED, } } pub fn new_null_ref() -> QuickJsValueAdapter { QuickJsValueAdapter::new_no_context(new_null(), "null_ref") } /// get the current filename pub fn get_script_or_module_name_q(ctx: &QuickJsRealmAdapter) -> Result<String, JsError> { unsafe { get_script_or_module_name(ctx.context) } } /// get the current filename /// # Safety /// ensure the QuickJsContext has not been dropped pub unsafe fn get_script_or_module_name(context: *mut q::JSContext) -> Result<String, JsError> { for x in 0..100 { let atom = q::JS_GetScriptOrModuleName(context, x); let atom_ref = JSAtomRef::new(context, atom); let r = atoms::to_string(context, &atom_ref)?; if !r.is_empty() { return Ok(r); } } Ok("".to_string()) } pub fn get_global_q(context: &QuickJsRealmAdapter) -> QuickJsValueAdapter { unsafe { get_global(context.context) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_global(context: *mut q::JSContext) -> QuickJsValueAdapter { let global = q::JS_GetGlobalObject(context); QuickJsValueAdapter::new(context, global, false, true, "global") } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn get_constructor( context: *mut q::JSContext, constructor_name: &str, ) -> Result<QuickJsValueAdapter, JsError> { let global_ref = get_global(context); let constructor_ref = get_property(context, &global_ref, constructor_name)?; if constructor_ref.is_null_or_undefined() { Err(JsError::new_string(format!( "not found: {constructor_name}" ))) } else { Ok(constructor_ref) } } /// Calculate a runtimes memory usage /// # Safety /// runtime ref should be a valid existing runtime pub unsafe fn get_memory_usage(runtime: *mut q::JSRuntime) -> q::JSMemoryUsage { let mut mu = q::JSMemoryUsage { malloc_size: 0, malloc_limit: 0, memory_used_size: 0, malloc_count: 0, memory_used_count: 0, atom_count: 0, atom_size: 0, str_count: 0, str_size: 0, obj_count: 0, obj_size: 0, prop_count: 0, prop_size: 0, shape_count: 0, shape_size: 0, js_func_count: 0, js_func_size: 0, js_func_code_size: 0, js_func_pc2line_count: 0, js_func_pc2line_size: 0, c_func_count: 0, array_count: 0, fast_array_count: 0, fast_array_elements: 0, binary_object_count: 0, binary_object_size: 0, }; q::JS_ComputeMemoryUsage(runtime, &mut mu); mu } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn parse_args( context: *mut q::JSContext, argc: ::std::os::raw::c_int, argv: *mut q::JSValue, ) -> Vec<QuickJsValueAdapter> { let arg_slice = std::slice::from_raw_parts(argv, argc as usize); arg_slice .iter() .map(|raw| QuickJsValueAdapter::new(context, *raw, true, true, "quickjs_utils::parse_args")) .collect::<Vec<_>>() } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::Script; use crate::quickjs_utils::{get_global_q, get_script_or_module_name_q}; use crate::values::JsValueConvertable; #[test] fn test_global() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); #[cfg(feature = "bellard")] let ct = get_global_q(q_ctx).get_ref_count(); for _ in 0..5 { let _global = get_global_q(q_ctx); #[cfg(feature = "bellard")] assert_eq!(_global.get_ref_count(), ct); } }); } #[test] fn test_script_name() { let rt = init_test_rt(); rt.set_function(&[], "testName", |q_ctx, _args| { let res = get_script_or_module_name_q(q_ctx)?.to_js_value_facade(); Ok(res) }) .ok() .expect("func set failed"); let name_esvf = rt .eval_sync( None, Script::new("the_name.es", "(function(){return(testName());}())"), ) .ok() .expect("script failed"); assert_eq!(name_esvf.get_str(), "the_name.es"); let name_esvf = rt .eval_sync( None, Script::new("https://githubstuff.org/tes.js", "(testName())"), ) .ok() .expect("script failed"); assert_eq!(name_esvf.get_str(), "https://githubstuff.org/tes.js"); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/bigints.rs
src/quickjs_utils/bigints.rs
use crate::jsutils::JsError; use crate::quickjs_utils; use crate::quickjs_utils::{functions, primitives}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; #[cfg(feature = "bellard")] use crate::quickjsvalueadapter::TAG_BIG_INT; use libquickjs_sys as q; pub fn new_bigint_i64_q( context: &QuickJsRealmAdapter, int: i64, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_bigint_i64(context.context, int) } } pub fn new_bigint_u64_q( context: &QuickJsRealmAdapter, int: u64, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_bigint_u64(context.context, int) } } #[allow(dead_code)] /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn new_bigint_i64( context: *mut q::JSContext, int: i64, ) -> Result<QuickJsValueAdapter, JsError> { let res_val = q::JS_NewBigInt64(context, int); let ret = QuickJsValueAdapter::new(context, res_val, false, true, "new_bigint_i64"); #[cfg(feature = "bellard")] { #[cfg(debug_assertions)] if ret.get_tag() == TAG_BIG_INT { assert_eq!(ret.get_ref_count(), 1); } } Ok(ret) } #[allow(dead_code)] /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn new_bigint_u64( context: *mut q::JSContext, int: u64, ) -> Result<QuickJsValueAdapter, JsError> { let res_val = q::JS_NewBigUint64(context, int); let ret = QuickJsValueAdapter::new(context, res_val, false, true, "new_bigint_u64"); #[cfg(feature = "bellard")] { #[cfg(debug_assertions)] if ret.get_tag() == TAG_BIG_INT { assert_eq!(ret.get_ref_count(), 1); } } Ok(ret) } pub fn new_bigint_str_q( context: &QuickJsRealmAdapter, input_str: &str, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_bigint_str(context.context, input_str) } } #[allow(dead_code)] /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn new_bigint_str( context: *mut q::JSContext, input_str: &str, ) -> Result<QuickJsValueAdapter, JsError> { let global_ref = quickjs_utils::get_global(context); let str_ref = primitives::from_string(context, input_str)?; let bigint_ref = functions::invoke_member_function(context, &global_ref, "BigInt", &[str_ref])?; let ret = bigint_ref; #[cfg(feature = "bellard")] assert_eq!(ret.get_ref_count(), 1); Ok(ret) } pub fn to_string_q( context: &QuickJsRealmAdapter, big_int_ref: &QuickJsValueAdapter, ) -> Result<String, JsError> { unsafe { to_string(context.context, big_int_ref) } } #[allow(dead_code)] /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn to_string( context: *mut q::JSContext, big_int_ref: &QuickJsValueAdapter, ) -> Result<String, JsError> { if !big_int_ref.is_big_int() { return Err(JsError::new_str("big_int_ref was not a big_int")); } functions::call_to_string(context, big_int_ref) } #[cfg(test)] pub mod tests { use crate::facades::tests::init_test_rt; use crate::jsutils::Script; use crate::quickjs_utils::bigints; use crate::quickjs_utils::bigints::new_bigint_str_q; #[test] fn test_bigint() { let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let res = q_ctx .eval(Script::new("createABigInt.js", "BigInt(1234567890)")) .expect("script failed"); log::info!( "script bi was {} {}", res.get_tag(), res.to_string().expect("could not toString") ); let bi_ref = bigints::new_bigint_u64_q(q_ctx, 659863456456) .expect("could not create bigint from u64"); unsafe { if let Some(e) = crate::quickjs_utils::errors::get_exception(q_ctx.context) { log::error!("ex: {}", e); } } let to_str = bigints::to_string_q(q_ctx, &bi_ref).expect("could not tostring bigint"); assert_eq!(to_str, "659863456456"); let bi_ref = bigints::new_bigint_i64_q(q_ctx, 659863456457) .expect("could not create bigint from u64"); let to_str = bigints::to_string_q(q_ctx, &bi_ref).expect("could not tostring bigint"); assert_eq!(to_str, "659863456457"); let bi_ref = new_bigint_str_q(q_ctx, "345346345645234564536345345345345456534783448567") .expect("could not create bigint from str"); log::debug!("bi_ref.get_js_type is {}", bi_ref.get_js_type()); let to_str = bigints::to_string_q(q_ctx, &bi_ref).expect("could not tostring bigint"); assert_eq!(to_str, "345346345645234564536345345345345456534783448567"); }); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/promises.rs
src/quickjs_utils/promises.rs
use crate::jsutils::JsError; use crate::quickjs_utils; #[cfg(feature = "bellard")] use crate::quickjs_utils::class_ids::JS_CLASS_PROMISE; use crate::quickjs_utils::errors::get_stack; use crate::quickjs_utils::functions; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; #[cfg(feature = "bellard")] use libquickjs_sys::JS_GetClassID; #[cfg(feature = "quickjs-ng")] use libquickjs_sys::JS_IsPromise; pub fn is_promise_q(context: &QuickJsRealmAdapter, obj_ref: &QuickJsValueAdapter) -> bool { unsafe { is_promise(context.context, obj_ref) } } #[allow(dead_code)] /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid #[allow(unused_variables)] pub unsafe fn is_promise(ctx: *mut q::JSContext, obj: &QuickJsValueAdapter) -> bool { #[cfg(feature = "bellard")] { JS_GetClassID(*obj.borrow_value()) == JS_CLASS_PROMISE } #[cfg(feature = "quickjs-ng")] { JS_IsPromise(*obj.borrow_value()) } } pub struct QuickJsPromiseAdapter { promise_obj_ref: QuickJsValueAdapter, reject_function_obj_ref: QuickJsValueAdapter, resolve_function_obj_ref: QuickJsValueAdapter, } #[allow(dead_code)] impl QuickJsPromiseAdapter { pub fn get_promise_obj_ref(&self) -> QuickJsValueAdapter { self.promise_obj_ref.clone() } pub fn resolve_q( &self, q_ctx: &QuickJsRealmAdapter, value: QuickJsValueAdapter, ) -> Result<(), JsError> { unsafe { self.resolve(q_ctx.context, value) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn resolve( &self, context: *mut q::JSContext, value: QuickJsValueAdapter, ) -> Result<(), JsError> { log::trace!("PromiseRef.resolve()"); crate::quickjs_utils::functions::call_function( context, &self.resolve_function_obj_ref, &[value], None, )?; Ok(()) } pub fn reject_q( &self, q_ctx: &QuickJsRealmAdapter, value: QuickJsValueAdapter, ) -> Result<(), JsError> { unsafe { self.reject(q_ctx.context, value) } } /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn reject( &self, context: *mut q::JSContext, value: QuickJsValueAdapter, ) -> Result<(), JsError> { log::trace!("PromiseRef.reject()"); crate::quickjs_utils::functions::call_function( context, &self.reject_function_obj_ref, &[value], None, )?; Ok(()) } } impl Clone for QuickJsPromiseAdapter { fn clone(&self) -> Self { Self { promise_obj_ref: self.promise_obj_ref.clone(), reject_function_obj_ref: self.reject_function_obj_ref.clone(), resolve_function_obj_ref: self.resolve_function_obj_ref.clone(), } } } impl QuickJsPromiseAdapter { pub fn js_promise_resolve( &self, context: &QuickJsRealmAdapter, resolution: &QuickJsValueAdapter, ) -> Result<(), JsError> { self.resolve_q(context, resolution.clone()) } pub fn js_promise_reject( &self, context: &QuickJsRealmAdapter, rejection: &QuickJsValueAdapter, ) -> Result<(), JsError> { self.reject_q(context, rejection.clone()) } pub fn js_promise_get_value(&self, _realm: &QuickJsRealmAdapter) -> QuickJsValueAdapter { self.promise_obj_ref.clone() } } pub fn new_promise_q(q_ctx: &QuickJsRealmAdapter) -> Result<QuickJsPromiseAdapter, JsError> { unsafe { new_promise(q_ctx.context) } } /// create a new Promise /// you can use this to respond asynchronously to method calls from JavaScript by returning a Promise /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn new_promise(context: *mut q::JSContext) -> Result<QuickJsPromiseAdapter, JsError> { log::trace!("promises::new_promise()"); let mut promise_resolution_functions = [quickjs_utils::new_null(), quickjs_utils::new_null()]; let prom_val = q::JS_NewPromiseCapability(context, promise_resolution_functions.as_mut_ptr()); let resolve_func_val = *promise_resolution_functions.first().unwrap(); let reject_func_val = *promise_resolution_functions.get(1).unwrap(); let resolve_function_obj_ref = QuickJsValueAdapter::new( context, resolve_func_val, false, true, "promises::new_promise resolve_func_val", ); let reject_function_obj_ref = QuickJsValueAdapter::new( context, reject_func_val, false, true, "promises::new_promise reject_func_val", ); debug_assert!(functions::is_function(context, &resolve_function_obj_ref)); debug_assert!(functions::is_function(context, &reject_function_obj_ref)); let promise_obj_ref = QuickJsValueAdapter::new( context, prom_val, false, true, "promises::new_promise prom_val", ); #[cfg(feature = "bellard")] debug_assert_eq!(resolve_function_obj_ref.get_ref_count(), 1); #[cfg(feature = "bellard")] debug_assert_eq!(reject_function_obj_ref.get_ref_count(), 1); #[cfg(feature = "bellard")] debug_assert_eq!(promise_obj_ref.get_ref_count(), 3); Ok(QuickJsPromiseAdapter { promise_obj_ref, reject_function_obj_ref, resolve_function_obj_ref, }) } pub(crate) fn init_promise_rejection_tracker(q_js_rt: &QuickJsRuntimeAdapter) { let tracker: q::JSHostPromiseRejectionTracker = Some(promise_rejection_tracker); unsafe { q::JS_SetHostPromiseRejectionTracker(q_js_rt.runtime, tracker, std::ptr::null_mut()); } } pub fn add_promise_reactions_q( context: &QuickJsRealmAdapter, promise_obj_ref: &QuickJsValueAdapter, then_func_obj_ref_opt: Option<QuickJsValueAdapter>, catch_func_obj_ref_opt: Option<QuickJsValueAdapter>, finally_func_obj_ref_opt: Option<QuickJsValueAdapter>, ) -> Result<(), JsError> { unsafe { add_promise_reactions( context.context, promise_obj_ref, then_func_obj_ref_opt, catch_func_obj_ref_opt, finally_func_obj_ref_opt, ) } } #[allow(dead_code)] /// # Safety /// When passing a context pointer please make sure the corresponding QuickJsContext is still valid pub unsafe fn add_promise_reactions( context: *mut q::JSContext, promise_obj_ref: &QuickJsValueAdapter, then_func_obj_ref_opt: Option<QuickJsValueAdapter>, catch_func_obj_ref_opt: Option<QuickJsValueAdapter>, finally_func_obj_ref_opt: Option<QuickJsValueAdapter>, ) -> Result<(), JsError> { debug_assert!(is_promise(context, promise_obj_ref)); if let Some(then_func_obj_ref) = then_func_obj_ref_opt { functions::invoke_member_function(context, promise_obj_ref, "then", &[then_func_obj_ref])?; } if let Some(catch_func_obj_ref) = catch_func_obj_ref_opt { functions::invoke_member_function( context, promise_obj_ref, "catch", &[catch_func_obj_ref], )?; } if let Some(finally_func_obj_ref) = finally_func_obj_ref_opt { functions::invoke_member_function( context, promise_obj_ref, "finally", &[finally_func_obj_ref], )?; } Ok(()) } unsafe extern "C" fn promise_rejection_tracker( ctx: *mut q::JSContext, _promise: q::JSValue, reason: q::JSValue, #[cfg(feature = "bellard")] is_handled: ::std::os::raw::c_int, #[cfg(feature = "quickjs-ng")] is_handled: bool, _opaque: *mut ::std::os::raw::c_void, ) { #[cfg(feature = "bellard")] let handled = is_handled != 0; #[cfg(feature = "quickjs-ng")] let handled = is_handled; if !handled { let reason_ref = QuickJsValueAdapter::new( ctx, reason, false, false, "promises::promise_rejection_tracker reason", ); let reason_str_res = functions::call_to_string(ctx, &reason_ref); QuickJsRuntimeAdapter::do_with(|rt| { let realm = rt.get_quickjs_context(ctx); let realm_id = realm.get_realm_id(); let stack = match get_stack(realm) { Ok(s) => match s.to_string() { Ok(s) => s, Err(_) => "".to_string(), }, Err(_) => "".to_string(), }; #[cfg(feature = "typescript")] let stack = crate::typescript::unmap_stack_trace(stack.as_str()); match reason_str_res { Ok(reason_str) => { log::error!( "[{}] unhandled promise rejection, reason: {}\nRejection stack:\n{}", realm_id, reason_str, stack ); } Err(e) => { log::error!( "[{}] unhandled promise rejection, could not get reason: {}\nRejection stack:\n{}", realm_id, e, stack ); } } }); } } #[cfg(test)] pub mod tests { use crate::builder::QuickJsRuntimeBuilder; use crate::facades::tests::init_test_rt; use crate::jsutils::Script; use crate::quickjs_utils::promises::{add_promise_reactions_q, is_promise_q, new_promise_q}; use crate::quickjs_utils::{functions, new_null_ref, primitives}; use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use crate::values::JsValueFacade; use futures::executor::block_on; use std::time::Duration; #[test] fn test_instance_of_prom() { log::info!("> test_instance_of_prom"); let rt = init_test_rt(); let io = rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let res = q_ctx.eval(Script::new( "test_instance_of_prom.es", "(new Promise((res, rej) => {}));", )); match res { Ok(v) => { log::info!("checking if instance_of prom"); is_promise_q(q_ctx, &v) && is_promise_q(q_ctx, &v) && is_promise_q(q_ctx, &v) && is_promise_q(q_ctx, &v) && is_promise_q(q_ctx, &v) } Err(e) => { log::error!("err testing instance_of prom: {}", e); false } } }); assert!(io); log::info!("< test_instance_of_prom"); std::thread::sleep(Duration::from_secs(1)); } #[test] fn new_prom() { log::info!("> new_prom"); let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let func_ref = q_ctx .eval(Script::new( "new_prom.es", "(function(p){p.then((res) => {console.log('prom resolved to ' + res);});});", )) .ok() .unwrap(); let prom = new_promise_q(q_ctx).ok().unwrap(); let res = functions::call_function_q(q_ctx, &func_ref, &[prom.get_promise_obj_ref()], None); if res.is_err() { panic!("func call failed: {}", res.err().unwrap()); } unsafe { prom.resolve(q_ctx.context, primitives::from_i32(743)) .expect("resolve failed"); } }); std::thread::sleep(Duration::from_secs(1)); log::info!("< new_prom"); } #[test] fn new_prom2() { log::info!("> new_prom2"); let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let func_ref = q_ctx .eval(Script::new( "new_prom.es", "(function(p){p.catch((res) => {console.log('prom rejected to ' + res);});});", )) .ok() .unwrap(); let prom = new_promise_q(q_ctx).ok().unwrap(); let res = functions::call_function_q(q_ctx, &func_ref, &[prom.get_promise_obj_ref()], None); if res.is_err() { panic!("func call failed: {}", res.err().unwrap()); } unsafe { prom.reject(q_ctx.context, primitives::from_i32(130)) .expect("reject failed"); } }); std::thread::sleep(Duration::from_secs(1)); log::info!("< new_prom2"); } #[test] fn test_promise_reactions() { log::info!("> test_promise_reactions"); let rt = init_test_rt(); rt.exe_rt_task_in_event_loop(|q_js_rt| { let q_ctx = q_js_rt.get_main_realm(); let prom_ref = q_ctx .eval(Script::new( "test_promise_reactions.es", "(new Promise(function(resolve, reject) {resolve(364);}));", )) .expect("script failed"); let then_cb = functions::new_function_q( q_ctx, "testThen", |_q_ctx, _this, args| { let res = primitives::to_i32(args.first().unwrap()).ok().unwrap(); log::trace!("prom resolved with: {}", res); Ok(new_null_ref()) }, 1, ) .expect("could not create cb"); let finally_cb = functions::new_function_q( q_ctx, "testThen", |_q_ctx, _this, _args| { log::trace!("prom finalized"); Ok(new_null_ref()) }, 1, ) .expect("could not create cb"); add_promise_reactions_q(q_ctx, &prom_ref, Some(then_cb), None, Some(finally_cb)) .expect("could not add promise reactions"); }); std::thread::sleep(Duration::from_secs(1)); log::info!("< test_promise_reactions"); } #[tokio::test] async fn test_promise_async() { let rt = init_test_rt(); let jsvf = rt .eval( None, Script::new("test_prom_async.js", "Promise.resolve(123)"), ) .await .expect("script failed"); if let JsValueFacade::JsPromise { cached_promise } = jsvf { let res = cached_promise .get_promise_result() .await .expect("promise resolve send code stuf exploded"); match res { Ok(prom_res) => { if prom_res.is_i32() { assert_eq!(prom_res.get_i32(), 123); } else { panic!("promise did not resolve to an i32.. well that was unexpected!"); } } Err(e) => { panic!("prom was rejected: {}", e.stringify()) } } } } #[test] fn test_promise_nested() { log::info!("> test_promise_nested"); let rt = init_test_rt(); let mut jsvf_res = rt.exe_task_in_event_loop(|| { QuickJsRuntimeAdapter::create_context("test").expect("create ctx failed"); QuickJsRuntimeAdapter::do_with(|q_js_rt| { let q_ctx = q_js_rt.get_context("test"); let script = "(new Promise((resolve, reject) => {resolve({a: 7});}).then((obj) => {return {b: obj.a * 5}}));"; let esvf_res = q_ctx .eval(Script::new("test_promise_nested.es", script)) .expect("script failed"); q_ctx.to_js_value_facade(&esvf_res).expect("poof") }) }); while jsvf_res.is_js_promise() { match jsvf_res { JsValueFacade::JsPromise { cached_promise } => { jsvf_res = cached_promise .get_promise_result_sync() .expect("prom timed out") .expect("prom was rejected"); } _ => {} } } assert!(jsvf_res.is_js_object()); match jsvf_res { JsValueFacade::JsObject { cached_object } => { let obj = cached_object.get_object_sync().expect("esvf to map failed"); let b = obj.get("b").expect("got no b"); assert!(b.is_i32()); let i = b.get_i32(); assert_eq!(i, 5 * 7); } _ => {} } rt.exe_task_in_event_loop(|| { let _ = QuickJsRuntimeAdapter::remove_context("test"); }) } #[test] fn test_to_string_err() { let rt = QuickJsRuntimeBuilder::new().build(); let res = block_on(rt.eval( None, Script::new( "test_test_to_string_err.js", r#" (async () => { throw Error("poof"); })(); "#, ), )); match res { Ok(val) => { if let JsValueFacade::JsPromise { cached_promise } = val { let prom_res = block_on(cached_promise.get_promise_result()).expect("promise timed out"); match prom_res { Ok(v) => { panic!("promise unexpectedly resolved to val: {:?}", v); } Err(ev) => { println!("prom resolved to error: {ev:?}"); } } } else { panic!("func did not return a promise"); } } Err(e) => { panic!("scrtip failed {}", e) } } } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/interrupthandler.rs
src/quickjs_utils/interrupthandler.rs
use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter; use libquickjs_sys as q; use std::ffi::c_void; use std::os::raw::c_int; // /// set an interrupt handler for the runtime /// # Safety /// be safe pub unsafe fn set_interrupt_handler(runtime: *mut q::JSRuntime, handler: q::JSInterruptHandler) { q::JS_SetInterruptHandler(runtime, handler, std::ptr::null_mut()); } pub(crate) fn init(q_js_rt: &QuickJsRuntimeAdapter) { unsafe { set_interrupt_handler(q_js_rt.runtime, Some(interrupt_handler)) }; } unsafe extern "C" fn interrupt_handler(_rt: *mut q::JSRuntime, _opaque: *mut c_void) -> c_int { QuickJsRuntimeAdapter::do_with(|q_js_rt| { let handler = q_js_rt.interrupt_handler.as_ref().unwrap(); i32::from(handler(q_js_rt)) }) } #[cfg(test)] pub mod tests { use crate::builder::QuickJsRuntimeBuilder; use crate::jsutils::Script; use crate::quickjs_utils::get_script_or_module_name_q; use std::cell::RefCell; use std::panic; use std::sync::{Arc, Mutex}; #[test] fn test_interrupt_handler() { log::info!("interrupt_handler test"); let called = Arc::new(Mutex::new(RefCell::new(false))); let called2 = called.clone(); /*panic::set_hook(Box::new(|panic_info| { let backtrace = Backtrace::new(); println!("thread panic occurred: {panic_info}\nbacktrace: {backtrace:?}"); log::error!( "thread panic occurred: {}\nbacktrace: {:?}", panic_info, backtrace ); }));*/ //simple_logging::log_to_file("esruntime.log", LevelFilter::max()) // .expect("could not init logger"); let rt = QuickJsRuntimeBuilder::new() .set_interrupt_handler(move |qjs_rt| { log::debug!("interrupt_handler called / 1"); let script_name = get_script_or_module_name_q(qjs_rt.get_main_realm()); match script_name { Ok(script_name) => { log::debug!("interrupt_handler called: {}", script_name); } Err(_) => { log::debug!("interrupt_handler called"); } } let lck = called2.lock().unwrap(); *lck.borrow_mut() = true; false }) .build(); match rt.eval_sync( None, Script::new( "test_interrupt.es", "for (let x = 0; x < 10000; x++) {console.log('x' + x);}", ), ) { Ok(_) => {} Err(err) => { panic!("err: {}", err); } } rt.create_context("newctx").expect("ctx crea failed"); rt.exe_rt_task_in_event_loop(|q_js_rt| { let ctx = q_js_rt.get_context("newctx"); match ctx.eval(Script::new( "test_interrupt.es", "for (let x = 0; x < 10000; x++) {console.log('x' + x);}", )) { Ok(_) => {} Err(err) => { panic!("err: {}", err); } } }); let lck = called.lock().unwrap(); assert!(*lck.borrow()); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/maps.rs
src/quickjs_utils/maps.rs
//! Map utils, these methods can be used to manage Map objects from rust //! see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) for more on Maps use crate::jsutils::JsError; #[cfg(feature = "bellard")] use crate::quickjs_utils::class_ids::JS_CLASS_MAP; use crate::quickjs_utils::objects::construct_object; use crate::quickjs_utils::{arrays, functions, get_constructor, iterators, objects, primitives}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; #[cfg(feature = "bellard")] use libquickjs_sys::JS_GetClassID; #[cfg(feature = "quickjs-ng")] use libquickjs_sys::JS_IsMap; /// create new instance of Map /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::new_map_q; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// }); /// ``` pub fn new_map_q(q_ctx: &QuickJsRealmAdapter) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_map(q_ctx.context) } } /// create new instance of Map /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn new_map(ctx: *mut q::JSContext) -> Result<QuickJsValueAdapter, JsError> { let map_constructor = get_constructor(ctx, "Map")?; construct_object(ctx, &map_constructor, &[]) } /// see if a JSValueRef is an instance of Map pub fn is_map_q(q_ctx: &QuickJsRealmAdapter, obj: &QuickJsValueAdapter) -> bool { unsafe { is_map(q_ctx.context, obj) } } /// see if a JSValueRef is an instance of Map /// # Safety /// please ensure the passed JSContext is still valid #[allow(unused_variables)] pub unsafe fn is_map(ctx: *mut q::JSContext, obj: &QuickJsValueAdapter) -> bool { #[cfg(feature = "bellard")] { JS_GetClassID(*obj.borrow_value()) == JS_CLASS_MAP } #[cfg(feature = "quickjs-ng")] { JS_IsMap(*obj.borrow_value()) } } /// set a key/value pair in a Map /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::{new_map_q, set_q}; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// let key = primitives::from_i32(12); /// let value = primitives::from_i32(23); /// set_q(q_ctx, &my_map, key, value).ok().unwrap(); /// }); /// ``` pub fn set_q( q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter, key: QuickJsValueAdapter, val: QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { set(q_ctx.context, map, key, val) } } /// set a key/value pair in a Map /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn set( ctx: *mut q::JSContext, map: &QuickJsValueAdapter, key: QuickJsValueAdapter, val: QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { functions::invoke_member_function(ctx, map, "set", &[key, val]) } /// get a value from a map by key /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::{new_map_q, get_q, set_q}; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// let key = primitives::from_i32(12); /// let value = primitives::from_i32(23); /// set_q(q_ctx, &my_map, key.clone(), value).ok().unwrap(); /// let val_res = get_q(q_ctx, &my_map, key).ok().unwrap(); /// assert_eq!(primitives::to_i32(&val_res).ok().unwrap(), 23); /// }); /// ``` pub fn get_q( q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter, key: QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { get(q_ctx.context, map, key) } } /// get a value from a map by key /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn get( ctx: *mut q::JSContext, map: &QuickJsValueAdapter, key: QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { functions::invoke_member_function(ctx, map, "get", &[key]) } /// delete a value from a map by key /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::{new_map_q, set_q, delete_q}; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// let key = primitives::from_i32(12); /// let value = primitives::from_i32(23); /// set_q(q_ctx, &my_map, key.clone(), value).ok().unwrap(); /// delete_q(q_ctx, &my_map, key).ok().unwrap(); /// }); /// ``` pub fn delete_q( q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter, key: QuickJsValueAdapter, ) -> Result<bool, JsError> { unsafe { delete(q_ctx.context, map, key) } } /// delete a value from a map by key /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn delete( ctx: *mut q::JSContext, map: &QuickJsValueAdapter, key: QuickJsValueAdapter, ) -> Result<bool, JsError> { let res = functions::invoke_member_function(ctx, map, "delete", &[key])?; primitives::to_bool(&res) } /// check whether a Map has a value for a key /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::{new_map_q, set_q, has_q}; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// let key = primitives::from_i32(12); /// let value = primitives::from_i32(23); /// set_q(q_ctx, &my_map, key.clone(), value).ok().unwrap(); /// let bln_has = has_q(q_ctx, &my_map, key).ok().unwrap(); /// assert!(bln_has); /// }); /// ``` pub fn has_q( q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter, key: QuickJsValueAdapter, ) -> Result<bool, JsError> { unsafe { has(q_ctx.context, map, key) } } /// check whether a Map has a value for a key /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn has( ctx: *mut q::JSContext, map: &QuickJsValueAdapter, key: QuickJsValueAdapter, ) -> Result<bool, JsError> { let res = functions::invoke_member_function(ctx, map, "has", &[key])?; primitives::to_bool(&res) } /// get the number of entries in a map /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::{new_map_q, set_q, size_q}; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// let key = primitives::from_i32(12); /// let value = primitives::from_i32(23); /// set_q(q_ctx, &my_map, key.clone(), value).ok().unwrap(); /// let i_size = size_q(q_ctx, &my_map).ok().unwrap(); /// assert_eq!(i_size, 1); /// }); /// ``` pub fn size_q(q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter) -> Result<i32, JsError> { unsafe { size(q_ctx.context, map) } } /// get the number of entries in a map /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn size(ctx: *mut q::JSContext, map: &QuickJsValueAdapter) -> Result<i32, JsError> { let res = objects::get_property(ctx, map, "size")?; primitives::to_i32(&res) } /// remove all entries from a map /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::{new_map_q, set_q, clear_q, size_q}; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// let key = primitives::from_i32(12); /// let value = primitives::from_i32(23); /// set_q(q_ctx, &my_map, key.clone(), value).ok().unwrap(); /// clear_q(q_ctx, &my_map).ok().unwrap(); /// let i_size = size_q(q_ctx, &my_map).ok().unwrap(); /// assert_eq!(i_size, 0); /// }); /// ``` pub fn clear_q(q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter) -> Result<(), JsError> { unsafe { clear(q_ctx.context, map) } } /// remove all entries from a map /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn clear(ctx: *mut q::JSContext, map: &QuickJsValueAdapter) -> Result<(), JsError> { let _ = functions::invoke_member_function(ctx, map, "clear", &[])?; Ok(()) } /// iterate over all keys of a map /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::{new_map_q, set_q, keys_q}; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// let key = primitives::from_i32(12); /// let value = primitives::from_i32(23); /// set_q(q_ctx, &my_map, key, value).ok().unwrap(); /// let mapped_keys = keys_q(q_ctx, &my_map, |key| {Ok(123)}).ok().unwrap(); /// assert_eq!(mapped_keys.len(), 1); /// }); /// ``` pub fn keys_q<C: Fn(QuickJsValueAdapter) -> Result<R, JsError>, R>( q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter, consumer_producer: C, ) -> Result<Vec<R>, JsError> { unsafe { keys(q_ctx.context, map, consumer_producer) } } /// iterate over all keys of a map /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn keys<C: Fn(QuickJsValueAdapter) -> Result<R, JsError>, R>( ctx: *mut q::JSContext, map: &QuickJsValueAdapter, consumer_producer: C, ) -> Result<Vec<R>, JsError> { let iter_ref = functions::invoke_member_function(ctx, map, "keys", &[])?; iterators::iterate(ctx, &iter_ref, consumer_producer) } /// iterate over all values of a map /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::{new_map_q, set_q, values_q}; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// let key = primitives::from_i32(12); /// let value = primitives::from_i32(23); /// set_q(q_ctx, &my_map, key, value).ok().unwrap(); /// let mapped_values = values_q(q_ctx, &my_map, |value| {Ok(123)}).ok().unwrap(); /// assert_eq!(mapped_values.len(), 1); /// }); /// ``` pub fn values_q<C: Fn(QuickJsValueAdapter) -> Result<R, JsError>, R>( q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter, consumer_producer: C, ) -> Result<Vec<R>, JsError> { unsafe { values(q_ctx.context, map, consumer_producer) } } /// iterate over all values of a map /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn values<C: Fn(QuickJsValueAdapter) -> Result<R, JsError>, R>( ctx: *mut q::JSContext, map: &QuickJsValueAdapter, consumer_producer: C, ) -> Result<Vec<R>, JsError> { let iter_ref = functions::invoke_member_function(ctx, map, "values", &[])?; iterators::iterate(ctx, &iter_ref, consumer_producer) } /// iterate over all entries of a map /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjs_utils::maps::{new_map_q, set_q, entries_q}; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_map: QuickJsValueAdapter = new_map_q(q_ctx).ok().unwrap(); /// let key = primitives::from_i32(12); /// let value = primitives::from_i32(23); /// set_q(q_ctx, &my_map, key, value).ok().unwrap(); /// let mapped_values = entries_q(q_ctx, &my_map, |key, value| {Ok(123)}).ok().unwrap(); /// assert_eq!(mapped_values.len(), 1); /// }); /// ``` pub fn entries_q<C: Fn(QuickJsValueAdapter, QuickJsValueAdapter) -> Result<R, JsError>, R>( q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter, consumer_producer: C, ) -> Result<Vec<R>, JsError> { unsafe { entries(q_ctx.context, map, consumer_producer) } } /// iterate over all entries of a map /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn entries<C: Fn(QuickJsValueAdapter, QuickJsValueAdapter) -> Result<R, JsError>, R>( ctx: *mut q::JSContext, map: &QuickJsValueAdapter, consumer_producer: C, ) -> Result<Vec<R>, JsError> { let iter_ref = functions::invoke_member_function(ctx, map, "entries", &[])?; iterators::iterate(ctx, &iter_ref, |arr_ref| { let key = arrays::get_element(ctx, &arr_ref, 0)?; let value = arrays::get_element(ctx, &arr_ref, 1)?; consumer_producer(key, value) }) }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/typedarrays.rs
src/quickjs_utils/typedarrays.rs
//! this module is a work in progress and is currently used by me to pass Vec<u8>'s from rust to js and back again //! //! //! use crate::jsutils::JsError; use crate::quickjs_utils::class_ids::JS_CLASS_ARRAY_BUFFER; use crate::quickjs_utils::get_constructor; use crate::quickjs_utils::objects::{ construct_object, get_property, get_prototype_of, is_instance_of, set_property2, }; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use hirofa_utils::auto_id_map::AutoIdMap; use libquickjs_sys as q; use libquickjs_sys::JS_GetClassID; use std::cell::RefCell; // relevant quickjs bindings functions // pub type JSFreeArrayBufferDataFunc = ::std::option::Option< // unsafe extern "C" fn( // rt: *mut JSRuntime, // opaque: *mut ::std::os::raw::c_void, // ptr: *mut ::std::os::raw::c_void, // ), // >; // extern "C" { // pub fn JS_NewArrayBuffer( // ctx: *mut JSContext, // buf: *mut u8, // len: size_t, // free_func: JSFreeArrayBufferDataFunc, // opaque: *mut ::std::os::raw::c_void, // is_shared: ::std::os::raw::c_int, // ) -> JSValue; // } // extern "C" { // pub fn JS_NewArrayBufferCopy(ctx: *mut JSContext, buf: *const u8, len: size_t) -> JSValue; // } // extern "C" { // pub fn JS_DetachArrayBuffer(ctx: *mut JSContext, obj: JSValue); // } // extern "C" { // pub fn JS_GetArrayBuffer(ctx: *mut JSContext, psize: *mut size_t, obj: JSValue) -> *mut u8; // } // extern "C" { // pub fn JS_GetTypedArrayBuffer( // ctx: *mut JSContext, // obj: JSValue, // pbyte_offset: *mut size_t, // pbyte_length: *mut size_t, // pbytes_per_element: *mut size_t, // ) -> JSValue; // } thread_local! { // max size is 32.max because we store id as prop pub static BUFFERS: RefCell<AutoIdMap<Vec<u8>>> = RefCell::new(AutoIdMap::new_with_max_size(i32::MAX as usize)); } /// this method creates a new ArrayBuffer which is used as a basis for all typed arrays /// the buffer vec is stored and used in js, when it is no longer needed it is dropped pub fn new_array_buffer_q( q_ctx: &QuickJsRealmAdapter, buf: Vec<u8>, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_array_buffer(q_ctx.context, buf) } } /// this method creates a new ArrayBuffer which is used as a basis for all typed arrays /// the buffer vec is stored and used in js, when it is no longer needed it is dropped /// # Safety /// QuickJsRealmAdapter should not be dropped before using this, e.g. the context should still be valid pub unsafe fn new_array_buffer( ctx: *mut q::JSContext, buf: Vec<u8>, ) -> Result<QuickJsValueAdapter, JsError> { log::trace!("new_array_buffer"); let length: usize = buf.len(); let (buffer_id, buffer_ptr) = BUFFERS.with(|rc| { let buffers = &mut *rc.borrow_mut(); let id = buffers.insert(buf); let ptr = buffers.get_mut(&id).unwrap().as_mut_ptr(); (id, ptr) }); let opaque = buffer_id; #[cfg(feature = "bellard")] let is_shared = 0; #[cfg(feature = "quickjs-ng")] let is_shared = false; let raw = q::JS_NewArrayBuffer( ctx, buffer_ptr, length, Some(free_func), opaque as _, is_shared as _, ); let obj_ref = QuickJsValueAdapter::new(ctx, raw, false, true, "typedarrays::new_array_buffer_q"); if obj_ref.is_exception() { return Err(JsError::new_str("Could not create array buffer")); } let prop_ref = crate::quickjs_utils::primitives::from_i32(buffer_id as i32); set_property2(ctx, &obj_ref, "__buffer_id", &prop_ref, 0)?; Ok(obj_ref) } pub fn is_array_buffer_q(buf: &QuickJsValueAdapter) -> bool { unsafe { is_array_buffer(buf) } } /// check if a ref is an ArrayBuffer /// # Safety /// please ensure that the relevant QuickjsRealmAdapter is not dropped while using this function or a result of this function pub unsafe fn is_array_buffer(buf: &QuickJsValueAdapter) -> bool { JS_GetClassID(*buf.borrow_value()) == JS_CLASS_ARRAY_BUFFER } pub fn is_typed_array_q(q_ctx: &QuickJsRealmAdapter, arr: &QuickJsValueAdapter) -> bool { unsafe { is_typed_array(q_ctx.context, arr) } } /// check if a ref is a TypedArray /// # Safety /// please ensure that the relevant QuickjsRealmAdapter is not dropped while using this function or a result of this function pub unsafe fn is_typed_array(ctx: *mut q::JSContext, arr: &QuickJsValueAdapter) -> bool { if arr.is_object() { match get_constructor(ctx, "Uint16Array") { Ok(u_int_some_array) => match get_prototype_of(ctx, &u_int_some_array) { Ok(typed_array) => is_instance_of(ctx, arr, &typed_array), Err(_) => false, }, Err(_) => false, } } else { false } } /// create an array buffer with a copy of the data in a Vec pub fn new_array_buffer_copy_q( q_ctx: &QuickJsRealmAdapter, buf: &[u8], ) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_array_buffer_copy(q_ctx.context, buf) } } /// create an array buffer with a copy of the data in a Vec /// # Safety /// please ensure that the relevant QuickjsRealmAdapter is not dropped while using this function or a result of this function pub unsafe fn new_array_buffer_copy( ctx: *mut q::JSContext, buf: &[u8], ) -> Result<QuickJsValueAdapter, JsError> { log::trace!("new_array_buffer_copy"); let length: usize = buf.len(); let raw = q::JS_NewArrayBufferCopy(ctx, buf.as_ptr(), length); let obj_ref = QuickJsValueAdapter::new( ctx, raw, false, true, "typedarrays::new_array_buffer_copy_q", ); if obj_ref.is_exception() { return Err(JsError::new_str("Could not create array buffer")); } Ok(obj_ref) } /// detach the array buffer and return it, after this the TypedArray is no longer usable in JS (or at least all items will return undefined) pub fn detach_array_buffer_buffer_q( q_ctx: &QuickJsRealmAdapter, array_buffer: &QuickJsValueAdapter, ) -> Result<Vec<u8>, JsError> { unsafe { detach_array_buffer_buffer(q_ctx.context, array_buffer) } } /// detach the array buffer and return it, after this the TypedArray is no longer usable in JS (or at least all items will return undefined) /// # Safety /// please ensure that the relevant QuickjsRealmAdapter is not dropped while using this function or a result of this function pub unsafe fn detach_array_buffer_buffer( ctx: *mut q::JSContext, array_buffer: &QuickJsValueAdapter, ) -> Result<Vec<u8>, JsError> { log::trace!("detach_array_buffer_buffer"); debug_assert!(is_array_buffer(array_buffer)); // check if vec is one we buffered, if not we create a new one from the slice we got from quickjs // abuf->opaque seems impossible to get at, so we store the id ourselves as well let id_prop = get_property(ctx, array_buffer, "__buffer_id")?; let id_opt = if id_prop.is_i32() { Some(id_prop.to_i32() as usize) } else { None }; let v = if let Some(id) = id_opt { BUFFERS.with(|rc| { let buffers = &mut *rc.borrow_mut(); buffers.remove(&id) }) } else { let mut len: usize = 0; let ptr = q::JS_GetArrayBuffer(ctx, &mut len, *array_buffer.borrow_value()); Vec::from_raw_parts(ptr, len as _, len as _) }; q::JS_DetachArrayBuffer(ctx, *array_buffer.borrow_value()); Ok(v) } /// Get a copy of the underlying array buffer and return it /// unlike when using detach_array_buffer_buffer_q the TypedArray is still intact after using this /// the operation is just more expensive because the Vec is cloned pub fn get_array_buffer_buffer_copy_q( q_ctx: &QuickJsRealmAdapter, array_buffer: &QuickJsValueAdapter, ) -> Result<Vec<u8>, JsError> { unsafe { get_array_buffer_buffer_copy(q_ctx.context, array_buffer) } } /// Get a copy of the underlying array buffer and return it /// unlike when using detach_array_buffer_buffer_q the TypedArray is still intact after using this /// the operation is just more expensive because the Vec is cloned /// # Safety /// please ensure that the relevant QuickjsRealmAdapter is not dropped while using this function or a result of this function pub unsafe fn get_array_buffer_buffer_copy( ctx: *mut q::JSContext, array_buffer: &QuickJsValueAdapter, ) -> Result<Vec<u8>, JsError> { debug_assert!(is_array_buffer(array_buffer)); log::trace!("get_array_buffer_buffer_copy"); let id_prop = get_property(ctx, array_buffer, "__buffer_id")?; let id_opt = if id_prop.is_i32() { Some(id_prop.to_i32() as usize) } else { None }; if let Some(id) = id_opt { let b = BUFFERS.with(|rc| { let buffers = &mut *rc.borrow_mut(); buffers.get(&id).expect("invalid buffer state").clone() }); Ok(b) } else { let mut len: usize = 0; let ptr = q::JS_GetArrayBuffer(ctx, &mut len, *array_buffer.borrow_value()); let slice = std::slice::from_raw_parts(ptr, len as _); Ok(slice.to_vec()) } } /// get the underlying ArrayBuffer of a TypedArray pub fn get_array_buffer_q( q_ctx: &QuickJsRealmAdapter, typed_array: &QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { get_array_buffer(q_ctx.context, typed_array) } } /// get the underlying ArrayBuffer of a TypedArray /// # Safety /// please ensure that the relevant QuickjsRealmAdapter is not dropped while using this function or a result of this function pub unsafe fn get_array_buffer( ctx: *mut q::JSContext, typed_array: &QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { debug_assert!(is_typed_array(ctx, typed_array)); // this is probably needed later for different typed arrays //let raw = q::JS_GetTypedArrayBuffer() // todo!(); // for our Uint8Array uses cases this works fine log::trace!("get_array_buffer"); get_property(ctx, typed_array, "buffer") } /// create a new TypedArray with a buffer, the buffer is consumed and can be reclaimed later by calling detach_array_buffer_buffer_q pub fn new_uint8_array_q( q_ctx: &QuickJsRealmAdapter, buf: Vec<u8>, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_uint8_array(q_ctx.context, buf) } } /// create a new TypedArray with a buffer, the buffer is consumed and can be reclaimed later by calling detach_array_buffer_buffer_q /// # Safety /// please ensure that the relevant QuickjsRealmAdapter is not dropped while using this function or a result of this function pub unsafe fn new_uint8_array( ctx: *mut q::JSContext, buf: Vec<u8>, ) -> Result<QuickJsValueAdapter, JsError> { let array_buffer = new_array_buffer(ctx, buf)?; let constructor = get_constructor(ctx, "Uint8Array")?; construct_object(ctx, &constructor, &[&array_buffer]) } /// create a new TypedArray with a buffer, the buffer is copied and that copy can be reclaimed later by calling detach_array_buffer_buffer_q pub fn new_uint8_array_copy_q( q_ctx: &QuickJsRealmAdapter, buf: &[u8], ) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_uint8_array_copy(q_ctx.context, buf) } } /// create a new TypedArray with a buffer, the buffer is copied and that copy can be reclaimed later by calling detach_array_buffer_buffer_q /// # Safety /// please ensure that the relevant QuickjsRealmAdapter is not dropped while using this function or a result of this function pub unsafe fn new_uint8_array_copy( ctx: *mut q::JSContext, buf: &[u8], ) -> Result<QuickJsValueAdapter, JsError> { let array_buffer = new_array_buffer_copy(ctx, buf)?; let constructor = get_constructor(ctx, "Uint8Array")?; construct_object(ctx, &constructor, &[&array_buffer]) } unsafe extern "C" fn free_func( _rt: *mut q::JSRuntime, opaque: *mut ::std::os::raw::c_void, ptr: *mut ::std::os::raw::c_void, ) { let id = opaque as usize; log::trace!("typedarrays::free_func {}", id); if ptr.is_null() { return; } BUFFERS.with(|rc| { let buffers = &mut *rc.borrow_mut(); if buffers.contains_key(&id) { let _buf = buffers.remove(&id); } }); } #[cfg(test)] pub mod tests { use crate::jsutils::{JsError, Script}; use crate::quickjs_utils::typedarrays::{ detach_array_buffer_buffer_q, get_array_buffer_buffer_copy_q, get_array_buffer_q, is_array_buffer_q, is_typed_array_q, new_array_buffer_q, new_uint8_array_copy_q, new_uint8_array_q, }; use crate::values::{JsValueFacade, TypedArrayType}; use crate::facades::tests::init_test_rt; use crate::quickjs_utils::objects::set_property_q; use crate::quickjs_utils::{get_global_q, new_undefined_ref}; use std::thread; use std::time::Duration; #[test] fn test_typed() { let rt = init_test_rt(); let res: Result<(), JsError> = rt.exe_rt_task_in_event_loop(|rt| { let mut buffer: Vec<u8> = vec![]; for y in 0..(10 * 1024 * 1024) { buffer.push(y as u8); } let realm = rt.get_main_realm(); let adapter = new_uint8_array_copy_q(realm, &buffer)?; drop(buffer); let global = get_global_q(realm); set_property_q(realm, &global, "buf", &adapter)?; drop(adapter); realm.eval(Script::new( "l.js", "console.log(`buf l=%s 1=%s`, globalThis.buf.length, globalThis.buf[1]);", ))?; set_property_q(realm, &global, "buf", &new_undefined_ref())?; rt.gc(); Ok(()) }); match res { Ok(_) => { log::info!("done ok"); } Err(err) => { panic!("{err}"); } } } #[test] fn test_typed2() { let rt = init_test_rt(); let res = rt.loop_realm_sync(None, |_rt, realm| { let obj = realm .eval(Script::new( "testu8", "const arr = new Uint8Array(10); arr;", )) .expect("script failed"); obj.get_tag() }); log::debug!("tag res {}", res); rt.loop_realm_sync(None, |_rt, realm| { realm .eval(Script::new( "testu8", "globalThis.testTyped = function(typedArray) {console.log('t=%s len=%s 0=%s 1=%s 2=%s', typedArray.constructor.name, typedArray.length, typedArray[0], typedArray[1], typedArray[2]); typedArray[0] = 34; const ret = []; for (let x = 0; x < 1024; x++) {ret.push(x);}; return new Uint8Array(ret);};", )) .expect("script failed"); }); rt.loop_realm_sync(None, |_rt, realm| { let buf = vec![1, 2, 3]; let ab_res = new_array_buffer_q(realm, buf); match ab_res { Ok(ab) => { log::debug!("buffer created, dropping"); assert!(is_array_buffer_q(&ab)); drop(ab); log::debug!("buffer created, dropped"); } Err(e) => { log::debug!("err: {}", e); } } let mut buf2 = vec![]; for x in 0..(1024 * 1024) { buf2.push(x as u8); } let arr_res = new_uint8_array_q(realm, buf2); match arr_res { Ok(mut arr) => { arr.label("arr"); #[cfg(feature = "bellard")] log::debug!("arr created, refcount={}", arr.get_ref_count()); assert!(is_typed_array_q(realm, &arr)); realm .invoke_function_by_name(&[], "testTyped", &[arr.clone()]) .expect("testTyped failed"); let ab = get_array_buffer_q(realm, &arr).expect("did not get buffer"); let copy = get_array_buffer_buffer_copy_q(realm, &ab).expect("could not copy"); log::info!("copy.len = {}", copy.len()); log::trace!("reclaiming"); let buf2_reclaimed = detach_array_buffer_buffer_q(realm, &ab).expect("detach failed"); //unsafe { q::JS_DetachArrayBuffer(realm.context, *arr.borrow_value()) }; log::trace!("reclaimed"); // this still works but all values should be undefined.. realm .invoke_function_by_name(&[], "testTyped", &[arr.clone()]) .expect("script failed"); log::trace!("ab dropped"); // atm this causes another call to free_buffer, also code above just works ... is detach not working? drop(arr); log::trace!("arr dropped"); log::debug!("buf2.len={}", buf2_reclaimed.len()); log::debug!( "0={} 1={}, 2={}", buf2_reclaimed.first().unwrap(), buf2_reclaimed.get(1).unwrap(), buf2_reclaimed.get(2).unwrap() ); } Err(e) => { log::debug!("err2: {}", e); } } }); thread::sleep(Duration::from_secs(1)); for x in 0..10 { let mut buffer2: Vec<u8> = vec![]; for y in 0..(10 * 1024 * 1024) { buffer2.push(y as u8); } let ta = JsValueFacade::TypedArray { buffer: buffer2, array_type: TypedArrayType::Uint8, }; let res = rt.invoke_function_sync(None, &[], "testTyped", vec![ta]); match res { Ok(r) => { log::info!("from jsvf got {:?}", r); } Err(e) => { panic!("{}", e); } } log::info!("x={x}"); } drop(rt); crate::quickjs_utils::typedarrays::BUFFERS.with(|rc| { let buffers = &mut *rc.borrow_mut(); log::info!("BUFFERS.len = {}", buffers.len()); }); thread::sleep(Duration::from_secs(1)); } }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
HiRoFa/quickjs_es_runtime
https://github.com/HiRoFa/quickjs_es_runtime/blob/86cd72baf95baa4391cd831432fd2a1f4defbde5/src/quickjs_utils/sets.rs
src/quickjs_utils/sets.rs
//! Set utils, these methods can be used to manage Set objects from rust //! see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Sap) for more on Sets use crate::jsutils::JsError; #[cfg(feature = "bellard")] use crate::quickjs_utils::class_ids::JS_CLASS_SET; use crate::quickjs_utils::objects::construct_object; use crate::quickjs_utils::{functions, get_constructor, iterators, objects, primitives}; use crate::quickjsrealmadapter::QuickJsRealmAdapter; use crate::quickjsvalueadapter::QuickJsValueAdapter; use libquickjs_sys as q; #[cfg(feature = "bellard")] use libquickjs_sys::JS_GetClassID; #[cfg(feature = "quickjs-ng")] use libquickjs_sys::JS_IsSet; /// create new instance of Set /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::sets::new_set_q; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_set: QuickJsValueAdapter = new_set_q(q_ctx).ok().unwrap(); /// }); /// ``` pub fn new_set_q(q_ctx: &QuickJsRealmAdapter) -> Result<QuickJsValueAdapter, JsError> { unsafe { new_set(q_ctx.context) } } /// create new instance of Set /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn new_set(ctx: *mut q::JSContext) -> Result<QuickJsValueAdapter, JsError> { let map_constructor = get_constructor(ctx, "Set")?; construct_object(ctx, &map_constructor, &[]) } /// see if a JSValueRef is an instance of Set pub fn is_set_q(obj: &QuickJsValueAdapter) -> bool { unsafe { is_set(obj) } } /// see if a JSValueRef is an instance of Set /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn is_set(obj: &QuickJsValueAdapter) -> bool { #[cfg(feature = "bellard")] return JS_GetClassID(*obj.borrow_value()) == JS_CLASS_SET; #[cfg(feature = "quickjs-ng")] return JS_IsSet(*obj.borrow_value()); } /// add a value to the Set /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::quickjs_utils::sets::{new_set_q, add_q}; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_set: QuickJsValueAdapter = new_set_q(q_ctx).ok().unwrap(); /// let value = primitives::from_i32(23); /// add_q(q_ctx, &my_set, value).ok().unwrap(); /// }); /// ``` pub fn add_q( q_ctx: &QuickJsRealmAdapter, set: &QuickJsValueAdapter, val: QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { unsafe { add(q_ctx.context, set, val) } } /// add a value to a Set /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn add( ctx: *mut q::JSContext, set: &QuickJsValueAdapter, val: QuickJsValueAdapter, ) -> Result<QuickJsValueAdapter, JsError> { functions::invoke_member_function(ctx, set, "add", &[val]) } /// delete a value from a set /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::quickjs_utils::sets::{add_q, new_set_q, delete_q}; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_set: QuickJsValueAdapter = new_set_q(q_ctx).ok().unwrap(); /// let value = primitives::from_i32(23); /// add_q(q_ctx, &my_set, value.clone()).ok().unwrap(); /// delete_q(q_ctx, &my_set, value).ok().unwrap(); /// }); /// ``` pub fn delete_q( q_ctx: &QuickJsRealmAdapter, set: &QuickJsValueAdapter, value: QuickJsValueAdapter, ) -> Result<bool, JsError> { unsafe { delete(q_ctx.context, set, value) } } /// delete a value from a set /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn delete( ctx: *mut q::JSContext, set: &QuickJsValueAdapter, value: QuickJsValueAdapter, ) -> Result<bool, JsError> { let res = functions::invoke_member_function(ctx, set, "delete", &[value])?; primitives::to_bool(&res) } /// check whether a Set has a certain value /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::quickjs_utils::sets::{new_set_q, add_q, has_q}; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_set: QuickJsValueAdapter = new_set_q(q_ctx).ok().unwrap(); /// let value = primitives::from_i32(23); /// add_q(q_ctx, &my_set, value.clone()).ok().unwrap(); /// let bln_has = has_q(q_ctx, &my_set, value).ok().unwrap(); /// assert!(bln_has); /// }); /// ``` pub fn has_q( q_ctx: &QuickJsRealmAdapter, set: &QuickJsValueAdapter, key: QuickJsValueAdapter, ) -> Result<bool, JsError> { unsafe { has(q_ctx.context, set, key) } } /// check whether a Set has a value /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn has( ctx: *mut q::JSContext, set: &QuickJsValueAdapter, key: QuickJsValueAdapter, ) -> Result<bool, JsError> { let res = functions::invoke_member_function(ctx, set, "has", &[key])?; primitives::to_bool(&res) } /// get the number of entries in a Set /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::quickjs_utils::sets::{add_q, new_set_q, size_q}; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_set: QuickJsValueAdapter = new_set_q(q_ctx).ok().unwrap(); /// let value = primitives::from_i32(23); /// add_q(q_ctx, &my_set, value).ok().unwrap(); /// let i_size = size_q(q_ctx, &my_set).ok().unwrap(); /// assert_eq!(i_size, 1); /// }); /// ``` pub fn size_q(q_ctx: &QuickJsRealmAdapter, set: &QuickJsValueAdapter) -> Result<i32, JsError> { unsafe { size(q_ctx.context, set) } } /// get the number of entries in a Set /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn size(ctx: *mut q::JSContext, set: &QuickJsValueAdapter) -> Result<i32, JsError> { let res = objects::get_property(ctx, set, "size")?; primitives::to_i32(&res) } /// remove all entries from a Set /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::quickjs_utils::sets::{size_q, clear_q, add_q, new_set_q}; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_set: QuickJsValueAdapter = new_set_q(q_ctx).ok().unwrap(); /// let value = primitives::from_i32(23); /// add_q(q_ctx, &my_set, value).ok().unwrap(); /// clear_q(q_ctx, &my_set).ok().unwrap(); /// let i_size = size_q(q_ctx, &my_set).ok().unwrap(); /// assert_eq!(i_size, 0); /// }); /// ``` pub fn clear_q(q_ctx: &QuickJsRealmAdapter, map: &QuickJsValueAdapter) -> Result<(), JsError> { unsafe { clear(q_ctx.context, map) } } /// remove all entries from a Set /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn clear(ctx: *mut q::JSContext, set: &QuickJsValueAdapter) -> Result<(), JsError> { let _ = functions::invoke_member_function(ctx, set, "clear", &[])?; Ok(()) } /// iterate over all values of a Set /// # Example /// ```rust /// use quickjs_runtime::builder::QuickJsRuntimeBuilder; /// use quickjs_runtime::quickjsvalueadapter::QuickJsValueAdapter; /// use quickjs_runtime::quickjs_utils::primitives; /// use quickjs_runtime::quickjs_utils::sets::{new_set_q, add_q, values_q}; /// /// let rt = QuickJsRuntimeBuilder::new().build(); /// rt.exe_rt_task_in_event_loop(|q_js_rt| { /// let q_ctx = q_js_rt.get_main_realm(); /// let my_set: QuickJsValueAdapter = new_set_q(q_ctx).ok().unwrap(); /// let value = primitives::from_i32(23); /// add_q(q_ctx, &my_set, value).ok().unwrap(); /// let mapped_values = values_q(q_ctx, &my_set, |value| {Ok(123)}).ok().unwrap(); /// assert_eq!(mapped_values.len(), 1); /// }); /// ``` pub fn values_q<C: Fn(QuickJsValueAdapter) -> Result<R, JsError>, R>( q_ctx: &QuickJsRealmAdapter, set: &QuickJsValueAdapter, consumer_producer: C, ) -> Result<Vec<R>, JsError> { unsafe { values(q_ctx.context, set, consumer_producer) } } /// iterate over all values of a Set /// # Safety /// please ensure the passed JSContext is still valid pub unsafe fn values<C: Fn(QuickJsValueAdapter) -> Result<R, JsError>, R>( ctx: *mut q::JSContext, set: &QuickJsValueAdapter, consumer_producer: C, ) -> Result<Vec<R>, JsError> { let iter_ref = functions::invoke_member_function(ctx, set, "values", &[])?; iterators::iterate(ctx, &iter_ref, consumer_producer) }
rust
MIT
86cd72baf95baa4391cd831432fd2a1f4defbde5
2026-01-04T20:25:00.898147Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/misc/simple_message_relay/src/main.rs
misc/simple_message_relay/src/main.rs
use std::{ collections::{HashMap, VecDeque}, sync::Mutex, }; use actix_web::{ get, post, web::{self, Bytes}, App, HttpResponse, HttpServer, Responder, }; #[derive(Default)] struct UserMessages { messages_by_user_id: Mutex<HashMap<String, VecDeque<Vec<u8>>>>, } #[get("/")] async fn hello() -> impl Responder { HttpResponse::Ok().body("Hello world!") } #[get("/pop_user_message/{user_id}")] async fn pop_user_message( path: web::Path<String>, data: web::Data<UserMessages>, ) -> impl Responder { let user_id = path.into_inner(); let mut messages_by_user_id = data.messages_by_user_id.lock().unwrap(); let messages_for_user = messages_by_user_id.get_mut(&user_id); let message_body = messages_for_user.and_then(|msgs| msgs.pop_front()); if let Some(body) = message_body { HttpResponse::Ok().body(body) } else { HttpResponse::NoContent().into() } } #[post("/send_user_message/{user_id}")] async fn send_user_message( path: web::Path<String>, body: Bytes, data: web::Data<UserMessages>, ) -> impl Responder { let user_id = path.into_inner(); let body = body.to_vec(); let mut messages_by_user_id = data.messages_by_user_id.lock().unwrap(); let messages_for_user = messages_by_user_id.get_mut(&user_id); if let Some(messages) = messages_for_user { messages.push_back(body); } else { messages_by_user_id.insert(user_id, vec![body].into()); } HttpResponse::Ok() } #[get("/status")] async fn status() -> impl Responder { HttpResponse::Ok() } #[actix_web::main] async fn main() -> std::io::Result<()> { let user_messages = web::Data::new(UserMessages::default()); HttpServer::new(move || { App::new() .app_data(user_messages.clone()) .service(pop_user_message) .service(send_user_message) .service(status) }) .bind(("0.0.0.0", 8420))? .run() .await } #[cfg(test)] mod tests { use actix_web::{ body, http::StatusCode, test::{self, TestRequest}, web, App, }; use crate::{pop_user_message, send_user_message, UserMessages}; fn pop_message_request(user_id: &str) -> TestRequest { test::TestRequest::get().uri(&format!("/pop_user_message/{user_id}")) } fn send_message_request(user_id: &str, msg: &'static str) -> TestRequest { test::TestRequest::post() .uri(&format!("/send_user_message/{user_id}")) .set_payload(msg) } #[actix_web::test] async fn test_standard_user_flow() { // assemble service let user_messages = web::Data::new(UserMessages::default()); let app = test::init_service( App::new() .app_data(user_messages) .service(send_user_message) .service(pop_user_message), ) .await; let user_id = "user1"; // pop for unknown user == NO CONTENT let pop_response = test::call_service(&app, pop_message_request(user_id).to_request()).await; assert_eq!(pop_response.status(), StatusCode::NO_CONTENT); let body = pop_response.into_body(); assert!(body::to_bytes(body).await.unwrap().is_empty()); // post a message in let message = "hello world"; let req = send_message_request(user_id, message).to_request(); let resp = test::call_service(&app, req).await; assert!(resp.status().is_success()); // pop for known user == OK and body let pop_response = test::call_service(&app, pop_message_request(user_id).to_request()).await; assert_eq!(pop_response.status(), StatusCode::OK); let body = pop_response.into_body(); assert_eq!(body::to_bytes(body).await.unwrap(), message.as_bytes()); // pop for no messages == NO CONTENT let pop_response = test::call_service(&app, pop_message_request(user_id).to_request()).await; assert_eq!(pop_response.status(), StatusCode::NO_CONTENT); let body = pop_response.into_body(); assert!(body::to_bytes(body).await.unwrap().is_empty()); } #[actix_web::test] async fn test_multi_message_multi_user_flow() { // assemble service let user_messages = web::Data::new(UserMessages::default()); let app = test::init_service( App::new() .app_data(user_messages) .service(send_user_message) .service(pop_user_message), ) .await; let user_id1 = "user1"; let user_id2 = "user2"; let message1 = "message1"; let message2 = "message2"; let message3 = "message3"; let message4 = "message4"; // populate test::call_service(&app, send_message_request(user_id1, message1).to_request()).await; test::call_service(&app, send_message_request(user_id1, message2).to_request()).await; test::call_service(&app, send_message_request(user_id2, message3).to_request()).await; test::call_service(&app, send_message_request(user_id2, message4).to_request()).await; // pop and check let res = test::call_service(&app, pop_message_request(user_id1).to_request()).await; assert_eq!( body::to_bytes(res.into_body()).await.unwrap(), message1.as_bytes() ); let res = test::call_service(&app, pop_message_request(user_id2).to_request()).await; assert_eq!( body::to_bytes(res.into_body()).await.unwrap(), message3.as_bytes() ); let res = test::call_service(&app, pop_message_request(user_id1).to_request()).await; assert_eq!( body::to_bytes(res.into_body()).await.unwrap(), message2.as_bytes() ); let res = test::call_service(&app, pop_message_request(user_id2).to_request()).await; assert_eq!( body::to_bytes(res.into_body()).await.unwrap(), message4.as_bytes() ); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/misc/display_as_json/src/lib.rs
misc/display_as_json/src/lib.rs
extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; #[proc_macro_derive(Display)] pub fn display_as_json_derive(input: TokenStream) -> TokenStream { let ast = syn::parse(input).unwrap(); impl_display(&ast) } fn impl_display(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; let generics = &ast.generics; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); // For each of the generics parameter G, we prepare addition trait bound "G: serde::Serialize" let serialize_bounds = generics.params.iter().filter_map(|param| { match param { syn::GenericParam::Type(type_param) => { let ident = &type_param.ident; Some(quote! { #ident: serde::Serialize }) } _ => None, // Skip non-type parameters, eg lifetimes } }); // Combine the original where clause with additional bounds we prepared above // See quote! macro docs for more info on the #() syntax https://docs.rs/quote/1.0.33/quote/macro.quote.html let combined_where_clause = if where_clause.is_none() { quote! { where #(#serialize_bounds),* } } else { quote! { #where_clause, #(#serialize_bounds),* } }; // Generate the actual impl let gen = quote! { impl #impl_generics std::fmt::Display for #name #ty_generics #combined_where_clause { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match serde_json::to_string(self) { Ok(json) => write!(f, "{}", json), Err(e) => write!(f, "Error serializing {}: {}", stringify!(#name), e), } } } }; gen.into() }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/misc/display_as_json/tests/demo.rs
misc/display_as_json/tests/demo.rs
extern crate display_as_json; extern crate serde; use serde::{Deserialize, Serialize}; use crate::display_as_json::Display; #[derive(Serialize, Deserialize, Display)] struct TestStruct { field1: u32, field2: String, } #[test] fn test_display_as_json() { let instance = TestStruct { field1: 42, field2: "hello".to_string(), }; let displayed = format!("{instance}"); let expected = r#"{"field1":42,"field2":"hello"}"#; assert_eq!(displayed, expected); }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/lib.rs
did_core/did_doc/src/lib.rs
extern crate display_as_json; extern crate serde; extern crate serde_json; pub mod error; pub mod schema; pub use did_parser_nom;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/error.rs
did_core/did_doc/src/error.rs
use crate::schema::verification_method::{error::KeyDecodingError, VerificationMethodType}; #[derive(Debug)] pub enum DidDocumentBuilderError { CustomError(String), MissingField(&'static str), JsonError(serde_json::Error), KeyDecodingError(KeyDecodingError), UnsupportedVerificationMethodType(VerificationMethodType), PublicKeyError(public_key::PublicKeyError), } impl std::fmt::Display for DidDocumentBuilderError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { DidDocumentBuilderError::MissingField(field) => { write!(f, "Missing field: {field}") } DidDocumentBuilderError::JsonError(error) => { write!(f, "(De)serialization error: {error}") } DidDocumentBuilderError::UnsupportedVerificationMethodType(vm_type) => { write!(f, "Unsupported verification method type: {vm_type}") } DidDocumentBuilderError::PublicKeyError(error) => { write!(f, "Public key error: {error}") } DidDocumentBuilderError::CustomError(string) => { write!(f, "Custom DidDocumentBuilderError: {string}") } DidDocumentBuilderError::KeyDecodingError(error) => { write!(f, "Key decoding error: {error}") } } } } impl std::error::Error for DidDocumentBuilderError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { DidDocumentBuilderError::JsonError(error) => Some(error), DidDocumentBuilderError::PublicKeyError(error) => Some(error), _ => None, } } } impl From<serde_json::Error> for DidDocumentBuilderError { fn from(error: serde_json::Error) -> Self { DidDocumentBuilderError::JsonError(error) } } impl From<public_key::PublicKeyError> for DidDocumentBuilderError { fn from(error: public_key::PublicKeyError) -> Self { DidDocumentBuilderError::PublicKeyError(error) } } impl From<KeyDecodingError> for DidDocumentBuilderError { fn from(error: KeyDecodingError) -> Self { DidDocumentBuilderError::KeyDecodingError(error) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/mod.rs
did_core/did_doc/src/schema/mod.rs
pub mod did_doc; pub mod service; pub mod types; pub mod utils; pub mod verification_method; /// Module of commonly used DID-related JSON-LD contexts pub mod contexts { pub const W3C_DID_V1: &str = "https://www.w3.org/ns/did/v1"; pub const W3C_DID_V1_ALT: &str = "https://w3id.org/did/v1"; pub const W3C_SUITE_ED25519_2020: &str = "https://w3id.org/security/suites/ed25519-2020/v1"; pub const W3C_SUITE_ED25519_2018: &str = "https://w3id.org/security/suites/ed25519-2018/v1"; pub const W3C_SUITE_JWS_2020: &str = "https://w3id.org/security/suites/jws-2020/v1"; pub const W3C_SUITE_SECP256K1_2019: &str = "https://w3id.org/security/suites/secp256k1-2019/v1"; pub const W3C_BBS_V1: &str = "https://w3id.org/security/bbs/v1"; pub const W3C_PGP_V1: &str = "https://w3id.org/pgp/v1"; pub const W3C_SUITE_X25519_2019: &str = "https://w3id.org/security/suites/x25519-2019/v1"; pub const W3C_SUITE_X25519_2020: &str = "https://w3id.org/security/suites/x25519-2020/v1"; pub const W3C_SUITE_SECP259K1_RECOVERY_2020: &str = "https://w3id.org/security/suites/secp256k1recovery-2020/v2"; pub const W3C_MULTIKEY_V1: &str = "https://w3id.org/security/multikey/v1"; }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/did_doc.rs
did_core/did_doc/src/schema/did_doc.rs
use std::collections::HashMap; use did_parser_nom::{Did, DidUrl}; use display_as_json::Display; use serde::{Deserialize, Serialize}; use serde_json::Value; use super::{ types::uri::Uri, utils::OneOrList, verification_method::{VerificationMethod, VerificationMethodKind}, }; use crate::{error::DidDocumentBuilderError, schema::service::Service}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default, Display)] #[serde(default)] #[serde(rename_all = "camelCase")] pub struct DidDocument { id: Did, #[serde(skip_serializing_if = "Vec::is_empty")] also_known_as: Vec<Uri>, #[serde(skip_serializing_if = "Option::is_none")] controller: Option<OneOrList<Did>>, #[serde(skip_serializing_if = "Vec::is_empty")] verification_method: Vec<VerificationMethod>, #[serde(skip_serializing_if = "Vec::is_empty")] authentication: Vec<VerificationMethodKind>, #[serde(skip_serializing_if = "Vec::is_empty")] assertion_method: Vec<VerificationMethodKind>, #[serde(skip_serializing_if = "Vec::is_empty")] key_agreement: Vec<VerificationMethodKind>, #[serde(skip_serializing_if = "Vec::is_empty")] capability_invocation: Vec<VerificationMethodKind>, #[serde(skip_serializing_if = "Vec::is_empty")] capability_delegation: Vec<VerificationMethodKind>, #[serde(skip_serializing_if = "Vec::is_empty")] service: Vec<Service>, #[serde(skip_serializing_if = "HashMap::is_empty")] #[serde(flatten)] extra: HashMap<String, Value>, } impl DidDocument { pub fn new(id: Did) -> Self { DidDocument { id, also_known_as: vec![], controller: None, verification_method: vec![], authentication: vec![], assertion_method: vec![], key_agreement: vec![], capability_invocation: vec![], capability_delegation: vec![], service: vec![], extra: Default::default(), } } pub fn id(&self) -> &Did { &self.id } pub fn set_id(&mut self, id: Did) { self.id = id; } pub fn also_known_as(&self) -> &[Uri] { self.also_known_as.as_ref() } pub fn controller(&self) -> Option<&OneOrList<Did>> { self.controller.as_ref() } pub fn verification_method(&self) -> &[VerificationMethod] { self.verification_method.as_ref() } pub fn verification_method_by_id(&self, id: &str) -> Option<&VerificationMethod> { self.verification_method .iter() .find(|vm| match vm.id().fragment() { Some(fragment) => fragment == id, None => false, }) } pub fn authentication(&self) -> &[VerificationMethodKind] { self.authentication.as_ref() } fn try_match_and_deref_verification_method<'a>( &'a self, vm: &'a VerificationMethodKind, id: &str, ) -> Option<&'a VerificationMethod> { match vm { VerificationMethodKind::Resolved(vm) => { if vm.id().fragment() == Some(id) { Some(vm) } else { None } } VerificationMethodKind::Resolvable(vm_ref) => { if vm_ref.fragment() == Some(id) { self.dereference_key(vm_ref) } else { None } } } } pub fn authentication_by_id(&self, id: &str) -> Option<&VerificationMethod> { for vm in self.authentication.iter() { match self.try_match_and_deref_verification_method(vm, id) { Some(vm) => return Some(vm), None => continue, } } None } pub fn assertion_method(&self) -> &[VerificationMethodKind] { self.assertion_method.as_ref() } pub fn assertion_method_by_key(&self, id: &str) -> Option<&VerificationMethod> { for vm in self.assertion_method.iter() { match self.try_match_and_deref_verification_method(vm, id) { Some(vm) => return Some(vm), None => continue, } } None } pub fn key_agreement(&self) -> &[VerificationMethodKind] { self.key_agreement.as_ref() } pub fn key_agreement_by_id(&self, id: &str) -> Option<&VerificationMethod> { for vm in self.key_agreement.iter() { match self.try_match_and_deref_verification_method(vm, id) { Some(vm) => return Some(vm), None => continue, } } None } pub fn capability_invocation(&self) -> &[VerificationMethodKind] { self.capability_invocation.as_ref() } pub fn capability_invocation_by_id(&self, id: &str) -> Option<&VerificationMethod> { for vm in self.capability_invocation.iter() { match self.try_match_and_deref_verification_method(vm, id) { Some(vm) => return Some(vm), None => continue, } } None } pub fn capability_delegation(&self) -> &[VerificationMethodKind] { self.capability_delegation.as_ref() } pub fn capability_delegation_by_id(&self, id: &str) -> Option<&VerificationMethod> { for vm in self.capability_delegation.iter() { match self.try_match_and_deref_verification_method(vm, id) { Some(vm) => return Some(vm), None => continue, } } None } pub fn service(&self) -> &[Service] { self.service.as_ref() } pub fn extra_field(&self, key: &str) -> Option<&Value> { self.extra.get(key) } /// Scan the DIDDocument for a [VerificationMethod] that matches the given reference. pub fn dereference_key(&self, reference: &DidUrl) -> Option<&VerificationMethod> { let vms = self.verification_method.iter(); // keys are typically in the VMs ^, but may be embedded in the other fields: let assertions = self.assertion_method.iter().filter_map(|k| k.resolved()); let key_agreements = self.key_agreement.iter().filter_map(|k| k.resolved()); let authentications = self.authentication.iter().filter_map(|k| k.resolved()); let cap_invocations = self .capability_invocation .iter() .filter_map(|k| k.resolved()); let cap_delegations = self .capability_delegation .iter() .filter_map(|k| k.resolved()); let mut all_vms = vms .chain(assertions) .chain(key_agreements) .chain(authentications) .chain(cap_invocations) .chain(cap_delegations); all_vms.find(|vm| vm.id().fragment() == reference.fragment()) } pub fn validate(&self) -> Result<(), DidDocumentBuilderError> { Ok(()) } pub fn set_also_known_as(&mut self, uris: Vec<Uri>) { self.also_known_as = uris; } pub fn add_also_known_as(&mut self, uri: Uri) { self.also_known_as.push(uri); } pub fn set_controller(&mut self, controller: OneOrList<Did>) { self.controller = Some(controller); } pub fn add_verification_method(&mut self, method: VerificationMethod) { self.verification_method.push(method); } // authentication pub fn add_authentication(&mut self, method: VerificationMethodKind) { self.authentication.push(method); } pub fn add_authentication_object(&mut self, method: VerificationMethod) { self.authentication .push(VerificationMethodKind::Resolved(method)); } pub fn add_authentication_ref(&mut self, reference: DidUrl) { self.authentication .push(VerificationMethodKind::Resolvable(reference)); } // assertion pub fn add_assertion_method(&mut self, method: VerificationMethodKind) { self.assertion_method.push(method); } pub fn add_assertion_method_object(&mut self, method: VerificationMethod) { self.assertion_method .push(VerificationMethodKind::Resolved(method)); } pub fn add_assertion_method_ref(&mut self, reference: DidUrl) { self.assertion_method .push(VerificationMethodKind::Resolvable(reference)); } // key agreement pub fn add_key_agreement(&mut self, method: VerificationMethodKind) { self.key_agreement.push(method); } pub fn add_key_agreement_object(&mut self, method: VerificationMethod) { self.key_agreement .push(VerificationMethodKind::Resolved(method)); } pub fn add_key_agreement_ref(&mut self, reference: DidUrl) { self.key_agreement .push(VerificationMethodKind::Resolvable(reference)); } // capability invocation pub fn add_capability_invocation(&mut self, method: VerificationMethodKind) { self.capability_invocation.push(method); } pub fn add_capability_invocation_object(&mut self, method: VerificationMethod) { self.capability_invocation .push(VerificationMethodKind::Resolved(method)); } pub fn add_capability_invocation_ref(&mut self, reference: DidUrl) { self.capability_invocation .push(VerificationMethodKind::Resolvable(reference)); } // capability delegation pub fn add_capability_delegation(&mut self, method: VerificationMethodKind) { self.capability_delegation.push(method); } pub fn add_capability_delegation_object(&mut self, method: VerificationMethod) { self.capability_delegation .push(VerificationMethodKind::Resolved(method)); } pub fn add_capability_delegation_ref(&mut self, reference: DidUrl) { self.capability_delegation .push(VerificationMethodKind::Resolvable(reference)); } pub fn set_service(&mut self, services: Vec<Service>) { self.service = services; } pub fn add_service(&mut self, service: Service) { self.service.push(service); } pub fn set_extra_field(&mut self, key: String, value: Value) { self.extra.insert(key, value); } pub fn remove_extra_field(&mut self, key: &str) { self.extra.remove(key); } } #[cfg(test)] mod tests { use super::*; use crate::schema::verification_method::{PublicKeyField, VerificationMethodType}; #[test] fn test_construct_did_document() { let id = Did::parse("did:example:123456789abcdefghi".to_string()).unwrap(); let also_known_as = Uri::new("https://example.com").unwrap(); let controller = Did::parse("did:example:controller".to_string()).unwrap(); let vm1_id = DidUrl::parse("did:example:vm1#vm1".to_string()).unwrap(); let verification_method = VerificationMethod::builder() .id(vm1_id.clone()) .controller(Did::parse("did:example:vm1".to_string()).unwrap()) .verification_method_type(VerificationMethodType::Ed25519VerificationKey2018) .public_key(PublicKeyField::Base58 { public_key_base58: "H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV".to_string(), }) .build(); let authentication_reference = DidUrl::parse("did:example:authref".to_string()).unwrap(); let assertion_method = VerificationMethod::builder() .id(DidUrl::parse("did:example:am1".to_string()).unwrap()) .controller(Did::parse("did:example:am2".to_string()).unwrap()) .verification_method_type(VerificationMethodType::Ed25519VerificationKey2018) .public_key(PublicKeyField::Base58 { public_key_base58: "H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV".to_string(), }) .build(); let service_id = Uri::new("did:example:123456789abcdefghi;service-1").unwrap(); let service_endpoint = "https://example.com/service"; let service = Service::new( service_id, service_endpoint.try_into().unwrap(), OneOrList::One(ServiceType::Other("test-service".to_string())), HashMap::default(), ); let mut did_doc = DidDocument::new(id.clone()); did_doc.set_also_known_as(vec![also_known_as.clone()]); did_doc.set_controller(OneOrList::One(controller.clone())); did_doc.add_verification_method(verification_method.clone()); did_doc.add_authentication_object(verification_method.clone()); did_doc.add_authentication_ref(authentication_reference.clone()); did_doc.add_assertion_method_object(assertion_method.clone()); did_doc.add_assertion_method_ref(authentication_reference.clone()); did_doc.add_key_agreement_object(verification_method.clone()); did_doc.add_key_agreement_ref(authentication_reference.clone()); did_doc.add_capability_invocation_object(verification_method.clone()); did_doc.add_capability_invocation_ref(authentication_reference.clone()); did_doc.add_capability_delegation_object(verification_method.clone()); did_doc.add_capability_delegation_ref(authentication_reference.clone()); did_doc.set_service(vec![service.clone()]) } use std::str::FromStr; use did_parser_nom::{Did, DidUrl}; use serde_json::Value; use crate::schema::{ did_doc::DidDocument, service::typed::ServiceType, types::{jsonwebkey::JsonWebKey, uri::Uri}, verification_method::{VerificationMethod, VerificationMethodKind}, }; const VALID_DID_DOC_JSON: &str = r##" { "@context": [ "https://w3.org/ns/did/v1", "https://w3id.org/security/suites/ed25519-2018/v1" ], "id": "did:web:did-actor-alice", "alsoKnownAs": [ "https://example.com/user-profile/123" ], "publicKey": [ { "id": "did:web:did-actor-alice#z6MkrmNwty5ajKtFqc1U48oL2MMLjWjartwc5sf2AihZwXDN", "controller": "did:web:did-actor-alice", "type": "Ed25519VerificationKey2018", "publicKeyBase58": "DK7uJiq9PnPnj7AmNZqVBFoLuwTjT1hFPrk6LSjZ2JRz" } ], "authentication": [ "did:web:did-actor-alice#z6MkrmNwty5ajKtFqc1U48oL2MMLjWjartwc5sf2AihZwXDN" ], "assertionMethod": [ "did:web:did-actor-alice#z6MkrmNwty5ajKtFqc1U48oL2MMLjWjartwc5sf2AihZwXDN" ], "capabilityDelegation": [ "did:web:did-actor-alice#z6MkrmNwty5ajKtFqc1U48oL2MMLjWjartwc5sf2AihZwXDN" ], "capabilityInvocation": [ "did:web:did-actor-alice#z6MkrmNwty5ajKtFqc1U48oL2MMLjWjartwc5sf2AihZwXDN" ], "verificationMethod": [ { "id": "#g1", "controller": "did:web:did-actor-alice", "type": "JsonWebKey2020", "publicKeyJwk": { "kty": "EC", "crv": "BLS12381_G1", "x": "hxF12gtsn9ju4-kJq2-nUjZQKVVWpcBAYX5VHnUZMDilClZsGuOaDjlXS8pFE1GG" } }, { "id": "#g2", "controller": "did:web:did-actor-alice", "type": "JsonWebKey2020", "publicKeyJwk": { "kty": "EC", "crv": "BLS12381_G2", "x": "l4MeBsn_OGa2OEDtHeHdq0TBC8sYh6QwoI7QsNtZk9oAru1OnGClaAPlMbvvs73EABDB6GjjzybbOHarkBmP6pon8H1VuMna0nkEYihZi8OodgdbwReDiDvWzZuXXMl-" } } ], "keyAgreement": [ { "id": "did:web:did-actor-alice#zC8GybikEfyNaausDA4mkT4egP7SNLx2T1d1kujLQbcP6h", "type": "X25519KeyAgreementKey2019", "controller": "did:web:did-actor-alice", "publicKeyBase58": "CaSHXEvLKS6SfN9aBfkVGBpp15jSnaHazqHgLHp8KZ3Y" } ] } "##; #[test] fn test_deserialization() { let did_doc: DidDocument = serde_json::from_str(VALID_DID_DOC_JSON).unwrap(); assert_eq!( did_doc.id(), &"did:web:did-actor-alice".to_string().try_into().unwrap() ); assert_eq!( did_doc.also_known_as(), vec![Uri::from_str("https://example.com/user-profile/123").unwrap()] ); let controller: Did = "did:web:did-actor-alice".to_string().try_into().unwrap(); let pk_id = DidUrl::parse( "did:web:did-actor-alice#z6MkrmNwty5ajKtFqc1U48oL2MMLjWjartwc5sf2AihZwXDN".to_string(), ) .unwrap(); let vm1_id = DidUrl::parse("#g1".to_string()).unwrap(); let vm1 = VerificationMethod::builder() .id(vm1_id) .controller(controller.clone()) .verification_method_type(VerificationMethodType::JsonWebKey2020) .public_key(PublicKeyField::Jwk { public_key_jwk: JsonWebKey::from_str( r#"{ "kty": "EC", "crv": "BLS12381_G1", "x": "hxF12gtsn9ju4-kJq2-nUjZQKVVWpcBAYX5VHnUZMDilClZsGuOaDjlXS8pFE1GG" }"#, ) .unwrap(), }) .build(); let vm2_id = DidUrl::parse("#g2".to_string()).unwrap(); let vm2 = VerificationMethod::builder() .id(vm2_id) .controller(controller.clone()) .verification_method_type(VerificationMethodType::JsonWebKey2020) .public_key(PublicKeyField::Jwk { public_key_jwk: JsonWebKey::from_str( r#"{ "kty": "EC", "crv": "BLS12381_G2", "x": "l4MeBsn_OGa2OEDtHeHdq0TBC8sYh6QwoI7QsNtZk9oAru1OnGClaAPlMbvvs73EABDB6GjjzybbOHarkBmP6pon8H1VuMna0nkEYihZi8OodgdbwReDiDvWzZuXXMl-" }"#, ).unwrap()}) .build(); assert_eq!(did_doc.verification_method().first().unwrap().clone(), vm1); assert_eq!(did_doc.verification_method().get(1).unwrap().clone(), vm2); assert_eq!( did_doc.authentication(), &[VerificationMethodKind::Resolvable(pk_id.clone())] ); assert_eq!( did_doc.assertion_method(), &[VerificationMethodKind::Resolvable(pk_id.clone())] ); assert_eq!( did_doc.capability_delegation(), &[VerificationMethodKind::Resolvable(pk_id.clone())] ); assert_eq!( did_doc.capability_invocation(), &[VerificationMethodKind::Resolvable(pk_id)] ); assert_eq!( did_doc.extra_field("publicKey").unwrap().clone(), Value::Array(vec![Value::Object( serde_json::from_str( r#"{ "id": "did:web:did-actor-alice#z6MkrmNwty5ajKtFqc1U48oL2MMLjWjartwc5sf2AihZwXDN", "type": "Ed25519VerificationKey2018", "controller": "did:web:did-actor-alice", "publicKeyBase58": "DK7uJiq9PnPnj7AmNZqVBFoLuwTjT1hFPrk6LSjZ2JRz" }"# ) .unwrap() )]) ); let ka1_id = DidUrl::parse( "did:web:did-actor-alice#zC8GybikEfyNaausDA4mkT4egP7SNLx2T1d1kujLQbcP6h".to_string(), ) .unwrap(); let ka1 = VerificationMethod::builder() .id(ka1_id) .controller(controller.clone()) .verification_method_type(VerificationMethodType::X25519KeyAgreementKey2019) .public_key(PublicKeyField::Base58 { public_key_base58: "CaSHXEvLKS6SfN9aBfkVGBpp15jSnaHazqHgLHp8KZ3Y".to_string(), }) .build(); assert_eq!( did_doc.key_agreement(), &[VerificationMethodKind::Resolved(ka1)] ); } #[test] fn test_serialization() { let did_doc: DidDocument = serde_json::from_str(VALID_DID_DOC_JSON).unwrap(); let serialized_json = serde_json::to_string(&did_doc).unwrap(); let original_json_value: DidDocument = serde_json::from_str(VALID_DID_DOC_JSON).unwrap(); let serialized_json_value: DidDocument = serde_json::from_str(&serialized_json).unwrap(); assert_eq!(serialized_json_value, original_json_value); } #[test] fn did_doc_dereferencing() { let did_doc: DidDocument = serde_json::from_value(serde_json::json!({ "@context": [ "https://w3.org/ns/did/v1", "https://w3id.org/security/suites/ed25519-2018/v1" ], "id": "did:web:did-actor-alice", "alsoKnownAs": [ "https://example.com/user-profile/123" ], "verificationMethod": [ { "id": "did:example:123456789abcdefghi#keys-2", "type": "Ed25519VerificationKey2020", "controller": "did:example:123456789abcdefghi", "publicKeyMultibase": "zH3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV" }, { "id": "#keys-3", "type": "Ed25519VerificationKey2020", "controller": "did:example:123456789abcdefghi", "publicKeyMultibase": "zH3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV" } ] })) .unwrap(); { let vm = did_doc .dereference_key( &DidUrl::parse("did:example:123456789abcdefghi#keys-2".to_string()).unwrap(), ) .unwrap(); assert_eq!(vm.id().to_string(), "did:example:123456789abcdefghi#keys-2"); assert_eq!( vm.controller().to_string(), "did:example:123456789abcdefghi" ); assert_eq!( vm.verification_method_type(), &VerificationMethodType::Ed25519VerificationKey2020 ); assert_eq!( vm.public_key_field(), &PublicKeyField::Multibase { public_key_multibase: "zH3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV" .to_string() } ); } { let vm = did_doc .dereference_key(&DidUrl::parse("#keys-2".to_string()).unwrap()) .unwrap(); assert_eq!(vm.id().to_string(), "did:example:123456789abcdefghi#keys-2"); } { let vm = did_doc .dereference_key( &DidUrl::parse("did:example:123456789abcdefghi#keys-3".to_string()).unwrap(), ) .unwrap(); assert_eq!(vm.id().to_string(), "#keys-3"); } { let vm = did_doc .dereference_key(&DidUrl::parse("#keys-3".to_string()).unwrap()) .unwrap(); assert_eq!(vm.id().to_string(), "#keys-3"); } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/service/service_key_kind.rs
did_core/did_doc/src/schema/service/service_key_kind.rs
use std::fmt::Display; use did_key::DidKey; use did_parser_nom::DidUrl; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(untagged)] pub enum ServiceKeyKind { DidKey(DidKey), Reference(DidUrl), Value(String), } impl Display for ServiceKeyKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ServiceKeyKind::Reference(did_url) => write!(f, "{did_url}"), ServiceKeyKind::Value(value) => write!(f, "{value}"), ServiceKeyKind::DidKey(did_key) => write!(f, "{did_key}"), } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/service/mod.rs
did_core/did_doc/src/schema/service/mod.rs
use std::collections::HashMap; use display_as_json::Display; use serde::{Deserialize, Serialize}; use serde_json::Value; use service_accept_type::ServiceAcceptType; use service_key_kind::ServiceKeyKind; use url::Url; use crate::{ error::DidDocumentBuilderError, schema::{service::typed::ServiceType, types::uri::Uri, utils::OneOrList}, }; pub mod service_accept_type; pub mod service_key_kind; pub mod typed; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Display)] #[serde(rename_all = "camelCase")] pub struct Service { id: Uri, #[serde(rename = "type")] service_type: OneOrList<ServiceType>, service_endpoint: Url, #[serde(flatten)] #[serde(skip_serializing_if = "HashMap::is_empty")] extra: HashMap<String, Value>, } impl Service { pub fn new( id: Uri, service_endpoint: Url, service_type: OneOrList<ServiceType>, extra: HashMap<String, Value>, ) -> Service { Service { id, service_endpoint, service_type, extra, } } pub fn id(&self) -> &Uri { &self.id } pub fn service_type(&self) -> &OneOrList<ServiceType> { &self.service_type } pub fn service_types(&self) -> &[ServiceType] { match &self.service_type { OneOrList::One(service_type) => std::slice::from_ref(service_type), OneOrList::List(service_types) => service_types.as_slice(), } } pub fn service_endpoint(&self) -> &Url { &self.service_endpoint } pub fn extra(&self) -> &HashMap<String, Value> { &self.extra } pub fn extra_field_priority(&self) -> Result<u32, DidDocumentBuilderError> { self._expected_extra_field_type::<u32>("priority") } pub fn extra_field_routing_keys(&self) -> Result<Vec<ServiceKeyKind>, DidDocumentBuilderError> { self._expected_extra_field_type::<Vec<ServiceKeyKind>>("routingKeys") } pub fn extra_field_recipient_keys( &self, ) -> Result<Vec<ServiceKeyKind>, DidDocumentBuilderError> { self._expected_extra_field_type::<Vec<ServiceKeyKind>>("recipientKeys") } pub fn extra_field_accept(&self) -> Result<Vec<ServiceAcceptType>, DidDocumentBuilderError> { self._expected_extra_field_type::<Vec<ServiceAcceptType>>("accept") } fn _expected_extra_field_type<T: for<'de> serde::Deserialize<'de>>( &self, key: &'static str, ) -> Result<T, DidDocumentBuilderError> { match self.extra_field_as_as::<T>(key) { None => Err(DidDocumentBuilderError::MissingField(key)), Some(value) => value, } } pub fn extra_field_as_as<T: for<'de> serde::Deserialize<'de>>( &self, key: &str, ) -> Option<Result<T, DidDocumentBuilderError>> { match self.extra.get(key) { Some(value) => { let result = serde_json::from_value::<T>(value.clone()).map_err(|_err| { DidDocumentBuilderError::CustomError(format!( "Extra field {} is not of type {}", key, std::any::type_name::<T>() )) }); Some(result) } None => None, } } pub fn add_extra_field_as<T: serde::Serialize>( &mut self, key: &str, value: T, ) -> Result<(), DidDocumentBuilderError> { let value = serde_json::to_value(value).map_err(|_err| { DidDocumentBuilderError::CustomError(format!( "Failed to serialize extra field {} as {}", key, std::any::type_name::<T>() )) })?; self.extra.insert(key.to_string(), value); Ok(()) } pub fn add_extra_field_routing_keys( &mut self, routing_keys: Vec<ServiceKeyKind>, ) -> Result<(), DidDocumentBuilderError> { self.add_extra_field_as("routingKeys", routing_keys) } pub fn add_extra_field_recipient_keys( &mut self, recipient_keys: Vec<ServiceKeyKind>, ) -> Result<(), DidDocumentBuilderError> { self.add_extra_field_as("recipientKeys", recipient_keys) } pub fn add_extra_field_accept( &mut self, accept: Vec<ServiceAcceptType>, ) -> Result<(), DidDocumentBuilderError> { self.add_extra_field_as("accept", accept) } pub fn add_extra_field_priority( &mut self, priority: u32, ) -> Result<(), DidDocumentBuilderError> { self.add_extra_field_as("priority", priority) } } #[cfg(test)] mod tests { use std::collections::HashMap; use did_parser_nom::DidUrl; use serde_json::json; use crate::schema::{ service::{ service_accept_type::ServiceAcceptType, service_key_kind::ServiceKeyKind, typed::ServiceType, Service, }, types::uri::Uri, utils::OneOrList, }; #[test] fn test_service_builder() { let uri_id = Uri::new("http://example.com").unwrap(); let service_endpoint = "http://example.com/endpoint"; let service_type = ServiceType::DIDCommV2; let service = Service::new( uri_id.clone(), service_endpoint.try_into().unwrap(), OneOrList::One(service_type.clone()), HashMap::default(), ); assert_eq!(service.id(), &uri_id); assert_eq!(service.service_endpoint().as_ref(), service_endpoint); assert_eq!(service.service_types(), vec!(service_type.clone())); assert_eq!(service.service_type(), &OneOrList::One(service_type)); } #[test] fn test_serde_service_aip1() { let service_aip1 = json!({ "id": "service-0", "type": "endpoint", "serviceEndpoint": "https://example.com/endpoint" }) .to_string(); let service = serde_json::from_str::<Service>(&service_aip1).unwrap(); assert_eq!(service.id().to_string(), "service-0"); assert_eq!( service.service_endpoint().to_string(), "https://example.com/endpoint" ); assert_eq!(service.service_types().first().unwrap(), &ServiceType::AIP1); } #[test] fn test_serde_service_didcomm1() { let service_didcomm1 = json!({ "id": "service-0", "type": "did-communication", "priority": 0, "recipientKeys": ["did:sov:HR6vs6GEZ8rHaVgjg2WodM#key-agreement-1"], "routingKeys": [ "did:sov:HR6vs6GEZ8rHaVgjg2WodM#key-agreement-2"], "accept": ["didcomm/aip2;env=rfc19"], "serviceEndpoint": "https://example.com/endpoint" }) .to_string(); let service = serde_json::from_str::<Service>(&service_didcomm1).unwrap(); assert_eq!(service.id().to_string(), "service-0"); assert_eq!( service.service_types().first().unwrap(), &ServiceType::DIDCommV1 ); assert_eq!( service.service_endpoint().to_string(), "https://example.com/endpoint" ); let recipient_keys = service.extra_field_recipient_keys().unwrap(); assert_eq!(recipient_keys.len(), 1); assert_eq!( recipient_keys.first().unwrap(), &ServiceKeyKind::Reference( DidUrl::parse(String::from( "did:sov:HR6vs6GEZ8rHaVgjg2WodM#key-agreement-1" )) .unwrap() ) ); let routing_keys = service.extra_field_routing_keys().unwrap(); assert_eq!(routing_keys.len(), 1); assert_eq!( routing_keys.first().unwrap(), &ServiceKeyKind::Reference( DidUrl::parse(String::from( "did:sov:HR6vs6GEZ8rHaVgjg2WodM#key-agreement-2" )) .unwrap() ) ); let accept = service.extra_field_accept().unwrap(); assert_eq!(accept.len(), 1); assert_eq!(accept.first().unwrap(), &ServiceAcceptType::DIDCommV1); let priority = service.extra_field_priority().unwrap(); assert_eq!(priority, 0); } #[test] fn test_serde_service_didcomm2() { let service_didcomm2 = json!({ "id": "service-0", "type": "DIDCommMessaging", "accept": [ "didcomm/v2"], "routingKeys": [], "serviceEndpoint": "https://example.com/endpoint" }) .to_string(); let service = serde_json::from_str::<Service>(&service_didcomm2).unwrap(); assert_eq!(service.id().to_string(), "service-0"); assert_eq!( service.service_types().first().unwrap(), &ServiceType::DIDCommV2 ); assert_eq!( service.service_endpoint().to_string(), "https://example.com/endpoint" ); let accept = service.extra_field_accept().unwrap(); assert_eq!(accept.len(), 1); assert_eq!(accept.first().unwrap(), &ServiceAcceptType::DIDCommV2); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/service/service_accept_type.rs
did_core/did_doc/src/schema/service/service_accept_type.rs
use std::fmt::Display; use serde::{Deserialize, Deserializer, Serialize}; #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum ServiceAcceptType { DIDCommV1, DIDCommV2, Other(String), } impl From<&str> for ServiceAcceptType { fn from(s: &str) -> Self { match s { "didcomm/aip2;env=rfc19" => ServiceAcceptType::DIDCommV1, "didcomm/v2" => ServiceAcceptType::DIDCommV2, _ => ServiceAcceptType::Other(s.to_string()), } } } impl Display for ServiceAcceptType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ServiceAcceptType::DIDCommV1 => write!(f, "didcomm/aip2;env=rfc19"), ServiceAcceptType::DIDCommV2 => write!(f, "didcomm/v2"), ServiceAcceptType::Other(other) => write!(f, "{other}"), } } } impl<'de> Deserialize<'de> for ServiceAcceptType { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; match s.as_str() { "didcomm/aip2;env=rfc19" => Ok(ServiceAcceptType::DIDCommV1), "didcomm/v2" => Ok(ServiceAcceptType::DIDCommV2), _ => Ok(ServiceAcceptType::Other(s)), } } } impl Serialize for ServiceAcceptType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match self { ServiceAcceptType::DIDCommV1 => serializer.serialize_str("didcomm/aip2;env=rfc19"), ServiceAcceptType::DIDCommV2 => serializer.serialize_str("didcomm/v2"), ServiceAcceptType::Other(other) => serializer.serialize_str(other), } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/service/typed/aip1.rs
did_core/did_doc/src/schema/service/typed/aip1.rs
use display_as_json::Display; use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default, Display, TypedBuilder)] #[serde(deny_unknown_fields)] pub struct ExtraFieldsAIP1 {}
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/service/typed/mod.rs
did_core/did_doc/src/schema/service/typed/mod.rs
pub mod aip1; pub mod didcommv1; pub mod didcommv2; pub mod legacy; use std::{fmt::Display, str::FromStr}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use url::Url; use crate::{error::DidDocumentBuilderError, schema::types::uri::Uri}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub(crate) struct TypedService<E> { id: Uri, #[serde(rename = "type")] service_type: ServiceType, service_endpoint: Url, #[serde(flatten)] extra: E, } impl<E> TypedService<E> { pub fn id(&self) -> &Uri { &self.id } pub fn service_endpoint(&self) -> &Url { &self.service_endpoint } pub fn extra(&self) -> &E { &self.extra } } const SERVICE_TYPE_AIP1: &str = "endpoint"; const SERVICE_TYPE_DIDCOMMV1: &str = "did-communication"; const SERVICE_TYPE_DIDCOMMV2: &str = "DIDCommMessaging"; const SERVICE_TYPE_LEGACY: &str = "IndyAgent"; #[derive(Clone, Debug, PartialEq)] pub enum ServiceType { AIP1, DIDCommV1, DIDCommV2, Legacy, Other(String), } impl FromStr for ServiceType { type Err = DidDocumentBuilderError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { SERVICE_TYPE_AIP1 => Ok(ServiceType::AIP1), SERVICE_TYPE_DIDCOMMV1 => Ok(ServiceType::DIDCommV1), SERVICE_TYPE_DIDCOMMV2 => Ok(ServiceType::DIDCommV2), SERVICE_TYPE_LEGACY => Ok(ServiceType::Legacy), _ => Ok(ServiceType::Other(s.to_owned())), } } } impl<'de> Deserialize<'de> for ServiceType { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; s.parse().map_err(de::Error::custom) } } impl Display for ServiceType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ServiceType::AIP1 => write!(f, "endpoint"), ServiceType::DIDCommV1 => write!(f, "did-communication"), // Interop note: AFJ useses DIDComm, Acapy uses DIDCommMessaging // Not matching spec: // * did:sov method - https://sovrin-foundation.github.io/sovrin/spec/did-method-spec-template.html#crud-operation-definitions // Matching spec: // * did:peer method - https://identity.foundation/peer-did-method-spec/#multi-key-creation // * did core - https://www.w3.org/TR/did-spec-registries/#didcommmessaging // * didcommv2 - https://identity.foundation/didcomm-messaging/spec/#service-endpoint ServiceType::DIDCommV2 => write!(f, "DIDCommMessaging"), ServiceType::Legacy => write!(f, "IndyAgent"), ServiceType::Other(other) => write!(f, "{other}"), } } } impl Serialize for ServiceType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { ServiceType::AIP1 => serializer.serialize_str(SERVICE_TYPE_AIP1), ServiceType::DIDCommV1 => serializer.serialize_str(SERVICE_TYPE_DIDCOMMV1), ServiceType::DIDCommV2 => serializer.serialize_str(SERVICE_TYPE_DIDCOMMV2), ServiceType::Legacy => serializer.serialize_str(SERVICE_TYPE_LEGACY), ServiceType::Other(ref value) => serializer.serialize_str(value), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_service_type_serialize() { let service_type = ServiceType::AIP1; let serialized = serde_json::to_string(&service_type).unwrap(); assert_eq!(serialized, "\"endpoint\""); let service_type = ServiceType::DIDCommV1; let serialized = serde_json::to_string(&service_type).unwrap(); assert_eq!(serialized, "\"did-communication\""); let service_type = ServiceType::DIDCommV2; let serialized = serde_json::to_string(&service_type).unwrap(); assert_eq!(serialized, "\"DIDCommMessaging\""); let service_type = ServiceType::Legacy; let serialized = serde_json::to_string(&service_type).unwrap(); assert_eq!(serialized, "\"IndyAgent\""); let service_type = ServiceType::Other("foobar".to_string()); let serialized = serde_json::to_string(&service_type).unwrap(); assert_eq!(serialized, "\"foobar\""); } #[test] fn test_service_type_deserialize() { let deserialized: ServiceType = serde_json::from_str("\"endpoint\"").unwrap(); assert_eq!(deserialized, ServiceType::AIP1); let deserialized: ServiceType = serde_json::from_str("\"did-communication\"").unwrap(); assert_eq!(deserialized, ServiceType::DIDCommV1); let deserialized: ServiceType = serde_json::from_str("\"DIDCommMessaging\"").unwrap(); assert_eq!(deserialized, ServiceType::DIDCommV2); let deserialized: ServiceType = serde_json::from_str("\"IndyAgent\"").unwrap(); assert_eq!(deserialized, ServiceType::Legacy); let deserialized: ServiceType = serde_json::from_str("\"foobar\"").unwrap(); assert_eq!(deserialized, ServiceType::Other("foobar".to_string())); } #[test] fn test_service_from_unquoted_string() { let service = ServiceType::from_str("endpoint").unwrap(); assert_eq!(service, ServiceType::AIP1); let service = ServiceType::from_str("did-communication").unwrap(); assert_eq!(service, ServiceType::DIDCommV1); let service = ServiceType::from_str("DIDCommMessaging").unwrap(); assert_eq!(service, ServiceType::DIDCommV2); let service = ServiceType::from_str("IndyAgent").unwrap(); assert_eq!(service, ServiceType::Legacy); let service = ServiceType::from_str("foobar").unwrap(); assert_eq!(service, ServiceType::Other("foobar".to_string())); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/service/typed/didcommv2.rs
did_core/did_doc/src/schema/service/typed/didcommv2.rs
use display_as_json::Display; use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; use url::Url; use crate::schema::{ service::{ service_accept_type::ServiceAcceptType, service_key_kind::ServiceKeyKind, typed::{ServiceType, TypedService}, }, types::uri::Uri, }; #[derive(Serialize, Clone, Debug, PartialEq)] pub struct ServiceDidCommV2 { #[serde(flatten)] service: TypedService<ExtraFieldsDidCommV2>, } impl ServiceDidCommV2 { pub fn new( id: Uri, service_endpoint: Url, routing_keys: Vec<ServiceKeyKind>, accept: Vec<ServiceAcceptType>, ) -> Self { let extra: ExtraFieldsDidCommV2 = ExtraFieldsDidCommV2::builder() .routing_keys(routing_keys) .accept(accept) .build(); Self { service: TypedService::<ExtraFieldsDidCommV2> { id, service_type: ServiceType::DIDCommV2, service_endpoint, extra, }, } } pub fn id(&self) -> &Uri { self.service.id() } pub fn service_endpoint(&self) -> Url { self.service.service_endpoint().clone() } pub fn extra(&self) -> &ExtraFieldsDidCommV2 { self.service.extra() } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default, Display, TypedBuilder)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] pub struct ExtraFieldsDidCommV2 { #[serde(skip_serializing_if = "Vec::is_empty")] routing_keys: Vec<ServiceKeyKind>, #[serde(default)] accept: Vec<ServiceAcceptType>, } impl ExtraFieldsDidCommV2 { pub fn routing_keys(&self) -> &[ServiceKeyKind] { self.routing_keys.as_ref() } pub fn accept(&self) -> &[ServiceAcceptType] { self.accept.as_ref() } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/service/typed/legacy.rs
did_core/did_doc/src/schema/service/typed/legacy.rs
use display_as_json::Display; use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; use crate::schema::service::service_key_kind::ServiceKeyKind; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default, Display, TypedBuilder)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] pub struct ExtraFieldsLegacy { #[serde(default)] priority: u32, #[serde(default)] recipient_keys: Vec<ServiceKeyKind>, #[serde(default)] routing_keys: Vec<ServiceKeyKind>, } impl ExtraFieldsLegacy { pub fn recipient_keys(&self) -> &[ServiceKeyKind] { self.recipient_keys.as_ref() } pub fn routing_keys(&self) -> &[ServiceKeyKind] { self.routing_keys.as_ref() } pub fn priority(&self) -> u32 { self.priority } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/service/typed/didcommv1.rs
did_core/did_doc/src/schema/service/typed/didcommv1.rs
use std::collections::HashMap; use display_as_json::Display; use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; use url::Url; use crate::{ error::DidDocumentBuilderError, schema::{ service::{ service_accept_type::ServiceAcceptType, service_key_kind::ServiceKeyKind, typed::{ServiceType, TypedService}, Service, }, types::uri::Uri, utils::OneOrList, }, }; #[derive(Serialize, Clone, Debug, PartialEq)] pub struct ServiceDidCommV1 { #[serde(flatten)] service: TypedService<ExtraFieldsDidCommV1>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default, Display, TypedBuilder)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] pub struct ExtraFieldsDidCommV1 { priority: u32, recipient_keys: Vec<ServiceKeyKind>, routing_keys: Vec<ServiceKeyKind>, #[serde(default)] accept: Vec<ServiceAcceptType>, } impl ServiceDidCommV1 { pub fn new( id: Uri, service_endpoint: Url, priority: u32, recipient_keys: Vec<ServiceKeyKind>, routing_keys: Vec<ServiceKeyKind>, ) -> Self { let extra = ExtraFieldsDidCommV1::builder() .priority(priority) .recipient_keys(recipient_keys) .routing_keys(routing_keys) .accept(vec![ServiceAcceptType::DIDCommV1]) .build(); Self { service: TypedService::<ExtraFieldsDidCommV1> { id, service_type: ServiceType::DIDCommV1, service_endpoint, extra, }, } } pub fn id(&self) -> &Uri { self.service.id() } pub fn service_endpoint(&self) -> Url { self.service.service_endpoint().clone() } pub fn extra(&self) -> &ExtraFieldsDidCommV1 { self.service.extra() } } impl TryFrom<ServiceDidCommV1> for Service { type Error = DidDocumentBuilderError; fn try_from(did_comm_service: ServiceDidCommV1) -> Result<Self, Self::Error> { let mut extra_fields = HashMap::new(); extra_fields.insert( "priority".to_string(), serde_json::Value::from(did_comm_service.extra().priority()), ); extra_fields.insert( "recipientKeys".to_string(), serde_json::to_value(did_comm_service.extra().recipient_keys())?, ); extra_fields.insert( "routingKeys".to_string(), serde_json::to_value(did_comm_service.extra().routing_keys())?, ); extra_fields.insert( "accept".to_string(), serde_json::to_value(did_comm_service.extra().accept())?, ); Ok(Service::new( did_comm_service.id().clone(), did_comm_service.service_endpoint(), OneOrList::One(ServiceType::DIDCommV1), extra_fields, )) } } impl ExtraFieldsDidCommV1 { pub fn priority(&self) -> u32 { self.priority } pub fn recipient_keys(&self) -> &[ServiceKeyKind] { self.recipient_keys.as_ref() } pub fn routing_keys(&self) -> &[ServiceKeyKind] { self.routing_keys.as_ref() } pub fn accept(&self) -> &[ServiceAcceptType] { self.accept.as_ref() } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/utils/error.rs
did_core/did_doc/src/schema/utils/error.rs
use std::fmt::{self, Display, Formatter}; use thiserror::Error; #[derive(Debug, Error)] pub struct DidDocumentLookupError { reason: String, } impl DidDocumentLookupError { pub fn new(reason: String) -> Self { Self { reason } } } impl Display for DidDocumentLookupError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "DiddocLookupError: {}", self.reason) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/utils/mod.rs
did_core/did_doc/src/schema/utils/mod.rs
pub mod error; use std::fmt::{Debug, Display}; use serde::{Deserialize, Serialize}; use crate::schema::{ did_doc::DidDocument, service::{typed::ServiceType, Service}, types::uri::Uri, utils::error::DidDocumentLookupError, verification_method::{VerificationMethod, VerificationMethodKind, VerificationMethodType}, }; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(untagged)] pub enum OneOrList<T> { One(T), List(Vec<T>), } impl<T> From<Vec<T>> for OneOrList<T> { fn from(mut value: Vec<T>) -> Self { match value.len() { 1 => OneOrList::One(value.remove(0)), _ => OneOrList::List(value), } } } impl OneOrList<String> { pub fn first(&self) -> Option<String> { match self { OneOrList::One(s) => Some(s.clone()), OneOrList::List(s) => s.first().cloned(), } } } impl<T: Display + Debug> Display for OneOrList<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { OneOrList::One(t) => write!(f, "{t}"), OneOrList::List(t) => write!(f, "{t:?}"), } } } impl DidDocument { pub fn get_key_agreement_of_type( &self, key_types: &[VerificationMethodType], ) -> Result<VerificationMethod, DidDocumentLookupError> { for verification_method_kind in self.key_agreement() { let verification_method = match verification_method_kind { VerificationMethodKind::Resolved(verification_method) => verification_method, VerificationMethodKind::Resolvable(reference) => { match self.dereference_key(reference) { None => { return Err(DidDocumentLookupError::new(format!( "Unable to resolve key agreement key by reference: {reference}" ))) } Some(verification_method) => verification_method, } } }; for key_type in key_types { if verification_method.verification_method_type() == key_type { return Ok(verification_method.clone()); } } } Err(DidDocumentLookupError::new( "No supported key_agreement keys have been found".to_string(), )) } pub fn get_service_of_type( &self, service_type: &ServiceType, ) -> Result<Service, DidDocumentLookupError> { self.service() .iter() .find(|service| service.service_types().contains(service_type)) .cloned() .ok_or(DidDocumentLookupError::new(format!( "Failed to look up service object by type {service_type}" ))) } pub fn get_service_by_id(&self, id: &Uri) -> Result<Service, DidDocumentLookupError> { self.service() .iter() .find(|service| service.id() == id) .cloned() .ok_or(DidDocumentLookupError::new(format!( "Failed to look up service object by id {id}" ))) } } #[cfg(test)] mod tests { use super::*; use crate::schema::verification_method::VerificationMethodType; const DID_DOC: &str = r##" { "@context": [ "https://w3.org/ns/did/v1", "https://w3id.org/security/suites/ed25519-2018/v1" ], "id": "did:web:did-actor-alice", "alsoKnownAs": [ "https://example.com/user-profile/123" ], "keyAgreement": [ { "id": "#foo", "type": "Bls12381G2Key2020", "controller": "did:web:did-actor-alice", "publicKeyBase58": "CaSHXEvLKS6SfN9aBfkVGBpp15jSnaHazqHgLHp8KZ3Y" }, { "id": "#bar", "type": "X25519KeyAgreementKey2020", "controller": "did:web:did-actor-alice", "publicKeyBase58": "CaSHXEvLKS6SfN9aBfkVGBpp15jSnaHazqHgLHp8KZ3Y" } ] } "##; #[test] fn should_resolve_key_agreement() { let did_document: DidDocument = serde_json::from_str(DID_DOC).unwrap(); let methods = &[ VerificationMethodType::Ed25519VerificationKey2020, VerificationMethodType::X25519KeyAgreementKey2020, ]; let key = did_document.get_key_agreement_of_type(methods).unwrap(); assert_eq!(key.id().to_string(), "#bar") } #[test] fn should_not_resolve_key_agreement() { let did_document: DidDocument = serde_json::from_str(DID_DOC).unwrap(); let methods = &[VerificationMethodType::Bls12381G1Key2020]; let err = did_document .get_key_agreement_of_type(methods) .expect_err("expected error"); assert!(err .to_string() .contains("No supported key_agreement keys have been found")) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/types/multibase.rs
did_core/did_doc/src/schema/types/multibase.rs
use std::{ error::Error, fmt::{self, Display, Formatter}, str::FromStr, }; use multibase::decode; use serde::{Deserialize, Serialize}; use thiserror::Error; #[derive(Debug, Error)] pub struct MultibaseWrapperError { reason: &'static str, #[source] source: Box<dyn Error + Sync + Send>, } impl Display for MultibaseWrapperError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!( f, "MultibaseWrapperError, reason: {}, source: {}", self.reason, self.source ) } } // https://datatracker.ietf.org/doc/html/draft-multiformats-multibase-07 #[derive(Clone, Debug, PartialEq)] pub struct Multibase { base: multibase::Base, bytes: Vec<u8>, } impl Multibase { pub fn new(multibase: String) -> Result<Self, MultibaseWrapperError> { let (base, bytes) = decode(multibase).map_err(|err| MultibaseWrapperError { reason: "Decoding multibase value failed", source: Box::new(err), })?; Ok(Self { base, bytes }) } pub fn base_to_multibase(base: multibase::Base, encoded: &str) -> Self { let multibase_encoded = format!("{}{}", base.code(), encoded); Self { base, bytes: multibase_encoded.as_bytes().to_vec(), } } } impl Serialize for Multibase { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(&self.base.encode(&self.bytes)) } } impl<'de> Deserialize<'de> for Multibase { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let s = String::deserialize(deserializer)?; Self::new(s).map_err(serde::de::Error::custom) } } impl FromStr for Multibase { type Err = MultibaseWrapperError; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::new(s.to_string()) } } impl Display for Multibase { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.base.encode(&self.bytes)) } } impl AsRef<[u8]> for Multibase { fn as_ref(&self) -> &[u8] { &self.bytes } } #[cfg(test)] mod tests { use multibase::Base::Base58Btc; use super::*; #[test] fn test_multibase_new_valid() { let multibase = Multibase::new("zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e".to_string()); assert!(multibase.is_ok()); } #[test] fn test_multibase_new_invalid() { let multibase = Multibase::new("invalidmultibasekey".to_string()); assert!(multibase.is_err()); } #[test] fn test_multibase_deserialize_valid() { let multibase: Multibase = serde_json::from_str("\"zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e\"").unwrap(); assert_eq!( multibase, Multibase { base: Base58Btc, bytes: decode("zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e") .unwrap() .1 } ) } #[test] fn test_multibase_deserialize_invalid() { let multibase: Result<Multibase, _> = serde_json::from_str("\"invalidmultibasekey\""); assert!(multibase.is_err()); } #[test] fn test_multibase_from_str_valid() { let multibase = "zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e".parse::<Multibase>(); assert!(multibase.is_ok()); } #[test] fn test_multibase_from_str_invalid() { let multibase = "invalidmultibasekey".parse::<Multibase>(); let err = multibase.expect_err("Error was expected."); assert!(err .source() .expect("Error was expected to has source set up.") .is::<multibase::Error>()); assert!(err .to_string() .contains("Decoding multibase value failed, source: ")); } #[test] fn test_multibase_to_string() { let multibase = Multibase::new("zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e".to_string()).unwrap(); assert_eq!( multibase.to_string(), "QmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e" ); } #[test] fn test_base_to_multibase() { let multibase = Multibase::base_to_multibase( Base58Btc, "QmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e", ); assert_eq!( multibase, Multibase { base: Base58Btc, bytes: "zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e" .as_bytes() .to_vec() } ) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/types/uri.rs
did_core/did_doc/src/schema/types/uri.rs
use std::{ fmt::{self, Display, Formatter}, str::FromStr, }; use serde::{Deserialize, Serialize}; use thiserror::Error; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct Uri(uniresid::Uri); #[derive(Debug, Error)] pub struct UriWrapperError { reason: uniresid::Error, } impl Display for UriWrapperError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "UriWrapperError: {}", self.reason) } } impl Uri { pub fn new(uri: &str) -> Result<Self, UriWrapperError> { Ok(Self( uniresid::Uri::try_from(uri).map_err(|e| UriWrapperError { reason: e })?, )) } } impl FromStr for Uri { type Err = UriWrapperError; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::new(s) } } impl Display for Uri { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl AsRef<uniresid::Uri> for Uri { fn as_ref(&self) -> &uniresid::Uri { &self.0 } } #[cfg(test)] mod tests { use super::*; #[test] fn test_uri_new_valid() { let uri = Uri::new("http://example.com"); assert!(uri.is_ok()); } #[test] fn test_uri_new_invalid() { let uri = Uri::new(r"http:\\example.com\index.html"); assert!(uri.is_err()); } #[test] fn test_uri_from_str_valid() { let uri = Uri::from_str("http://example.com"); assert!(uri.is_ok()); } #[test] fn test_uri_from_str_invalid() { let uri = Uri::from_str( r"http:\\example.com\index.html ", ); assert!(uri.is_err()); } #[test] fn test_uri_clone() { let uri_str = "http://example.com"; let uri = Uri::from_str(uri_str).unwrap(); assert_eq!(uri, uri.clone()); } #[test] fn test_uri_partial_eq() { let uri1 = Uri::from_str("http://example.com").unwrap(); let uri2 = Uri::from_str("http://example.com").unwrap(); let uri3 = Uri::from_str("http://different.com").unwrap(); assert_eq!(uri1, uri2); assert_ne!(uri1, uri3); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/types/mod.rs
did_core/did_doc/src/schema/types/mod.rs
pub mod jsonwebkey; pub mod multibase; pub mod uri;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/types/jsonwebkey.rs
did_core/did_doc/src/schema/types/jsonwebkey.rs
use std::{ collections::HashMap, error::Error, fmt::{self, Display, Formatter}, str::FromStr, }; use serde::{Deserialize, Serialize}; use serde_json::Value; use thiserror::Error; #[derive(Debug, Error)] pub struct JsonWebKeyError { reason: &'static str, #[source] source: Box<dyn Error + Sync + Send>, } impl Display for JsonWebKeyError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!( f, "JsonWebKeyError, reason: {}, source: {}", self.reason, self.source ) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] // TODO: Introduce proper custom type // Unfortunately only supports curves from the original RFC // pub struct JsonWebKey(jsonwebkey::JsonWebKey); pub struct JsonWebKey { pub kty: String, pub crv: String, pub x: String, #[serde(flatten)] #[serde(skip_serializing_if = "HashMap::is_empty")] #[serde(default)] pub extra: HashMap<String, Value>, } impl JsonWebKey { // todo: More future-proof way would be creating custom error type, but seems as overkill atm? pub fn new(jwk: &str) -> Result<Self, JsonWebKeyError> { serde_json::from_str(jwk).map_err(|err| JsonWebKeyError { reason: "Parsing JWK failed", source: Box::new(err), }) } } impl FromStr for JsonWebKey { type Err = JsonWebKeyError; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::new(s) } } impl Display for JsonWebKey { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", serde_json::to_string(&self).unwrap()) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/verification_method/public_key.rs
did_core/did_doc/src/schema/verification_method/public_key.rs
use base64::{engine::general_purpose, Engine}; use public_key::Key; use serde::{Deserialize, Serialize}; use crate::schema::{types::jsonwebkey::JsonWebKey, verification_method::error::KeyDecodingError}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(untagged)] #[serde(deny_unknown_fields)] pub enum PublicKeyField { #[serde(rename_all = "camelCase")] Multibase { public_key_multibase: String }, #[serde(rename_all = "camelCase")] Jwk { public_key_jwk: JsonWebKey }, #[serde(rename_all = "camelCase")] Base58 { public_key_base58: String }, #[serde(rename_all = "camelCase")] Base64 { public_key_base64: String }, #[serde(rename_all = "camelCase")] Hex { public_key_hex: String }, #[serde(rename_all = "camelCase")] Pem { public_key_pem: String }, #[serde(rename_all = "camelCase")] Pgp { public_key_pgp: String }, } impl PublicKeyField { pub fn key_decoded(&self) -> Result<Vec<u8>, KeyDecodingError> { match self { PublicKeyField::Multibase { public_key_multibase, } => { let key = Key::from_fingerprint(public_key_multibase)?; Ok(key.key().to_vec()) } PublicKeyField::Base58 { public_key_base58 } => { Ok(bs58::decode(public_key_base58).into_vec()?) } PublicKeyField::Base64 { public_key_base64 } => { Ok(general_purpose::STANDARD_NO_PAD.decode(public_key_base64.as_bytes())?) } PublicKeyField::Hex { public_key_hex } => Ok(hex::decode(public_key_hex)?), PublicKeyField::Pem { public_key_pem } => { Ok(pem::parse(public_key_pem.as_bytes())?.contents().to_vec()) } PublicKeyField::Jwk { public_key_jwk: _ } => Err(KeyDecodingError::new( "JWK public key decoding not supported", )), PublicKeyField::Pgp { public_key_pgp: _ } => Err(KeyDecodingError::new( "PGP public key decoding not supported", )), } } // TODO: Other formats pub fn base58(&self) -> Result<String, KeyDecodingError> { Ok(bs58::encode(self.key_decoded()?).into_string()) } } #[cfg(test)] mod tests { use std::error::Error; use super::*; static PUBLIC_KEY_MULTIBASE: &str = "z6LSbysY2xFMRpGMhb7tFTLMpeuPRaqaWM1yECx2AtzE3KCc"; static PUBLIC_KEY_BASE58: &str = "JhNWeSVLMYccCk7iopQW4guaSJTojqpMEELgSLhKwRr"; static PUBLIC_KEY_BASE64: &str = "BIiFcQEn3dfvB2pjlhOQQour6jXy9d5s2FKEJNTOJik"; static PUBLIC_KEY_HEX: &str = "048885710127ddd7ef076a63961390428babea35f2f5de6cd8528424d4ce2629"; static PUBLIC_KEY_BYTES: [u8; 32] = [ 4, 136, 133, 113, 1, 39, 221, 215, 239, 7, 106, 99, 150, 19, 144, 66, 139, 171, 234, 53, 242, 245, 222, 108, 216, 82, 132, 36, 212, 206, 38, 41, ]; #[test] fn test_multibase() { let public_key_field = PublicKeyField::Multibase { public_key_multibase: PUBLIC_KEY_MULTIBASE.to_string(), }; assert_eq!(public_key_field.key_decoded().unwrap(), PUBLIC_KEY_BYTES); assert_eq!(public_key_field.base58().unwrap(), PUBLIC_KEY_BASE58); } #[test] fn test_base58() { let public_key_field = PublicKeyField::Base58 { public_key_base58: PUBLIC_KEY_BASE58.to_string(), }; assert_eq!( public_key_field.key_decoded().unwrap(), PUBLIC_KEY_BYTES.to_vec() ); } #[test] fn test_base64() { let public_key_field = PublicKeyField::Base64 { public_key_base64: PUBLIC_KEY_BASE64.to_string(), }; assert_eq!( public_key_field.key_decoded().unwrap(), PUBLIC_KEY_BYTES.to_vec() ); } #[test] fn test_hex() { let public_key_field = PublicKeyField::Hex { public_key_hex: PUBLIC_KEY_HEX.to_string(), }; assert_eq!( public_key_field.key_decoded().unwrap(), PUBLIC_KEY_BYTES.to_vec() ); } #[test] fn test_b58_fails() { let public_key_field = PublicKeyField::Base58 { public_key_base58: "abcdefghijkl".to_string(), }; let err = public_key_field.key_decoded().expect_err("Expected error"); println!("Error: {err}"); assert!(err .source() .expect("Error was expected to has source set up.") .is::<bs58::decode::Error>()); assert!(err.to_string().contains("Failed to decode base58")); } #[test] fn test_pem_fails() { let public_key_field = PublicKeyField::Pem { public_key_pem: "abcdefghijkl".to_string(), }; let err = public_key_field.key_decoded().unwrap_err(); println!("Error: {err}"); assert!(err .source() .expect("Error was expected to has source set up.") .is::<pem::PemError>()); assert!(err.to_string().contains("Failed to decode PEM")); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/verification_method/error.rs
did_core/did_doc/src/schema/verification_method/error.rs
use std::{ error::Error, fmt, fmt::{Display, Formatter}, }; use thiserror::Error; use crate::schema::types::{jsonwebkey::JsonWebKeyError, multibase::MultibaseWrapperError}; #[derive(Debug, Error)] pub struct KeyDecodingError { reason: &'static str, #[source] source: Option<Box<dyn Error + Sync + Send>>, } impl KeyDecodingError { pub fn new(reason: &'static str) -> Self { KeyDecodingError { reason, source: None, } } } impl Display for KeyDecodingError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match &self.source { Some(source) => write!( f, "KeyDecodingError, reason: {}, source: {}", self.reason, source ), None => write!(f, "KeyDecodingError, reason: {}", self.reason), } } } impl From<pem::PemError> for KeyDecodingError { fn from(error: pem::PemError) -> Self { KeyDecodingError { reason: "Failed to decode PEM", source: Some(Box::new(error)), } } } impl From<bs58::decode::Error> for KeyDecodingError { fn from(error: bs58::decode::Error) -> Self { KeyDecodingError { reason: "Failed to decode base58", source: Some(Box::new(error)), } } } impl From<base64::DecodeError> for KeyDecodingError { fn from(error: base64::DecodeError) -> Self { KeyDecodingError { reason: "Failed to decode base64", source: Some(Box::new(error)), } } } impl From<hex::FromHexError> for KeyDecodingError { fn from(error: hex::FromHexError) -> Self { KeyDecodingError { reason: "Failed to decode hex value", source: Some(Box::new(error)), } } } impl From<MultibaseWrapperError> for KeyDecodingError { fn from(error: MultibaseWrapperError) -> Self { KeyDecodingError { reason: "Failed to decode multibase value", source: Some(Box::new(error)), } } } impl From<JsonWebKeyError> for KeyDecodingError { fn from(error: JsonWebKeyError) -> Self { KeyDecodingError { reason: "Failed to decode JWK", source: Some(Box::new(error)), } } } impl From<public_key::PublicKeyError> for KeyDecodingError { fn from(error: public_key::PublicKeyError) -> Self { KeyDecodingError { reason: "Failed to decode multibase public key", source: Some(Box::new(error)), } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/verification_method/mod.rs
did_core/did_doc/src/schema/verification_method/mod.rs
pub mod error; pub mod public_key; mod verification_method_kind; mod verification_method_type; use ::public_key::Key; use did_parser_nom::{Did, DidUrl}; use serde::{Deserialize, Serialize}; use typed_builder::TypedBuilder; pub use verification_method_kind::VerificationMethodKind; pub use verification_method_type::VerificationMethodType; pub use self::public_key::PublicKeyField; use crate::error::DidDocumentBuilderError; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, TypedBuilder)] #[serde(rename_all = "camelCase")] pub struct VerificationMethod { id: DidUrl, controller: Did, #[serde(rename = "type")] verification_method_type: VerificationMethodType, #[serde(flatten)] public_key: PublicKeyField, } impl VerificationMethod { pub fn id(&self) -> &DidUrl { &self.id } pub fn controller(&self) -> &Did { &self.controller } pub fn verification_method_type(&self) -> &VerificationMethodType { &self.verification_method_type } pub fn public_key_field(&self) -> &PublicKeyField { &self.public_key } pub fn public_key(&self) -> Result<Key, DidDocumentBuilderError> { let key = match &self.public_key { PublicKeyField::Multibase { public_key_multibase, } => Key::from_fingerprint(public_key_multibase)?, #[cfg(feature = "jwk")] PublicKeyField::Jwk { public_key_jwk } => Key::from_jwk(&public_key_jwk.to_string())?, // TODO - FUTURE - other key types could do with some special handling, i.e. // those where the key_type is encoded within the key field (multibase, jwk, etc) _ => Key::new( self.public_key.key_decoded()?, self.verification_method_type.try_into()?, )?, }; Ok(key) } } #[cfg(test)] mod tests { use serde_json::Value; use super::*; fn create_valid_did() -> Did { Did::parse("did:example:123456789abcdefghi".to_string()).unwrap() } fn create_valid_did_url() -> DidUrl { DidUrl::parse("did:example:123456789abcdefghi#fragment".to_string()).unwrap() } fn create_valid_multibase() -> String { "zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e".to_string() } fn create_valid_verification_key_type() -> VerificationMethodType { VerificationMethodType::Ed25519VerificationKey2018 } fn create_valid_verification_method_value() -> Value { serde_json::json!({ "id": "did:example:123456789abcdefghi#key-1", "type": "Ed25519VerificationKey2018", "controller": "did:example:123456789abcdefghi", "publicKeyMultibase": "zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e" }) } fn create_verification_method_multiple_keys() -> Value { serde_json::json!({ "id": "did:example:123456789abcdefghi#key-1", "type": "Ed25519VerificationKey2018", "controller": "did:example:123456789abcdefghi", "publicKeyMultibase": "zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e", "publicKeyJwk": { "kty": "OKP", "crv": "Ed25519", "x": "zQmWvQxTqbG2Z9HPJgG57jjwR154cKhbtJenbyYTWkjgF3e" } }) } #[test] fn test_verification_method_builder() { let id = create_valid_did_url(); let controller = create_valid_did(); let verification_method_type = create_valid_verification_key_type(); let public_key_multibase = create_valid_multibase(); let vm = VerificationMethod::builder() .id(id.clone()) .controller(controller.clone()) .verification_method_type(verification_method_type) .public_key(PublicKeyField::Multibase { public_key_multibase, }) .build(); assert_eq!(vm.id(), &id); assert_eq!(vm.controller(), &controller); assert_eq!(vm.verification_method_type(), &verification_method_type); match vm.public_key_field() { PublicKeyField::Multibase { public_key_multibase, } => { assert_eq!(public_key_multibase, public_key_multibase) } _ => panic!("Expected public key to be multibase"), } } #[test] fn test_verification_method_deserialization() { let vm: Result<VerificationMethod, _> = serde_json::from_str( create_valid_verification_method_value() .to_string() .as_str(), ); assert!(vm.is_ok()); } #[test] fn test_verification_method_deserialization_fails_with_multiple_keys() { let vm: Result<VerificationMethod, _> = serde_json::from_str( create_verification_method_multiple_keys() .to_string() .as_str(), ); assert!(vm.is_err()); } } #[cfg(feature = "jwk")] #[cfg(test)] mod jwk_tests { use ::public_key::KeyType; use serde_json::json; use super::*; #[test] fn test_public_key_from_ed25519_jwk_vm() { let vm: VerificationMethod = serde_json::from_value(json!({ "id": "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH#z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH", "type": "Ed25519VerificationKey2018", "controller": "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH", "publicKeyJwk": { "kty": "OKP", "crv": "Ed25519", "x": "lJZrfAjkBXdfjebMHEUI9usidAPhAlssitLXR3OYxbI" } })).unwrap(); let pk = vm.public_key().unwrap(); assert!(matches!(pk.key_type(), KeyType::Ed25519)); assert_eq!( pk.fingerprint(), "z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH" ) } #[test] fn test_public_key_from_p256_jwk_vm() { let vm: VerificationMethod = serde_json::from_value(json!({ "id": "did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169#zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169", "type": "JsonWebKey2020", "controller": "did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169", "publicKeyJwk": { "kty": "EC", "crv": "P-256", "x": "fyNYMN0976ci7xqiSdag3buk-ZCwgXU4kz9XNkBlNUI", "y": "hW2ojTNfH7Jbi8--CJUo3OCbH3y5n91g-IMA9MLMbTU" } })).unwrap(); let pk = vm.public_key().unwrap(); assert!(matches!(pk.key_type(), KeyType::P256)); assert_eq!( pk.fingerprint(), "zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169" ) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/verification_method/verification_method_type.rs
did_core/did_doc/src/schema/verification_method/verification_method_type.rs
use std::fmt::Display; use public_key::KeyType; use serde::{Deserialize, Serialize}; use crate::{error::DidDocumentBuilderError, schema::contexts}; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum VerificationMethodType { /// https://w3id.org/security/suites/jws-2020/v1 JsonWebKey2020, /// https://w3id.org/security/suites/secp256k1-2019/v1 EcdsaSecp256k1VerificationKey2019, /// https://w3id.org/security/suites/ed25519-2018/v1 Ed25519VerificationKey2018, /// https://w3id.org/security/suites/ed25519-2020/v1 Ed25519VerificationKey2020, /// https://w3id.org/security/bbs/v1 Bls12381G1Key2020, /// https://w3id.org/security/bbs/v1 Bls12381G2Key2020, /// https://w3id.org/pgp/v1 PgpVerificationKey2021, /// https://w3id.org/security/suites/x25519-2019/v1 X25519KeyAgreementKey2019, /// https://w3id.org/security/suites/x25519-2020/v1 X25519KeyAgreementKey2020, /// https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld EcdsaSecp256k1RecoveryMethod2020, /// https://www.w3.org/TR/vc-data-integrity/#multikey /// https://w3id.org/security/multikey/v1 Multikey, } impl VerificationMethodType { /// Return the JSON-LD context URL for which this type comes from pub fn context_for_type(&self) -> &str { match self { VerificationMethodType::JsonWebKey2020 => contexts::W3C_SUITE_JWS_2020, VerificationMethodType::EcdsaSecp256k1VerificationKey2019 => { contexts::W3C_SUITE_SECP256K1_2019 } VerificationMethodType::Ed25519VerificationKey2018 => contexts::W3C_SUITE_ED25519_2018, VerificationMethodType::Ed25519VerificationKey2020 => contexts::W3C_SUITE_ED25519_2020, VerificationMethodType::Bls12381G1Key2020 => contexts::W3C_BBS_V1, VerificationMethodType::Bls12381G2Key2020 => contexts::W3C_BBS_V1, VerificationMethodType::PgpVerificationKey2021 => contexts::W3C_PGP_V1, VerificationMethodType::X25519KeyAgreementKey2019 => contexts::W3C_SUITE_X25519_2019, VerificationMethodType::X25519KeyAgreementKey2020 => contexts::W3C_SUITE_X25519_2020, VerificationMethodType::EcdsaSecp256k1RecoveryMethod2020 => { contexts::W3C_SUITE_SECP259K1_RECOVERY_2020 } VerificationMethodType::Multikey => contexts::W3C_MULTIKEY_V1, } } } impl Display for VerificationMethodType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { VerificationMethodType::JsonWebKey2020 => write!(f, "JsonWebKey2020"), VerificationMethodType::EcdsaSecp256k1VerificationKey2019 => { write!(f, "EcdsaSecp256k1VerificationKey2019") } VerificationMethodType::Ed25519VerificationKey2018 => { write!(f, "Ed25519VerificationKey2018") } VerificationMethodType::Ed25519VerificationKey2020 => { write!(f, "Ed25519VerificationKey2020") } VerificationMethodType::Bls12381G1Key2020 => write!(f, "Bls12381G1Key2020"), VerificationMethodType::Bls12381G2Key2020 => write!(f, "Bls12381G2Key2020"), VerificationMethodType::PgpVerificationKey2021 => write!(f, "PgpVerificationKey2021"), VerificationMethodType::X25519KeyAgreementKey2019 => { write!(f, "X25519KeyAgreementKey2019") } VerificationMethodType::X25519KeyAgreementKey2020 => { write!(f, "X25519KeyAgreementKey2020") } VerificationMethodType::EcdsaSecp256k1RecoveryMethod2020 => { write!(f, "EcdsaSecp256k1RecoveryMethod2020") } VerificationMethodType::Multikey => { write!(f, "Multikey") } } } } impl TryFrom<VerificationMethodType> for KeyType { type Error = DidDocumentBuilderError; fn try_from(value: VerificationMethodType) -> Result<Self, Self::Error> { match value { VerificationMethodType::Ed25519VerificationKey2018 | VerificationMethodType::Ed25519VerificationKey2020 => Ok(KeyType::Ed25519), VerificationMethodType::Bls12381G1Key2020 => Ok(KeyType::Bls12381g1), VerificationMethodType::Bls12381G2Key2020 => Ok(KeyType::Bls12381g2), VerificationMethodType::X25519KeyAgreementKey2019 | VerificationMethodType::X25519KeyAgreementKey2020 => Ok(KeyType::X25519), // The verification method type does not map directly to a key type. // This may occur when the VM type is a multikey (JsonWebKey, Multikey, etc) _ => Err(DidDocumentBuilderError::UnsupportedVerificationMethodType( value, )), } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_doc/src/schema/verification_method/verification_method_kind.rs
did_core/did_doc/src/schema/verification_method/verification_method_kind.rs
use did_parser_nom::DidUrl; use serde::{Deserialize, Serialize}; use super::VerificationMethod; // Either a set of verification methods maps or DID URLs // https://www.w3.org/TR/did-core/#did-document-properties #[allow(clippy::large_enum_variant)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(untagged)] pub enum VerificationMethodKind { Resolved(VerificationMethod), Resolvable(DidUrl), } impl VerificationMethodKind { /// Convenience function to try get the resolved enum variant (if it is that variant) pub fn resolved(&self) -> Option<&VerificationMethod> { match &self { VerificationMethodKind::Resolved(x) => Some(x), VerificationMethodKind::Resolvable(_) => None, } } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/lib.rs
did_core/did_methods/did_resolver_sov/src/lib.rs
pub extern crate did_resolver; pub mod dereferencing; pub mod error; pub mod reader; pub mod resolution; pub mod service;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/service.rs
did_core/did_methods/did_resolver_sov/src/service.rs
use std::{collections::HashSet, fmt::Display}; use serde::{Deserialize, Deserializer}; use url::Url; #[derive(Debug, Deserialize, Clone, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct EndpointDidSov { pub endpoint: Url, #[serde(default)] pub routing_keys: Vec<String>, #[serde( default = "default_didsov_service_types", deserialize_with = "deserialize_didsov_service_types" )] pub types: HashSet<DidSovServiceType>, } #[derive(Debug, Clone, Deserialize, PartialEq, Eq, Hash)] pub enum DidSovServiceType { #[serde(rename = "endpoint")] // AIP 1.0 Endpoint, #[serde(rename = "did-communication")] // AIP 2.0 DidCommunication, #[serde(rename = "DIDComm")] // DIDComm V2 DIDComm, #[serde(other)] Unknown, } impl Display for DidSovServiceType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { DidSovServiceType::Endpoint => write!(f, "endpoint"), DidSovServiceType::DidCommunication => write!(f, "did-communication"), DidSovServiceType::DIDComm => write!(f, "DIDComm"), DidSovServiceType::Unknown => write!(f, "Unknown"), } } } fn default_didsov_service_types() -> HashSet<DidSovServiceType> { vec![ DidSovServiceType::Endpoint, DidSovServiceType::DidCommunication, ] .into_iter() .collect() } fn deserialize_didsov_service_types<'de, D>( deserializer: D, ) -> Result<HashSet<DidSovServiceType>, D::Error> where D: Deserializer<'de>, { let mut types: HashSet<DidSovServiceType> = Deserialize::deserialize(deserializer)?; if types.is_empty() || types.iter().all(|t| *t == DidSovServiceType::Unknown) { types = default_didsov_service_types(); } else { types.retain(|t| *t != DidSovServiceType::Unknown); } Ok(types) } #[cfg(test)] mod tests { use std::iter::FromIterator; use serde_json::from_str; use super::*; #[test] fn test_deserialize_endpoint_did_sov() { let json = r#"{ "endpoint": "https://example.com", "routingKeys": ["key1", "key2"], "types": ["endpoint", "did-communication"] }"#; let endpoint_did_sov: EndpointDidSov = from_str(json).unwrap(); assert_eq!( endpoint_did_sov.endpoint, "https://example.com".parse().unwrap() ); assert_eq!(endpoint_did_sov.routing_keys, vec!["key1", "key2"]); assert_eq!( endpoint_did_sov.types, HashSet::from_iter(vec![ DidSovServiceType::Endpoint, DidSovServiceType::DidCommunication, ]) ); let json = r#"{ "endpoint": "https://example.com", "routingKeys": ["key1", "key2"], "types": ["endpoint", "DIDComm"] }"#; let endpoint_did_sov: EndpointDidSov = from_str(json).unwrap(); assert_eq!( endpoint_did_sov.endpoint, "https://example.com".parse().unwrap() ); assert_eq!(endpoint_did_sov.routing_keys, vec!["key1", "key2"]); assert_eq!( endpoint_did_sov.types, HashSet::from_iter(vec![ DidSovServiceType::Endpoint, DidSovServiceType::DIDComm, ]) ); let json = r#"{ "endpoint": "https://example.com", "routingKeys": ["key1", "key2"], "types": ["endpoint", "endpoint"] }"#; let endpoint_did_sov: EndpointDidSov = from_str(json).unwrap(); assert_eq!( endpoint_did_sov.endpoint, "https://example.com".parse().unwrap() ); assert_eq!(endpoint_did_sov.routing_keys, vec!["key1", "key2"]); assert_eq!( endpoint_did_sov.types, HashSet::from_iter(vec![DidSovServiceType::Endpoint,]) ); let json = r#"{ "endpoint": "https://example.com", "routingKeys": ["key1", "key2"], "types": ["invalid"] }"#; let endpoint_did_sov: EndpointDidSov = from_str(json).unwrap(); assert_eq!( endpoint_did_sov.endpoint, "https://example.com".parse().unwrap() ); assert_eq!(endpoint_did_sov.routing_keys, vec!["key1", "key2"]); assert_eq!(endpoint_did_sov.types, default_didsov_service_types()); let json = r#"{ "endpoint": "https://example.com", "routingKeys": ["key1", "key2"] }"#; let endpoint_did_sov: EndpointDidSov = from_str(json).unwrap(); assert_eq!( endpoint_did_sov.endpoint, "https://example.com".parse().unwrap() ); assert_eq!(endpoint_did_sov.routing_keys, vec!["key1", "key2"]); assert_eq!(endpoint_did_sov.types, default_didsov_service_types()); let json = r#"{ "endpoint": "https://example.com" }"#; let endpoint_did_sov: EndpointDidSov = from_str(json).unwrap(); assert_eq!( endpoint_did_sov.endpoint, "https://example.com".parse().unwrap() ); assert!(endpoint_did_sov.routing_keys.is_empty()); assert_eq!(endpoint_did_sov.types, default_didsov_service_types()); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/error/resolution.rs
did_core/did_methods/did_resolver_sov/src/error/resolution.rs
use did_resolver::traits::resolvable::{ resolution_error::DidResolutionError, resolution_metadata::DidResolutionMetadata, }; use super::DidSovError; impl From<&DidSovError> for DidResolutionError { fn from(err: &DidSovError) -> Self { match err { DidSovError::NotFound(_) => DidResolutionError::NotFound, DidSovError::MethodNotSupported(_) => DidResolutionError::MethodNotSupported, _ => DidResolutionError::InternalError, } } } impl From<&DidSovError> for DidResolutionMetadata { fn from(err: &DidSovError) -> Self { DidResolutionMetadata::builder().error(err.into()).build() } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/error/mod.rs
did_core/did_methods/did_resolver_sov/src/error/mod.rs
pub mod parsing; mod resolution; use aries_vcx_ledger::errors::error::VcxLedgerError; use did_resolver::did_doc::{error::DidDocumentBuilderError, schema::types::uri::UriWrapperError}; use thiserror::Error; use self::parsing::ParsingErrorSource; use crate::error::DidSovError::ParsingError; // TODO: DIDDocumentBuilderError should do key validation and the error // should me mapped accordingly // TODO: Perhaps split into input errors and external errors? #[derive(Error, Debug)] #[non_exhaustive] pub enum DidSovError { #[error("Not found: {0}")] NotFound(String), #[error("DID method not supported: {0}")] MethodNotSupported(String), #[error("Representation not supported: {0}")] RepresentationNotSupported(String), #[error("Internal error")] InternalError, #[error("Invalid DID {0}")] InvalidDid(String), #[error("AriesVCX Ledger error: {0}")] AriesVcxLedgerError(#[from] VcxLedgerError), #[error("DID Document Builder Error: {0}")] DidDocumentBuilderError(#[from] DidDocumentBuilderError), #[error("Parsing error: {0}")] ParsingError(#[from] ParsingErrorSource), #[error("Invalid configuration: {0}")] InvalidConfiguration(String), #[error(transparent)] Other(#[from] Box<dyn std::error::Error + Send + Sync>), } impl From<UriWrapperError> for DidSovError { fn from(error: UriWrapperError) -> Self { ParsingError(ParsingErrorSource::DidDocumentParsingUriError(error)) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/error/parsing.rs
did_core/did_methods/did_resolver_sov/src/error/parsing.rs
use did_resolver::{did_doc::schema::types::uri::UriWrapperError, did_parser_nom}; use thiserror::Error; use super::DidSovError; #[derive(Error, Debug)] pub enum ParsingErrorSource { #[error("DID document parsing error: {0}")] DidDocumentParsingError(#[from] did_parser_nom::ParseError), #[error("DID document parsing URI error: {0}")] DidDocumentParsingUriError(#[from] UriWrapperError), #[error("Serde error: {0}")] SerdeError(#[from] serde_json::Error), #[error("Ledger response parsing error: {0}")] LedgerResponseParsingError(String), } impl From<did_parser_nom::ParseError> for DidSovError { fn from(error: did_parser_nom::ParseError) -> Self { DidSovError::ParsingError(ParsingErrorSource::DidDocumentParsingError(error)) } } impl From<serde_json::Error> for DidSovError { fn from(error: serde_json::Error) -> Self { DidSovError::ParsingError(ParsingErrorSource::SerdeError(error)) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/reader/mod.rs
did_core/did_methods/did_resolver_sov/src/reader/mod.rs
use aries_vcx_ledger::ledger::base_ledger::IndyLedgerRead; use async_trait::async_trait; use did_resolver::did_parser_nom::Did; use crate::error::DidSovError; #[async_trait] #[cfg_attr(test, mockall::automock)] pub trait AttrReader: Send + Sync { async fn get_attr(&self, target_did: &Did, attr_name: &str) -> Result<String, DidSovError>; async fn get_nym(&self, did: &Did) -> Result<String, DidSovError>; } #[async_trait] impl<S> AttrReader for S where S: IndyLedgerRead + ?Sized, { async fn get_attr(&self, target_did: &Did, attr_name: &str) -> Result<String, DidSovError> { IndyLedgerRead::get_attr(self, target_did, attr_name) .await .map_err(|err| err.into()) } async fn get_nym(&self, did: &Did) -> Result<String, DidSovError> { IndyLedgerRead::get_nym(self, did) .await .map_err(|err| err.into()) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/dereferencing/utils.rs
did_core/did_methods/did_resolver_sov/src/dereferencing/utils.rs
use std::io::Cursor; use did_resolver::{ did_doc::schema::{ did_doc::DidDocument, service::Service, verification_method::VerificationMethod, }, did_parser_nom::DidUrl, traits::{ dereferenceable::{ dereferencing_metadata::DidDereferencingMetadata, dereferencing_output::DidDereferencingOutput, }, resolvable::resolution_output::DidResolutionOutput, }, }; use crate::error::DidSovError; pub fn service_by_id<F>(services: &[Service], predicate: F) -> Option<&Service> where F: Fn(&str) -> bool, { services.iter().find(|svc| predicate(svc.id().as_ref())) } pub fn verification_by_id<F>( authentications: &[VerificationMethod], predicate: F, ) -> Option<&VerificationMethod> where F: Fn(&str) -> bool, { authentications .iter() .find(|auth| predicate(auth.id().did_url())) } fn content_stream_from( did_document: &DidDocument, did_url: &DidUrl, ) -> Result<Cursor<Vec<u8>>, DidSovError> { let fragment = did_url.fragment().ok_or_else(|| { DidSovError::InvalidDid(format!("No fragment provided in the DID URL {did_url}")) })?; let did_url_string = did_url.to_string(); let fragment_string = format!("#{fragment}"); let id_matcher = |id: &str| id == did_url_string || id.ends_with(&fragment_string); let value = match ( service_by_id(did_document.service(), id_matcher), verification_by_id(did_document.verification_method(), id_matcher), ) { (Some(service), None) => serde_json::to_value(service)?, (None, Some(authentication)) => serde_json::to_value(authentication)?, (None, None) => { return Err(DidSovError::NotFound(format!( "Fragment '{fragment}' not found in the DID document" ))); } (Some(_), Some(_)) => { return Err(DidSovError::InvalidDid(format!( "Fragment '{fragment}' is ambiguous" ))); } }; Ok(Cursor::new(value.to_string().into_bytes())) } // TODO: Currently, only fragment dereferencing is supported pub(crate) fn dereference_did_document( resolution_output: &DidResolutionOutput, did_url: &DidUrl, ) -> Result<DidDereferencingOutput<Cursor<Vec<u8>>>, DidSovError> { let content_stream = content_stream_from(&resolution_output.did_document, did_url)?; let content_metadata = resolution_output.did_document_metadata.clone(); let dereferencing_metadata = DidDereferencingMetadata::builder() .content_type("application/did+json".to_string()) .build(); Ok(DidDereferencingOutput::builder(content_stream) .content_metadata(content_metadata) .dereferencing_metadata(dereferencing_metadata) .build()) } #[cfg(test)] mod tests { use did_resolver::{ did_doc::schema::{ service::typed::ServiceType, utils::OneOrList, verification_method::{PublicKeyField, VerificationMethodType}, }, did_parser_nom::DidUrl, traits::resolvable::resolution_output::DidResolutionOutput, }; use serde_json::Value; use super::*; fn example_did_document() -> DidDocument { let verification_method = VerificationMethod::builder() .id(DidUrl::parse("did:example:123456789abcdefghi#keys-1".to_string()).unwrap()) .controller("did:example:123456789abcdefghi".parse().unwrap()) .verification_method_type(VerificationMethodType::Ed25519VerificationKey2018) .public_key(PublicKeyField::Base58 { public_key_base58: "H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV".to_string(), }) .build(); let agent_service = Service::new( "did:example:123456789abcdefghi#agent".parse().unwrap(), "https://agent.example.com/8377464".try_into().unwrap(), OneOrList::One(ServiceType::Other("AgentService".to_string())), Default::default(), ); let messaging_service = Service::new( "did:example:123456789abcdefghi#messages".parse().unwrap(), "https://example.com/messages/8377464".try_into().unwrap(), OneOrList::One(ServiceType::Other("MessagingService".to_string())), Default::default(), ); let mut did_doc = DidDocument::new(Default::default()); did_doc.add_verification_method(verification_method); did_doc.add_service(agent_service); did_doc.add_service(messaging_service); did_doc } fn example_resolution_output() -> DidResolutionOutput { DidResolutionOutput::builder(example_did_document()).build() } #[test] fn test_content_stream_from() { let did_document = example_did_document(); let did_url = DidUrl::parse("did:example:123456789abcdefghi#keys-1".to_string()).unwrap(); let content_stream = content_stream_from(&did_document, &did_url).unwrap(); let content_value: Value = serde_json::from_reader(content_stream).unwrap(); let expected = serde_json::json!( { "id": "did:example:123456789abcdefghi#keys-1", "type": "Ed25519VerificationKey2018", "controller": "did:example:123456789abcdefghi", "publicKeyBase58": "H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV" } ); assert_eq!(content_value, expected); } #[test] fn test_dereference_did_document() { let resolution_output = example_resolution_output(); let did_url = DidUrl::parse("did:example:123456789abcdefghi#keys-1".to_string()).unwrap(); let dereferencing_output = dereference_did_document(&resolution_output, &did_url).unwrap(); let content_value: Value = serde_json::from_reader(dereferencing_output.content_stream().clone()).unwrap(); let expected = serde_json::json!( { "id": "did:example:123456789abcdefghi#keys-1", "type": "Ed25519VerificationKey2018", "controller": "did:example:123456789abcdefghi", "publicKeyBase58": "H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV" } ); assert_eq!(content_value, expected); let content_metadata = dereferencing_output.content_metadata(); assert_eq!(content_metadata, &resolution_output.did_document_metadata); let dereferencing_metadata = dereferencing_output.dereferencing_metadata(); assert_eq!( dereferencing_metadata.content_type(), Some(&"application/did+json".to_string()) ); } #[test] fn test_dereference_did_document_not_found() { let resolution_output = example_resolution_output(); let did_url = DidUrl::parse("did:example:123456789abcdefghi#non-existent".to_string()).unwrap(); let result = dereference_did_document(&resolution_output, &did_url); assert!(matches!(result, Err(DidSovError::NotFound(_)))); } #[test] fn test_dereference_did_document_ambiguous() { let did_doc = { let mut did_doc = example_did_document(); let additional_service = Service::new( "did:example:123456789abcdefghi#keys-1".parse().unwrap(), "https://example.com/duplicated/8377464".try_into().unwrap(), OneOrList::One(ServiceType::Other("DuplicatedService".to_string())), Default::default(), ); did_doc.add_service(additional_service); did_doc }; let resolution_output = DidResolutionOutput::builder(did_doc).build(); let did_url = DidUrl::parse("did:example:123456789abcdefghi#keys-1".to_string()).unwrap(); let result = dereference_did_document(&resolution_output, &did_url); assert!(matches!(result, Err(DidSovError::InvalidDid(_)))); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/dereferencing/mod.rs
did_core/did_methods/did_resolver_sov/src/dereferencing/mod.rs
mod dereferencer; mod utils;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/dereferencing/dereferencer.rs
did_core/did_methods/did_resolver_sov/src/dereferencing/dereferencer.rs
use std::{borrow::Borrow, io::Cursor}; use async_trait::async_trait; use did_resolver::{ did_parser_nom::DidUrl, error::GenericError, traits::{ dereferenceable::{ dereferencing_options::DidDereferencingOptions, dereferencing_output::DidDereferencingOutput, DidDereferenceable, }, resolvable::DidResolvable, }, }; use super::utils::dereference_did_document; use crate::{reader::AttrReader, resolution::DidSovResolver}; #[async_trait] impl<T, A> DidDereferenceable for DidSovResolver<T, A> where T: Borrow<A> + Sync + Send, A: AttrReader, { type Output = Cursor<Vec<u8>>; async fn dereference( &self, did_url: &DidUrl, _options: &DidDereferencingOptions, ) -> Result<DidDereferencingOutput<Self::Output>, GenericError> { let resolution_output = self.resolve(&did_url.try_into()?, &()).await?; dereference_did_document(&resolution_output, did_url).map_err(|err| err.into()) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/resolution/utils.rs
did_core/did_methods/did_resolver_sov/src/resolution/utils.rs
use chrono::{DateTime, Utc}; use did_resolver::{ did_doc::schema::{ did_doc::DidDocument, service::{typed::ServiceType, Service}, types::uri::Uri, utils::OneOrList, verification_method::{PublicKeyField, VerificationMethod, VerificationMethodType}, }, did_parser_nom::{Did, DidUrl}, shared_types::did_document_metadata::DidDocumentMetadata, traits::resolvable::{ resolution_metadata::DidResolutionMetadata, resolution_output::DidResolutionOutput, }, }; use serde_json::Value; use crate::{ error::{parsing::ParsingErrorSource, DidSovError}, service::{DidSovServiceType, EndpointDidSov}, }; fn prepare_ids(did: &str) -> Result<(Uri, Did), DidSovError> { let service_id = Uri::new(did)?; let ddo_id = Did::parse(did.to_string())?; Ok((service_id, ddo_id)) } fn get_data_from_response(resp: &str) -> Result<Value, DidSovError> { let resp: serde_json::Value = serde_json::from_str(resp)?; match &resp["result"]["data"] { Value::String(ref data) => serde_json::from_str(data).map_err(|err| err.into()), Value::Null => Err(DidSovError::NotFound("DID not found".to_string())), resp => Err(DidSovError::ParsingError( ParsingErrorSource::LedgerResponseParsingError(format!( "Unexpected data format in ledger response: {resp}" )), )), } } fn get_txn_time_from_response(resp: &str) -> Result<i64, DidSovError> { let resp: serde_json::Value = serde_json::from_str(resp)?; let txn_time = resp["result"]["txnTime"] .as_i64() .ok_or(DidSovError::ParsingError( ParsingErrorSource::LedgerResponseParsingError("Failed to parse txnTime".to_string()), ))?; Ok(txn_time) } fn unix_to_datetime(posix_timestamp: i64) -> Option<DateTime<Utc>> { DateTime::from_timestamp(posix_timestamp, 0) } fn expand_abbreviated_verkey(nym: &str, verkey: &str) -> Result<String, DidSovError> { if let Some(stripped_verkey) = verkey.strip_prefix('~') { let mut decoded_nym = bs58::decode(nym).into_vec().map_err(|e| { DidSovError::ParsingError(ParsingErrorSource::LedgerResponseParsingError(format!( "Failed to decode did from base58: {nym} (error: {e})" ))) })?; let decoded_stripped_verkey = bs58::decode(stripped_verkey).into_vec().map_err(|e| { DidSovError::ParsingError(ParsingErrorSource::LedgerResponseParsingError(format!( "Failed to decode verkey from base58: {stripped_verkey} (error: {e})" ))) })?; decoded_nym.extend(&decoded_stripped_verkey); Ok(bs58::encode(decoded_nym).into_string()) } else { Ok(verkey.to_string()) } } pub(super) fn is_valid_sovrin_did_id(id: &str) -> bool { if id.len() < 21 || id.len() > 22 { return false; } let base58_chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; id.chars().all(|c| base58_chars.contains(c)) } pub(super) async fn ledger_response_to_ddo( did: &str, resp: &str, verkey: String, ) -> Result<DidResolutionOutput, DidSovError> { log::info!("ledger_response_to_ddo >> did: {did}, verkey: {verkey}, resp: {resp}"); let (service_id, ddo_id) = prepare_ids(did)?; let service_data = match get_data_from_response(resp) { Ok(data) => data, Err(e) => { log::warn!("Failed to get service data: {e}"); serde_json::Value::Null } }; let mut ddo = DidDocument::new(ddo_id.clone()); let mut services = Vec::new(); if !service_data.is_null() { let endpoint: EndpointDidSov = serde_json::from_value(service_data["endpoint"].clone())?; let service_types: Vec<ServiceType> = endpoint .types .into_iter() .map(|t| match t { DidSovServiceType::Endpoint => ServiceType::AIP1, DidSovServiceType::DidCommunication => ServiceType::DIDCommV1, DidSovServiceType::DIDComm => ServiceType::DIDCommV2, DidSovServiceType::Unknown => ServiceType::Other("Unknown".to_string()), }) .collect(); let service = Service::new( service_id, endpoint.endpoint, OneOrList::List(service_types), Default::default(), ); services.push(service); } ddo.set_service(services); let txn_time_result = get_txn_time_from_response(resp); let datetime = match txn_time_result { Ok(txn_time) => unix_to_datetime(txn_time), Err(e) => { log::warn!("Failed to parse txnTime: {e}"); None } }; let expanded_verkey = expand_abbreviated_verkey(ddo_id.id(), &verkey)?; // TODO: Use multibase instead of base58 let verification_method = VerificationMethod::builder() .id(DidUrl::parse("#1".to_string())?) .controller(did.to_string().try_into()?) .verification_method_type(VerificationMethodType::Ed25519VerificationKey2018) .public_key(PublicKeyField::Base58 { public_key_base58: expanded_verkey, }) .build(); ddo.add_verification_method(verification_method); ddo.add_key_agreement_ref(DidUrl::parse("#1".to_string())?); let ddo_metadata = { let mut metadata_builder = DidDocumentMetadata::builder().deactivated(false); if let Some(datetime) = datetime { metadata_builder = metadata_builder.updated(datetime); } metadata_builder.build() }; let resolution_metadata = DidResolutionMetadata::builder() .content_type("application/did+json".to_string()) .build(); Ok(DidResolutionOutput::builder(ddo) .did_document_metadata(ddo_metadata) .did_resolution_metadata(resolution_metadata) .build()) } #[cfg(test)] mod tests { use chrono::TimeZone; use did_resolver::did_doc::schema::verification_method::PublicKeyField; use super::*; #[test] fn test_prepare_ids() { let did = "did:example:1234567890".to_string(); let (service_id, ddo_id) = prepare_ids(&did).unwrap(); assert_eq!(service_id.to_string(), "did:example:1234567890"); assert_eq!(ddo_id.to_string(), "did:example:1234567890"); } #[test] fn test_get_data_from_response() { let resp = r#"{ "result": { "data": "{\"endpoint\":{\"endpoint\":\"https://example.com\"}}" } }"#; let data = get_data_from_response(resp).unwrap(); assert_eq!( data["endpoint"]["endpoint"].as_str().unwrap(), "https://example.com" ); } #[test] fn test_get_txn_time_from_response() { let resp = r#"{ "result": { "txnTime": 1629272938 } }"#; let txn_time = get_txn_time_from_response(resp).unwrap(); assert_eq!(txn_time, 1629272938); } #[test] fn test_posix_to_datetime() { let posix_timestamp = 1629272938; let datetime = unix_to_datetime(posix_timestamp).unwrap(); assert_eq!( datetime, chrono::Utc.timestamp_opt(posix_timestamp, 0).unwrap() ); } #[tokio::test] async fn test_resolve_ddo() { let did = "did:example:1234567890"; let resp = r#"{ "result": { "data": "{\"endpoint\":{\"endpoint\":\"https://example.com\"}}", "txnTime": 1629272938 } }"#; let verkey = "9wvq2i4xUa5umXoThe83CDgx1e5bsjZKJL4DEWvTP9qe".to_string(); let DidResolutionOutput { did_document: ddo, did_resolution_metadata, did_document_metadata, } = ledger_response_to_ddo(did, resp, verkey).await.unwrap(); assert_eq!(ddo.id().to_string(), "did:example:1234567890"); assert_eq!(ddo.service()[0].id().to_string(), "did:example:1234567890"); assert_eq!( ddo.service()[0].service_endpoint().as_ref(), "https://example.com/" ); assert_eq!( did_document_metadata.updated().unwrap(), Utc.timestamp_opt(1629272938, 0).unwrap() ); assert_eq!( did_resolution_metadata.content_type().unwrap(), "application/did+json" ); if let PublicKeyField::Base58 { public_key_base58 } = ddo.verification_method()[0].public_key_field() { assert_eq!( public_key_base58, "9wvq2i4xUa5umXoThe83CDgx1e5bsjZKJL4DEWvTP9qe" ); } else { panic!("Unexpected public key type"); } } #[test] fn test_expand_abbreviated_verkey_with_abbreviation() { let nym = "7Sqc3ne5NfUVxMTrHahxz3"; let abbreviated_verkey = "~DczaFTexiEYv5abkEUZeZt"; let expected_full_verkey = "4WkksEAXsewRbDYDz66aTdjtVF2LBxbqEMyF2WEjTBKk"; assert_eq!( expand_abbreviated_verkey(nym, abbreviated_verkey).unwrap(), expected_full_verkey ); } #[test] fn test_expand_abbreviated_verkey_without_abbreviation() { let nym = "123456789abcdefghi"; let full_verkey = "123456789abcdefghixyz123"; assert_eq!( expand_abbreviated_verkey(nym, full_verkey).unwrap(), full_verkey ); } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/resolution/mod.rs
did_core/did_methods/did_resolver_sov/src/resolution/mod.rs
mod resolver; mod utils; pub use resolver::DidSovResolver;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/src/resolution/resolver.rs
did_core/did_methods/did_resolver_sov/src/resolution/resolver.rs
use std::{borrow::Borrow, marker::PhantomData}; use async_trait::async_trait; use did_resolver::{ did_parser_nom::Did, error::GenericError, traits::resolvable::{resolution_output::DidResolutionOutput, DidResolvable}, }; use serde_json::Value; use super::utils::{is_valid_sovrin_did_id, ledger_response_to_ddo}; use crate::{ error::{parsing::ParsingErrorSource, DidSovError}, reader::AttrReader, }; pub struct DidSovResolver<T, A> where T: Borrow<A> + Sync + Send, A: AttrReader, { ledger: T, _marker: PhantomData<A>, } impl<T, A> DidSovResolver<T, A> where T: Borrow<A> + Sync + Send, A: AttrReader, { // todo: Creating instance can be non-ergonomic, as compiler will ask you to specify // the full type of DidSovResolver<T, A> explicitly, and the type can be quite long. // Consider improving the DX in the future. pub fn new(ledger: T) -> Self { DidSovResolver { ledger, _marker: PhantomData, } } } #[async_trait] impl<T, A> DidResolvable for DidSovResolver<T, A> where T: Borrow<A> + Sync + Send, A: AttrReader, { type DidResolutionOptions = (); async fn resolve( &self, parsed_did: &Did, _options: &Self::DidResolutionOptions, ) -> Result<DidResolutionOutput, GenericError> { log::info!("DidSovResolver::resolve >> Resolving did: {parsed_did}"); let method = parsed_did.method().ok_or_else(|| { DidSovError::InvalidDid("Attempted to resolve unqualified did".to_string()) })?; if method != "sov" { return Err(Box::new(DidSovError::MethodNotSupported( method.to_string(), ))); } if !is_valid_sovrin_did_id(parsed_did.id()) { return Err(Box::new(DidSovError::InvalidDid(format!( "Sovrin DID: {} contains invalid DID ID.", parsed_did.id() )))); } let ledger_response = self .ledger .borrow() .get_attr(parsed_did, "endpoint") .await?; let verkey = self.get_verkey(parsed_did).await?; ledger_response_to_ddo(parsed_did.did(), &ledger_response, verkey) .await .map_err(|err| err.into()) } } impl<T, A> DidSovResolver<T, A> where T: Borrow<A> + Sync + Send, A: AttrReader, { async fn get_verkey(&self, did: &Did) -> Result<String, DidSovError> { let nym_response = self.ledger.borrow().get_nym(did).await?; log::info!("get_verkey >> nym_response: {nym_response}"); let nym_json: Value = serde_json::from_str(&nym_response)?; let nym_data = nym_json["result"]["data"] .as_str() .ok_or(DidSovError::ParsingError( ParsingErrorSource::LedgerResponseParsingError( "Failed to parse nym data".to_string(), ), ))?; let nym_data: Value = serde_json::from_str(nym_data)?; let verkey = nym_data["verkey"] .as_str() .ok_or(DidSovError::ParsingError( ParsingErrorSource::LedgerResponseParsingError( "Failed to parse verkey from nym data".to_string(), ), ))?; Ok(verkey.to_string()) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/tests/resolution.rs
did_core/did_methods/did_resolver_sov/tests/resolution.rs
use std::{thread, time::Duration}; use aries_vcx::common::ledger::{service_didsov::EndpointDidSov, transactions::write_endpoint}; use aries_vcx_ledger::ledger::base_ledger::IndyLedgerWrite; use aries_vcx_wallet::wallet::base_wallet::{did_wallet::DidWallet, BaseWallet}; use did_resolver::{ did_doc::schema::service::typed::ServiceType, did_parser_nom::Did, traits::resolvable::{resolution_output::DidResolutionOutput, DidResolvable}, }; use did_resolver_sov::resolution::DidSovResolver; use test_utils::devsetup::build_setup_profile; async fn write_test_endpoint( wallet: &impl BaseWallet, ledger_write: &impl IndyLedgerWrite, did: &Did, ) { let endpoint = EndpointDidSov::create() .set_service_endpoint("http://localhost:8080".parse().unwrap()) .set_routing_keys(Some(vec!["key1".to_string(), "key2".to_string()])) .set_types(Some(vec![ServiceType::AIP1.to_string()])); write_endpoint(wallet, ledger_write, did, &endpoint) .await .unwrap(); thread::sleep(Duration::from_millis(50)); } #[tokio::test] async fn write_service_on_ledger_and_resolve_did_doc() { let profile = build_setup_profile().await; write_test_endpoint( &profile.wallet, &profile.ledger_write, &profile.institution_did, ) .await; let resolver = DidSovResolver::new(profile.ledger_read); let did = format!("did:sov:{}", profile.institution_did); let DidResolutionOutput { did_document, .. } = resolver .resolve(&Did::parse(did.clone()).unwrap(), &()) .await .unwrap(); assert_eq!(did_document.id().to_string(), did); } #[tokio::test] async fn test_error_handling_during_resolution() { let profile = build_setup_profile().await; let resolver = DidSovResolver::new(profile.ledger_read); let did = format!("did:unknownmethod:{}", profile.institution_did); let result = resolver .resolve(&Did::parse(did.clone()).unwrap(), &()) .await; assert!(result.is_err()); } #[tokio::test] async fn write_new_nym_and_get_did_doc() { let profile = build_setup_profile().await; let did_data = profile .wallet .create_and_store_my_did(None, None) .await .unwrap(); profile .ledger_write .publish_nym( &profile.wallet, &profile.institution_did, &did_data.did().parse().unwrap(), Some(did_data.verkey()), None, None, ) .await .unwrap(); let resolver = DidSovResolver::new(profile.ledger_read); let did = format!("did:sov:{}", did_data.did()); let DidResolutionOutput { did_document, .. } = resolver .resolve(&Did::parse(did.clone()).unwrap(), &()) .await .unwrap(); assert_eq!(did_document.id().to_string(), did); }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_sov/tests/dereferencing.rs
did_core/did_methods/did_resolver_sov/tests/dereferencing.rs
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_web/src/lib.rs
did_core/did_methods/did_resolver_web/src/lib.rs
pub mod error; pub mod resolution;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_web/src/error/mod.rs
did_core/did_methods/did_resolver_web/src/error/mod.rs
pub mod parsing; use hyper::StatusCode; use thiserror::Error; use self::parsing::ParsingErrorSource; #[derive(Error, Debug)] #[non_exhaustive] pub enum DidWebError { #[error("DID method not supported: {0}")] MethodNotSupported(String), #[error("Representation not supported: {0}")] RepresentationNotSupported(String), #[error("Invalid DID: {0}")] InvalidDid(String), #[error("Parsing error: {0}")] ParsingError(#[from] ParsingErrorSource), #[error("Network error: {0}")] NetworkError(#[from] hyper::Error), #[error("Network error: {0}")] NetworkClientError(#[from] hyper_util::client::legacy::Error), #[error("Non-success server response: {0}")] NonSuccessResponse(StatusCode), #[error(transparent)] Other(#[from] Box<dyn std::error::Error + Send + Sync>), }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_web/src/error/parsing.rs
did_core/did_methods/did_resolver_web/src/error/parsing.rs
use thiserror::Error; use super::DidWebError; #[derive(Error, Debug)] pub enum ParsingErrorSource { #[error("JSON parsing error: {0}")] JsonError(#[from] serde_json::Error), #[error("Invalid encoding: {0}")] Utf8Error(#[from] std::string::FromUtf8Error), } impl From<serde_json::Error> for DidWebError { fn from(error: serde_json::Error) -> Self { DidWebError::ParsingError(ParsingErrorSource::JsonError(error)) } } impl From<std::string::FromUtf8Error> for DidWebError { fn from(error: std::string::FromUtf8Error) -> Self { DidWebError::ParsingError(ParsingErrorSource::Utf8Error(error)) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_web/src/resolution/mod.rs
did_core/did_methods/did_resolver_web/src/resolution/mod.rs
pub mod resolver;
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_web/src/resolution/resolver.rs
did_core/did_methods/did_resolver_web/src/resolution/resolver.rs
use async_trait::async_trait; use did_resolver::{ did_parser_nom::Did, error::GenericError, shared_types::did_document_metadata::DidDocumentMetadata, traits::resolvable::{ resolution_metadata::DidResolutionMetadata, resolution_output::DidResolutionOutput, DidResolvable, }, }; use http_body_util::{combinators::BoxBody, BodyExt as _}; use hyper::{ body::Bytes, http::uri::{self, Scheme}, Uri, }; use hyper_tls::HttpsConnector; use hyper_util::{ client::legacy::{ connect::{Connect, HttpConnector}, Client, }, rt::TokioExecutor, }; use crate::error::DidWebError; pub struct DidWebResolver<C> where C: Connect + Send + Sync + Clone + 'static, { client: Client<C, BoxBody<Bytes, GenericError>>, scheme: Scheme, } impl DidWebResolver<HttpConnector> { pub fn http() -> DidWebResolver<HttpConnector> { DidWebResolver { client: Client::builder(TokioExecutor::new()) .build::<_, BoxBody<Bytes, GenericError>>(HttpConnector::new()), scheme: Scheme::HTTP, } } } impl DidWebResolver<HttpsConnector<HttpConnector>> { pub fn https() -> DidWebResolver<HttpsConnector<HttpConnector>> { DidWebResolver { client: Client::builder(TokioExecutor::new()) .build::<_, BoxBody<Bytes, GenericError>>(HttpsConnector::new()), scheme: Scheme::HTTPS, } } } impl<C> DidWebResolver<C> where C: Connect + Send + Sync + Clone + 'static, { async fn fetch_did_document(&self, url: Uri) -> Result<String, DidWebError> { let res = self.client.get(url).await?; if !res.status().is_success() { return Err(DidWebError::NonSuccessResponse(res.status())); } let body = res.into_body().collect().await?.to_bytes(); String::from_utf8(body.to_vec()).map_err(|err| err.into()) } } #[async_trait] impl<C> DidResolvable for DidWebResolver<C> where C: Connect + Send + Sync + Clone + 'static, { type DidResolutionOptions = (); async fn resolve( &self, did: &Did, _options: &Self::DidResolutionOptions, ) -> Result<DidResolutionOutput, GenericError> { let method = did.method().ok_or_else(|| { DidWebError::InvalidDid("Attempted to resolve unqualified did".to_string()) })?; if method != "web" { return Err(Box::new(DidWebError::MethodNotSupported( method.to_string(), ))); } let did_parts: Vec<&str> = did.id().split(':').collect(); if did_parts.is_empty() { return Err(Box::new(DidWebError::InvalidDid(did.id().to_string()))); } let domain = did_parts[0].replace("%3A", ":"); let path_parts = &did_parts[1..]; let path_and_query = if path_parts.is_empty() { "/.well-known/did.json".to_string() } else { let path = path_parts.join("/"); format!("/{path}/did.json") }; let url = uri::Builder::new() .scheme(self.scheme.clone()) .authority(domain.as_str()) .path_and_query(path_and_query.as_str()) .build()?; let did_document = serde_json::from_str(&self.fetch_did_document(url).await?)?; let did_resolution_output = DidResolutionOutput::builder(did_document) .did_resolution_metadata(DidResolutionMetadata::default()) .did_document_metadata(DidDocumentMetadata::default()) .build(); Ok(did_resolution_output) } }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false
openwallet-foundation/vcx
https://github.com/openwallet-foundation/vcx/blob/2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7/did_core/did_methods/did_resolver_web/tests/resolution.rs
did_core/did_methods/did_resolver_web/tests/resolution.rs
use std::convert::Infallible; use did_resolver::{ did_doc::schema::did_doc::DidDocument, did_parser_nom::Did, traits::resolvable::{resolution_output::DidResolutionOutput, DidResolvable}, }; use did_resolver_web::resolution::resolver::DidWebResolver; use http_body_util::{combinators::BoxBody, BodyExt, Full}; use hyper::{ body::{Bytes, Incoming}, service::service_fn, Request, Response, }; use hyper_util::{ rt::{TokioExecutor, TokioIo}, server::conn::auto::Builder, }; use tokio::{net::TcpListener, task::JoinSet}; use tokio_test::assert_ok; const DID_DOCUMENT: &str = r#" { "@context": [ "https://www.w3.org/ns/did/v1", "https://w3id.org/security/suites/jws-2020/v1" ], "id": "did:web:example.com", "verificationMethod": [ { "id": "did:web:example.com#key-0", "type": "JsonWebKey2020", "controller": "did:web:example.com", "publicKeyJwk": { "kty": "OKP", "crv": "Ed25519", "x": "0-e2i2_Ua1S5HbTYnVB0lj2Z2ytXu2-tYmDFf8f5NjU" } }, { "id": "did:web:example.com#key-1", "type": "JsonWebKey2020", "controller": "did:web:example.com", "publicKeyJwk": { "kty": "OKP", "crv": "X25519", "x": "9GXjPGGvmRq9F6Ng5dQQ_s31mfhxrcNZxRGONrmH30k" } }, { "id": "did:web:example.com#key-2", "type": "JsonWebKey2020", "controller": "did:web:example.com", "publicKeyJwk": { "kty": "EC", "crv": "P-256", "x": "38M1FDts7Oea7urmseiugGW7tWc3mLpJh6rKe7xINZ8", "y": "nDQW6XZ7b_u2Sy9slofYLlG03sOEoug3I0aAPQ0exs4" } } ], "authentication": [ "did:web:example.com#key-0", "did:web:example.com#key-2" ], "assertionMethod": [ "did:web:example.com#key-0", "did:web:example.com#key-2" ], "keyAgreement": [ "did:web:example.com#key-1", "did:web:example.com#key-2" ] }"#; async fn mock_server_handler( req: Request<Incoming>, ) -> Result<Response<BoxBody<Bytes, Infallible>>, Infallible> { let response = match req.uri().path() { "/.well-known/did.json" | "/user/alice/did.json" => { Response::new(Full::new(Bytes::from(DID_DOCUMENT)).boxed()) } _ => Response::builder() .status(404) .body(Full::new(Bytes::from("Not Found")).boxed()) .unwrap(), }; Ok(response) } async fn create_mock_server(port: u16) -> String { let listen_addr = format!("127.0.0.1:{port}"); let tcp_listener = TcpListener::bind(listen_addr).await.unwrap(); tokio::spawn(async move { let mut join_set = JoinSet::new(); loop { let (stream, addr) = match tcp_listener.accept().await { Ok(x) => x, Err(e) => { eprintln!("failed to accept connection: {e}"); continue; } }; let serve_connection = async move { println!("handling a request from {addr}"); let result = Builder::new(TokioExecutor::new()) .serve_connection(TokioIo::new(stream), service_fn(mock_server_handler)) .await; if let Err(e) = result { eprintln!("error serving {addr}: {e}"); } println!("handled a request from {addr}"); }; join_set.spawn(serve_connection); } }); "localhost".to_string() } #[tokio::test] async fn test_did_web_resolver() { fn verify_did_document(did_document: &DidDocument) { assert_eq!( did_document.id().to_string(), "did:web:example.com".to_string() ); assert_eq!(did_document.verification_method().len(), 3); assert_eq!(did_document.authentication().len(), 2); assert_eq!(did_document.assertion_method().len(), 2); assert_eq!(did_document.key_agreement().len(), 2); } let port = 3000; let host = create_mock_server(port).await; let did_web_resolver = DidWebResolver::http(); let did_example_1 = Did::parse(format!("did:web:{host}%3A{port}")).unwrap(); let did_example_2 = Did::parse(format!("did:web:{host}%3A{port}:user:alice")).unwrap(); let DidResolutionOutput { did_document: ddo1, .. } = assert_ok!(did_web_resolver.resolve(&did_example_1, &()).await); verify_did_document(&ddo1); let DidResolutionOutput { did_document: ddo2, .. } = assert_ok!(did_web_resolver.resolve(&did_example_2, &()).await); verify_did_document(&ddo2); }
rust
Apache-2.0
2d3034ed73ba8d49e0f72251b4c7cfb859a1efe7
2026-01-04T20:24:59.602734Z
false