file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
lambda.rs
use dotenv; use fastspring_keygen_integration::fastspring; use fastspring_keygen_integration::keygen; use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license}; use fastspring_keygen_integration::util; use fastspring_keygen_integration::patreon; use http::header::CONTENT_TYPE; use lambda_http::{lambda, Body, Request, RequestExt, Response}; use lambda_runtime::error::HandlerError; use lambda_runtime::Context; use log::{debug, info, warn}; use std::collections::HashMap; use std::error::Error; use std::env; use lazy_static::lazy_static; use lettre::transport::smtp::authentication::Credentials; use lettre::{Message, SmtpTransport, Transport}; lazy_static! { static ref MNPRX_COMMUNITY_KEYGEN_POLICY_ID: String = env::var("MNPRX_COMMUNITY_KEYGEN_POLICY_ID").unwrap(); static ref SMTP_SERVER: String = env::var("SMTP_SERVER").unwrap(); static ref SMTP_USERNAME: String = env::var("SMTP_USERNAME").unwrap(); static ref SMTP_PASSWORD: String = env::var("SMTP_PASSWORD").unwrap(); } fn router(req: Request, c: Context) -> Result<Response<Body>, HandlerError> { debug!("router request={:?}", req); debug!("path={:?}", req.uri().path()); debug!("query={:?}", req.query_string_parameters()); let client = reqwest::Client::new(); match req.uri().path() { "/fastspring-keygen-integration-service/keygen/create" => match *req.method() { http::Method::POST => handle_keygen_create(req, c), _ => not_allowed(req, c), }, "/fastspring-keygen-integration-service/webhooks" => match *req.method() { http::Method::POST => handle_webhook(&client, req, c), _ => not_allowed(req, c), }, "/fastspring-keygen-integration-service/patreon" => match *req.method() { http::Method::POST => handle_patreon_webhook(&client, req, c), _ => not_allowed(req, c), }, _ => not_found(req, c), } } fn license_key(code: &str) -> Option<&str> { code.split('.').nth(1) } fn handle_patreon_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if!patreon::authentify_web_hook(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let trigger = req.headers().get("X-Patreon-Event") .ok_or("invalid format (X-Patreon-Event)")? .to_str().ok().ok_or("invalid format (X-Patreon-Event)")?; debug!("X-Patreon-Event: {}", trigger); let body = util::body_to_json(req.body())?; if trigger == "pledges:create" { patreon_handle_pledge_create(client, &body)?;
Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Patreon pledge create trigger fn patreon_handle_pledge_create( client: &reqwest::Client, body: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_create {:?}", body); let user_id = body["data"]["relationships"]["patron"]["data"]["id"].as_str().ok_or("invalid format (.data.relationships.patron.data.id)")?; let mut user_email = None; let mut user_first_name = None; for included in body["included"].as_array().ok_or("invalid format (.included)")?.iter() { if included["id"].as_str().ok_or("invalid format (.included.#.id)")? == user_id { user_email = Some(included["attributes"]["email"].as_str().ok_or("invalid format (.included.#.attributes.email)")?); user_first_name = included["attributes"]["first_name"].as_str(); } } let user_email = user_email.ok_or("could not find patron email")?; debug!("patron email: {}", user_email); let license= keygen::generate_license( client, "PATREON", MNPRX_COMMUNITY_KEYGEN_POLICY_ID.as_ref(), None, Some(user_id), false)?; let user_name = body["data"]["relationships"]["patron"]["data"]["id"].as_str().unwrap_or(""); let email_body = format!(r##"Hi, Thank you for becoming our Patreon! You can activate your Flair Community license with the following key: {} For more information on how to install and activate your license, please refer to the documentation: https://docs.artineering.io/flair/setup/ If you encounter any issues, please feel free to reach out to us through Discord, we are here to help. Have fun using Flair and make sure to share your results with the community. Cheers, Your team at Artineering."##, license); // send the license to the patron let email = Message::builder() .from("Artineering <[email protected]>".parse().unwrap()) .reply_to("Artineering <[email protected]>".parse().unwrap()) .to(user_email.parse().unwrap()) .bcc("[email protected]".parse().unwrap()) .subject("[Flair] Your Community license key") .body(email_body) .unwrap(); let creds = Credentials::new(SMTP_USERNAME.clone(), SMTP_PASSWORD.clone()); let mailer = SmtpTransport::relay(SMTP_SERVER.as_ref()) .unwrap() .credentials(creds) .build(); match mailer.send(&email) { Ok(_) => info!("Email sent successfully"), Err(e) => panic!("Could not send email: {:?}", e), } Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } /// Patreon pledge delete trigger fn patreon_handle_pledge_delete( client: &reqwest::Client, data: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_delete {:?}", data); Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } fn handle_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if!fastspring::authentify_web_hook(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let events_json = util::body_to_json(req.body())?; let events_json = events_json["events"].as_array().ok_or("invalid format")?; // TODO do not reply OK every time: check each event for e in events_json { let ty = e["type"].as_str().ok_or("invalid format")?; let data = &e["data"]; match ty { "subscription.deactivated" => { handle_subscription_deactivated(client, data)?; } _ => { warn!("unhandled webhook: {}", ty); } }; } Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Handles deactivation of subscriptions. /// /// This will suspend all licenses associated with the order. fn handle_subscription_deactivated( client: &reqwest::Client, data: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_subscription_deactivated {:?}", data); let subscription_id = data["id"].as_str().ok_or("invalid format (.id)")?; info!("subscription deactivated: {}", subscription_id); let orders = fastspring::get_subscription_entries(client, subscription_id)?; // find the original order // according to the API, this is the entry whose ".reference" field does not include // a "B" (for "billing") at the end. All the others are subscription billing orders. let original_order = orders.as_array().ok_or("invalid format (orders)")?.iter().find(|&order| { let order = &order["order"]; if order["reference"].is_null() { return false; } if let Some(s) = order["reference"].as_str() { !s.ends_with('B') } else { false } }); let original_order = original_order.ok_or("could not find original order")?; let order_items = original_order["order"]["items"] .as_array() .ok_or("invalid format (.order.items)")?; // Collect all licenses to revoke let mut licenses_to_revoke = Vec::new(); for item in order_items.iter() { //let product = &item["product"]; for (_k, v) in item["fulfillments"] .as_object() .ok_or("invalid format (.fulfillments)")? .iter() { if let Some(licenses) = v.as_array() { for l in licenses { let code = if let Some(s) = l["license"].as_str() { s } else { continue; }; licenses_to_revoke.push(String::from(code)); } } } } // revoke all licenses for lic in licenses_to_revoke.iter() { let key = license_key(lic).ok_or("invalid license key")?; keygen::revoke_license(key)?; } Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } /// Handles license creation requests (coming from FastSpring). fn handle_keygen_create(req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { if!fastspring::verify_license_gen(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let params: HashMap<_, _> = url::form_urlencoded::parse(match req.body() { Body::Text(ref s) => s.as_bytes(), _ => return Err("invalid request body".into()), }) .collect(); //debug!("params = {:?}", params); let subscription = params .get("subscription") .ok_or("invalid query parameters (no subscription)")?; let policy_id = params .get("policy") .ok_or("invalid query parameters (no policy)")?; let quantity: u32 = params .get("quantity") .ok_or("invalid query parameters (no quantity)")? .parse()?; let (codes,errors) = generate_licenses(subscription, policy_id, quantity, None, false); if!errors.is_empty() { Err(format!("errors encountered while generating licenses ({} successfully generated)", codes.len()).as_str())? } let codes = codes.join("\n"); Ok(Response::builder() .status(http::StatusCode::OK) .header(CONTENT_TYPE, "text/plain") .body(codes.into()) .unwrap()) } fn not_found(_req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { Ok(Response::builder() .status(http::StatusCode::NOT_FOUND) .body(Body::default()) .unwrap()) } fn not_allowed(_req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { Ok(Response::builder() .status(http::StatusCode::METHOD_NOT_ALLOWED) .body(Body::default()) .unwrap()) } fn main() -> Result<(), Box<dyn Error>> { env_logger::init(); dotenv::dotenv().ok(); lambda!(router); Ok(()) }
} else if trigger == "pledges:delete" { patreon_handle_pledge_delete(client, &body)?; }
random_line_split
lambda.rs
use dotenv; use fastspring_keygen_integration::fastspring; use fastspring_keygen_integration::keygen; use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license}; use fastspring_keygen_integration::util; use fastspring_keygen_integration::patreon; use http::header::CONTENT_TYPE; use lambda_http::{lambda, Body, Request, RequestExt, Response}; use lambda_runtime::error::HandlerError; use lambda_runtime::Context; use log::{debug, info, warn}; use std::collections::HashMap; use std::error::Error; use std::env; use lazy_static::lazy_static; use lettre::transport::smtp::authentication::Credentials; use lettre::{Message, SmtpTransport, Transport}; lazy_static! { static ref MNPRX_COMMUNITY_KEYGEN_POLICY_ID: String = env::var("MNPRX_COMMUNITY_KEYGEN_POLICY_ID").unwrap(); static ref SMTP_SERVER: String = env::var("SMTP_SERVER").unwrap(); static ref SMTP_USERNAME: String = env::var("SMTP_USERNAME").unwrap(); static ref SMTP_PASSWORD: String = env::var("SMTP_PASSWORD").unwrap(); } fn router(req: Request, c: Context) -> Result<Response<Body>, HandlerError> { debug!("router request={:?}", req); debug!("path={:?}", req.uri().path()); debug!("query={:?}", req.query_string_parameters()); let client = reqwest::Client::new(); match req.uri().path() { "/fastspring-keygen-integration-service/keygen/create" => match *req.method() { http::Method::POST => handle_keygen_create(req, c), _ => not_allowed(req, c), }, "/fastspring-keygen-integration-service/webhooks" => match *req.method() { http::Method::POST => handle_webhook(&client, req, c), _ => not_allowed(req, c), }, "/fastspring-keygen-integration-service/patreon" => match *req.method() { http::Method::POST => handle_patreon_webhook(&client, req, c), _ => not_allowed(req, c), }, _ => not_found(req, c), } } fn license_key(code: &str) -> Option<&str>
fn handle_patreon_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if!patreon::authentify_web_hook(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let trigger = req.headers().get("X-Patreon-Event") .ok_or("invalid format (X-Patreon-Event)")? .to_str().ok().ok_or("invalid format (X-Patreon-Event)")?; debug!("X-Patreon-Event: {}", trigger); let body = util::body_to_json(req.body())?; if trigger == "pledges:create" { patreon_handle_pledge_create(client, &body)?; } else if trigger == "pledges:delete" { patreon_handle_pledge_delete(client, &body)?; } Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Patreon pledge create trigger fn patreon_handle_pledge_create( client: &reqwest::Client, body: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_create {:?}", body); let user_id = body["data"]["relationships"]["patron"]["data"]["id"].as_str().ok_or("invalid format (.data.relationships.patron.data.id)")?; let mut user_email = None; let mut user_first_name = None; for included in body["included"].as_array().ok_or("invalid format (.included)")?.iter() { if included["id"].as_str().ok_or("invalid format (.included.#.id)")? == user_id { user_email = Some(included["attributes"]["email"].as_str().ok_or("invalid format (.included.#.attributes.email)")?); user_first_name = included["attributes"]["first_name"].as_str(); } } let user_email = user_email.ok_or("could not find patron email")?; debug!("patron email: {}", user_email); let license= keygen::generate_license( client, "PATREON", MNPRX_COMMUNITY_KEYGEN_POLICY_ID.as_ref(), None, Some(user_id), false)?; let user_name = body["data"]["relationships"]["patron"]["data"]["id"].as_str().unwrap_or(""); let email_body = format!(r##"Hi, Thank you for becoming our Patreon! You can activate your Flair Community license with the following key: {} For more information on how to install and activate your license, please refer to the documentation: https://docs.artineering.io/flair/setup/ If you encounter any issues, please feel free to reach out to us through Discord, we are here to help. Have fun using Flair and make sure to share your results with the community. Cheers, Your team at Artineering."##, license); // send the license to the patron let email = Message::builder() .from("Artineering <[email protected]>".parse().unwrap()) .reply_to("Artineering <[email protected]>".parse().unwrap()) .to(user_email.parse().unwrap()) .bcc("[email protected]".parse().unwrap()) .subject("[Flair] Your Community license key") .body(email_body) .unwrap(); let creds = Credentials::new(SMTP_USERNAME.clone(), SMTP_PASSWORD.clone()); let mailer = SmtpTransport::relay(SMTP_SERVER.as_ref()) .unwrap() .credentials(creds) .build(); match mailer.send(&email) { Ok(_) => info!("Email sent successfully"), Err(e) => panic!("Could not send email: {:?}", e), } Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } /// Patreon pledge delete trigger fn patreon_handle_pledge_delete( client: &reqwest::Client, data: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_delete {:?}", data); Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } fn handle_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if!fastspring::authentify_web_hook(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let events_json = util::body_to_json(req.body())?; let events_json = events_json["events"].as_array().ok_or("invalid format")?; // TODO do not reply OK every time: check each event for e in events_json { let ty = e["type"].as_str().ok_or("invalid format")?; let data = &e["data"]; match ty { "subscription.deactivated" => { handle_subscription_deactivated(client, data)?; } _ => { warn!("unhandled webhook: {}", ty); } }; } Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Handles deactivation of subscriptions. /// /// This will suspend all licenses associated with the order. fn handle_subscription_deactivated( client: &reqwest::Client, data: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_subscription_deactivated {:?}", data); let subscription_id = data["id"].as_str().ok_or("invalid format (.id)")?; info!("subscription deactivated: {}", subscription_id); let orders = fastspring::get_subscription_entries(client, subscription_id)?; // find the original order // according to the API, this is the entry whose ".reference" field does not include // a "B" (for "billing") at the end. All the others are subscription billing orders. let original_order = orders.as_array().ok_or("invalid format (orders)")?.iter().find(|&order| { let order = &order["order"]; if order["reference"].is_null() { return false; } if let Some(s) = order["reference"].as_str() { !s.ends_with('B') } else { false } }); let original_order = original_order.ok_or("could not find original order")?; let order_items = original_order["order"]["items"] .as_array() .ok_or("invalid format (.order.items)")?; // Collect all licenses to revoke let mut licenses_to_revoke = Vec::new(); for item in order_items.iter() { //let product = &item["product"]; for (_k, v) in item["fulfillments"] .as_object() .ok_or("invalid format (.fulfillments)")? .iter() { if let Some(licenses) = v.as_array() { for l in licenses { let code = if let Some(s) = l["license"].as_str() { s } else { continue; }; licenses_to_revoke.push(String::from(code)); } } } } // revoke all licenses for lic in licenses_to_revoke.iter() { let key = license_key(lic).ok_or("invalid license key")?; keygen::revoke_license(key)?; } Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } /// Handles license creation requests (coming from FastSpring). fn handle_keygen_create(req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { if!fastspring::verify_license_gen(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let params: HashMap<_, _> = url::form_urlencoded::parse(match req.body() { Body::Text(ref s) => s.as_bytes(), _ => return Err("invalid request body".into()), }) .collect(); //debug!("params = {:?}", params); let subscription = params .get("subscription") .ok_or("invalid query parameters (no subscription)")?; let policy_id = params .get("policy") .ok_or("invalid query parameters (no policy)")?; let quantity: u32 = params .get("quantity") .ok_or("invalid query parameters (no quantity)")? .parse()?; let (codes,errors) = generate_licenses(subscription, policy_id, quantity, None, false); if!errors.is_empty() { Err(format!("errors encountered while generating licenses ({} successfully generated)", codes.len()).as_str())? } let codes = codes.join("\n"); Ok(Response::builder() .status(http::StatusCode::OK) .header(CONTENT_TYPE, "text/plain") .body(codes.into()) .unwrap()) } fn not_found(_req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { Ok(Response::builder() .status(http::StatusCode::NOT_FOUND) .body(Body::default()) .unwrap()) } fn not_allowed(_req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { Ok(Response::builder() .status(http::StatusCode::METHOD_NOT_ALLOWED) .body(Body::default()) .unwrap()) } fn main() -> Result<(), Box<dyn Error>> { env_logger::init(); dotenv::dotenv().ok(); lambda!(router); Ok(()) }
{ code.split('.').nth(1) }
identifier_body
lambda.rs
use dotenv; use fastspring_keygen_integration::fastspring; use fastspring_keygen_integration::keygen; use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license}; use fastspring_keygen_integration::util; use fastspring_keygen_integration::patreon; use http::header::CONTENT_TYPE; use lambda_http::{lambda, Body, Request, RequestExt, Response}; use lambda_runtime::error::HandlerError; use lambda_runtime::Context; use log::{debug, info, warn}; use std::collections::HashMap; use std::error::Error; use std::env; use lazy_static::lazy_static; use lettre::transport::smtp::authentication::Credentials; use lettre::{Message, SmtpTransport, Transport}; lazy_static! { static ref MNPRX_COMMUNITY_KEYGEN_POLICY_ID: String = env::var("MNPRX_COMMUNITY_KEYGEN_POLICY_ID").unwrap(); static ref SMTP_SERVER: String = env::var("SMTP_SERVER").unwrap(); static ref SMTP_USERNAME: String = env::var("SMTP_USERNAME").unwrap(); static ref SMTP_PASSWORD: String = env::var("SMTP_PASSWORD").unwrap(); } fn
(req: Request, c: Context) -> Result<Response<Body>, HandlerError> { debug!("router request={:?}", req); debug!("path={:?}", req.uri().path()); debug!("query={:?}", req.query_string_parameters()); let client = reqwest::Client::new(); match req.uri().path() { "/fastspring-keygen-integration-service/keygen/create" => match *req.method() { http::Method::POST => handle_keygen_create(req, c), _ => not_allowed(req, c), }, "/fastspring-keygen-integration-service/webhooks" => match *req.method() { http::Method::POST => handle_webhook(&client, req, c), _ => not_allowed(req, c), }, "/fastspring-keygen-integration-service/patreon" => match *req.method() { http::Method::POST => handle_patreon_webhook(&client, req, c), _ => not_allowed(req, c), }, _ => not_found(req, c), } } fn license_key(code: &str) -> Option<&str> { code.split('.').nth(1) } fn handle_patreon_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if!patreon::authentify_web_hook(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let trigger = req.headers().get("X-Patreon-Event") .ok_or("invalid format (X-Patreon-Event)")? .to_str().ok().ok_or("invalid format (X-Patreon-Event)")?; debug!("X-Patreon-Event: {}", trigger); let body = util::body_to_json(req.body())?; if trigger == "pledges:create" { patreon_handle_pledge_create(client, &body)?; } else if trigger == "pledges:delete" { patreon_handle_pledge_delete(client, &body)?; } Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Patreon pledge create trigger fn patreon_handle_pledge_create( client: &reqwest::Client, body: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_create {:?}", body); let user_id = body["data"]["relationships"]["patron"]["data"]["id"].as_str().ok_or("invalid format (.data.relationships.patron.data.id)")?; let mut user_email = None; let mut user_first_name = None; for included in body["included"].as_array().ok_or("invalid format (.included)")?.iter() { if included["id"].as_str().ok_or("invalid format (.included.#.id)")? == user_id { user_email = Some(included["attributes"]["email"].as_str().ok_or("invalid format (.included.#.attributes.email)")?); user_first_name = included["attributes"]["first_name"].as_str(); } } let user_email = user_email.ok_or("could not find patron email")?; debug!("patron email: {}", user_email); let license= keygen::generate_license( client, "PATREON", MNPRX_COMMUNITY_KEYGEN_POLICY_ID.as_ref(), None, Some(user_id), false)?; let user_name = body["data"]["relationships"]["patron"]["data"]["id"].as_str().unwrap_or(""); let email_body = format!(r##"Hi, Thank you for becoming our Patreon! You can activate your Flair Community license with the following key: {} For more information on how to install and activate your license, please refer to the documentation: https://docs.artineering.io/flair/setup/ If you encounter any issues, please feel free to reach out to us through Discord, we are here to help. Have fun using Flair and make sure to share your results with the community. Cheers, Your team at Artineering."##, license); // send the license to the patron let email = Message::builder() .from("Artineering <[email protected]>".parse().unwrap()) .reply_to("Artineering <[email protected]>".parse().unwrap()) .to(user_email.parse().unwrap()) .bcc("[email protected]".parse().unwrap()) .subject("[Flair] Your Community license key") .body(email_body) .unwrap(); let creds = Credentials::new(SMTP_USERNAME.clone(), SMTP_PASSWORD.clone()); let mailer = SmtpTransport::relay(SMTP_SERVER.as_ref()) .unwrap() .credentials(creds) .build(); match mailer.send(&email) { Ok(_) => info!("Email sent successfully"), Err(e) => panic!("Could not send email: {:?}", e), } Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } /// Patreon pledge delete trigger fn patreon_handle_pledge_delete( client: &reqwest::Client, data: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_delete {:?}", data); Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } fn handle_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if!fastspring::authentify_web_hook(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let events_json = util::body_to_json(req.body())?; let events_json = events_json["events"].as_array().ok_or("invalid format")?; // TODO do not reply OK every time: check each event for e in events_json { let ty = e["type"].as_str().ok_or("invalid format")?; let data = &e["data"]; match ty { "subscription.deactivated" => { handle_subscription_deactivated(client, data)?; } _ => { warn!("unhandled webhook: {}", ty); } }; } Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Handles deactivation of subscriptions. /// /// This will suspend all licenses associated with the order. fn handle_subscription_deactivated( client: &reqwest::Client, data: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_subscription_deactivated {:?}", data); let subscription_id = data["id"].as_str().ok_or("invalid format (.id)")?; info!("subscription deactivated: {}", subscription_id); let orders = fastspring::get_subscription_entries(client, subscription_id)?; // find the original order // according to the API, this is the entry whose ".reference" field does not include // a "B" (for "billing") at the end. All the others are subscription billing orders. let original_order = orders.as_array().ok_or("invalid format (orders)")?.iter().find(|&order| { let order = &order["order"]; if order["reference"].is_null() { return false; } if let Some(s) = order["reference"].as_str() { !s.ends_with('B') } else { false } }); let original_order = original_order.ok_or("could not find original order")?; let order_items = original_order["order"]["items"] .as_array() .ok_or("invalid format (.order.items)")?; // Collect all licenses to revoke let mut licenses_to_revoke = Vec::new(); for item in order_items.iter() { //let product = &item["product"]; for (_k, v) in item["fulfillments"] .as_object() .ok_or("invalid format (.fulfillments)")? .iter() { if let Some(licenses) = v.as_array() { for l in licenses { let code = if let Some(s) = l["license"].as_str() { s } else { continue; }; licenses_to_revoke.push(String::from(code)); } } } } // revoke all licenses for lic in licenses_to_revoke.iter() { let key = license_key(lic).ok_or("invalid license key")?; keygen::revoke_license(key)?; } Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } /// Handles license creation requests (coming from FastSpring). fn handle_keygen_create(req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { if!fastspring::verify_license_gen(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let params: HashMap<_, _> = url::form_urlencoded::parse(match req.body() { Body::Text(ref s) => s.as_bytes(), _ => return Err("invalid request body".into()), }) .collect(); //debug!("params = {:?}", params); let subscription = params .get("subscription") .ok_or("invalid query parameters (no subscription)")?; let policy_id = params .get("policy") .ok_or("invalid query parameters (no policy)")?; let quantity: u32 = params .get("quantity") .ok_or("invalid query parameters (no quantity)")? .parse()?; let (codes,errors) = generate_licenses(subscription, policy_id, quantity, None, false); if!errors.is_empty() { Err(format!("errors encountered while generating licenses ({} successfully generated)", codes.len()).as_str())? } let codes = codes.join("\n"); Ok(Response::builder() .status(http::StatusCode::OK) .header(CONTENT_TYPE, "text/plain") .body(codes.into()) .unwrap()) } fn not_found(_req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { Ok(Response::builder() .status(http::StatusCode::NOT_FOUND) .body(Body::default()) .unwrap()) } fn not_allowed(_req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { Ok(Response::builder() .status(http::StatusCode::METHOD_NOT_ALLOWED) .body(Body::default()) .unwrap()) } fn main() -> Result<(), Box<dyn Error>> { env_logger::init(); dotenv::dotenv().ok(); lambda!(router); Ok(()) }
router
identifier_name
lambda.rs
use dotenv; use fastspring_keygen_integration::fastspring; use fastspring_keygen_integration::keygen; use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license}; use fastspring_keygen_integration::util; use fastspring_keygen_integration::patreon; use http::header::CONTENT_TYPE; use lambda_http::{lambda, Body, Request, RequestExt, Response}; use lambda_runtime::error::HandlerError; use lambda_runtime::Context; use log::{debug, info, warn}; use std::collections::HashMap; use std::error::Error; use std::env; use lazy_static::lazy_static; use lettre::transport::smtp::authentication::Credentials; use lettre::{Message, SmtpTransport, Transport}; lazy_static! { static ref MNPRX_COMMUNITY_KEYGEN_POLICY_ID: String = env::var("MNPRX_COMMUNITY_KEYGEN_POLICY_ID").unwrap(); static ref SMTP_SERVER: String = env::var("SMTP_SERVER").unwrap(); static ref SMTP_USERNAME: String = env::var("SMTP_USERNAME").unwrap(); static ref SMTP_PASSWORD: String = env::var("SMTP_PASSWORD").unwrap(); } fn router(req: Request, c: Context) -> Result<Response<Body>, HandlerError> { debug!("router request={:?}", req); debug!("path={:?}", req.uri().path()); debug!("query={:?}", req.query_string_parameters()); let client = reqwest::Client::new(); match req.uri().path() { "/fastspring-keygen-integration-service/keygen/create" => match *req.method() { http::Method::POST => handle_keygen_create(req, c), _ => not_allowed(req, c), }, "/fastspring-keygen-integration-service/webhooks" => match *req.method() { http::Method::POST => handle_webhook(&client, req, c), _ => not_allowed(req, c), }, "/fastspring-keygen-integration-service/patreon" => match *req.method() { http::Method::POST => handle_patreon_webhook(&client, req, c), _ => not_allowed(req, c), }, _ => not_found(req, c), } } fn license_key(code: &str) -> Option<&str> { code.split('.').nth(1) } fn handle_patreon_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if!patreon::authentify_web_hook(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let trigger = req.headers().get("X-Patreon-Event") .ok_or("invalid format (X-Patreon-Event)")? .to_str().ok().ok_or("invalid format (X-Patreon-Event)")?; debug!("X-Patreon-Event: {}", trigger); let body = util::body_to_json(req.body())?; if trigger == "pledges:create" { patreon_handle_pledge_create(client, &body)?; } else if trigger == "pledges:delete" { patreon_handle_pledge_delete(client, &body)?; } Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Patreon pledge create trigger fn patreon_handle_pledge_create( client: &reqwest::Client, body: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_create {:?}", body); let user_id = body["data"]["relationships"]["patron"]["data"]["id"].as_str().ok_or("invalid format (.data.relationships.patron.data.id)")?; let mut user_email = None; let mut user_first_name = None; for included in body["included"].as_array().ok_or("invalid format (.included)")?.iter() { if included["id"].as_str().ok_or("invalid format (.included.#.id)")? == user_id { user_email = Some(included["attributes"]["email"].as_str().ok_or("invalid format (.included.#.attributes.email)")?); user_first_name = included["attributes"]["first_name"].as_str(); } } let user_email = user_email.ok_or("could not find patron email")?; debug!("patron email: {}", user_email); let license= keygen::generate_license( client, "PATREON", MNPRX_COMMUNITY_KEYGEN_POLICY_ID.as_ref(), None, Some(user_id), false)?; let user_name = body["data"]["relationships"]["patron"]["data"]["id"].as_str().unwrap_or(""); let email_body = format!(r##"Hi, Thank you for becoming our Patreon! You can activate your Flair Community license with the following key: {} For more information on how to install and activate your license, please refer to the documentation: https://docs.artineering.io/flair/setup/ If you encounter any issues, please feel free to reach out to us through Discord, we are here to help. Have fun using Flair and make sure to share your results with the community. Cheers, Your team at Artineering."##, license); // send the license to the patron let email = Message::builder() .from("Artineering <[email protected]>".parse().unwrap()) .reply_to("Artineering <[email protected]>".parse().unwrap()) .to(user_email.parse().unwrap()) .bcc("[email protected]".parse().unwrap()) .subject("[Flair] Your Community license key") .body(email_body) .unwrap(); let creds = Credentials::new(SMTP_USERNAME.clone(), SMTP_PASSWORD.clone()); let mailer = SmtpTransport::relay(SMTP_SERVER.as_ref()) .unwrap() .credentials(creds) .build(); match mailer.send(&email) { Ok(_) => info!("Email sent successfully"), Err(e) => panic!("Could not send email: {:?}", e), } Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } /// Patreon pledge delete trigger fn patreon_handle_pledge_delete( client: &reqwest::Client, data: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_delete {:?}", data); Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } fn handle_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if!fastspring::authentify_web_hook(&req)
let events_json = util::body_to_json(req.body())?; let events_json = events_json["events"].as_array().ok_or("invalid format")?; // TODO do not reply OK every time: check each event for e in events_json { let ty = e["type"].as_str().ok_or("invalid format")?; let data = &e["data"]; match ty { "subscription.deactivated" => { handle_subscription_deactivated(client, data)?; } _ => { warn!("unhandled webhook: {}", ty); } }; } Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Handles deactivation of subscriptions. /// /// This will suspend all licenses associated with the order. fn handle_subscription_deactivated( client: &reqwest::Client, data: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_subscription_deactivated {:?}", data); let subscription_id = data["id"].as_str().ok_or("invalid format (.id)")?; info!("subscription deactivated: {}", subscription_id); let orders = fastspring::get_subscription_entries(client, subscription_id)?; // find the original order // according to the API, this is the entry whose ".reference" field does not include // a "B" (for "billing") at the end. All the others are subscription billing orders. let original_order = orders.as_array().ok_or("invalid format (orders)")?.iter().find(|&order| { let order = &order["order"]; if order["reference"].is_null() { return false; } if let Some(s) = order["reference"].as_str() { !s.ends_with('B') } else { false } }); let original_order = original_order.ok_or("could not find original order")?; let order_items = original_order["order"]["items"] .as_array() .ok_or("invalid format (.order.items)")?; // Collect all licenses to revoke let mut licenses_to_revoke = Vec::new(); for item in order_items.iter() { //let product = &item["product"]; for (_k, v) in item["fulfillments"] .as_object() .ok_or("invalid format (.fulfillments)")? .iter() { if let Some(licenses) = v.as_array() { for l in licenses { let code = if let Some(s) = l["license"].as_str() { s } else { continue; }; licenses_to_revoke.push(String::from(code)); } } } } // revoke all licenses for lic in licenses_to_revoke.iter() { let key = license_key(lic).ok_or("invalid license key")?; keygen::revoke_license(key)?; } Ok(Response::builder() .status(http::StatusCode::OK) .body(().into()) .unwrap()) } /// Handles license creation requests (coming from FastSpring). fn handle_keygen_create(req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { if!fastspring::verify_license_gen(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); } let params: HashMap<_, _> = url::form_urlencoded::parse(match req.body() { Body::Text(ref s) => s.as_bytes(), _ => return Err("invalid request body".into()), }) .collect(); //debug!("params = {:?}", params); let subscription = params .get("subscription") .ok_or("invalid query parameters (no subscription)")?; let policy_id = params .get("policy") .ok_or("invalid query parameters (no policy)")?; let quantity: u32 = params .get("quantity") .ok_or("invalid query parameters (no quantity)")? .parse()?; let (codes,errors) = generate_licenses(subscription, policy_id, quantity, None, false); if!errors.is_empty() { Err(format!("errors encountered while generating licenses ({} successfully generated)", codes.len()).as_str())? } let codes = codes.join("\n"); Ok(Response::builder() .status(http::StatusCode::OK) .header(CONTENT_TYPE, "text/plain") .body(codes.into()) .unwrap()) } fn not_found(_req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { Ok(Response::builder() .status(http::StatusCode::NOT_FOUND) .body(Body::default()) .unwrap()) } fn not_allowed(_req: Request, _c: Context) -> Result<Response<Body>, HandlerError> { Ok(Response::builder() .status(http::StatusCode::METHOD_NOT_ALLOWED) .body(Body::default()) .unwrap()) } fn main() -> Result<(), Box<dyn Error>> { env_logger::init(); dotenv::dotenv().ok(); lambda!(router); Ok(()) }
{ return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); }
conditional_block
state.rs
use std::cmp::min; use std::collections::BTreeMap; use chrono::Utc; use tako::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use tako::ItemId; use tako::{define_wrapped_type, TaskId}; use crate::server::autoalloc::{AutoAllocService, LostWorkerDetails}; use crate::server::event::events::JobInfo; use crate::server::event::storage::EventStorage; use crate::server::job::Job; use crate::server::rpc::Backend; use crate::server::worker::Worker; use crate::transfer::messages::ServerInfo; use crate::WrappedRcRefCell; use crate::{JobId, JobTaskCount, Map, TakoTaskId, WorkerId}; pub struct State { jobs: crate::Map<JobId, Job>, workers: crate::Map<WorkerId, Worker>, // Here we store TaskId -> JobId data, but to make it sparse // we store ONLY the base_task_id there, i.e. each job has here // only one entry. // Example: // Real mapping: TaskId JobId // 1 -> 1 // 2 -> 1 // 3 -> 2 // 4 -> 2 // 5 -> 2 // The actual base_task_id_to_job will be 1 -> 1, 3 -> 2 // Therefore we need to find biggest key that is lower then a given task id // To make this query efficient, we use BTreeMap and not Map base_task_id_to_job_id: BTreeMap<TakoTaskId, JobId>, job_id_counter: <JobId as ItemId>::IdType, task_id_counter: <TaskId as ItemId>::IdType, pub(crate) autoalloc_service: Option<AutoAllocService>, event_storage: EventStorage, server_info: ServerInfo, } define_wrapped_type!(StateRef, State, pub); fn cancel_tasks_from_callback( state_ref: &StateRef, tako_ref: &Backend, job_id: JobId, tasks: Vec<TakoTaskId>, ) { if tasks.is_empty() { return; } log::debug!("Canceling {:?} tasks", tasks); let tako_ref = tako_ref.clone(); let state_ref = state_ref.clone(); tokio::task::spawn_local(async move { let message = FromGatewayMessage::CancelTasks(CancelTasks { tasks }); let response = tako_ref.send_tako_message(message).await.unwrap(); match response { ToGatewayMessage::CancelTasksResponse(msg) => { let mut state = state_ref.get_mut(); if let Some(job) = state.get_job_mut(job_id) { log::debug!("Tasks {:?} canceled", msg.cancelled_tasks); log::debug!("Tasks {:?} already finished", msg.already_finished); for tako_id in msg.cancelled_tasks { job.set_cancel_state(tako_id, &tako_ref); } } } ToGatewayMessage::Error(msg) => { log::debug!("Canceling job {} failed: {}", job_id, msg.message); } _ => { panic!("Invalid message"); } }; }); } impl State { pub fn get_job(&self, job_id: JobId) -> Option<&Job> { self.jobs.get(&job_id) } pub fn get_job_mut(&mut self, job_id: JobId) -> Option<&mut Job> { self.jobs.get_mut(&job_id) } pub fn jobs(&self) -> impl Iterator<Item = &Job> { self.jobs.values() } pub fn add_worker(&mut self, worker: Worker) { let worker_id = worker.worker_id(); assert!(self.workers.insert(worker_id, worker).is_none()) } pub fn server_info(&self) -> &ServerInfo { &self.server_info } pub fn set_worker_port(&mut self, port: u16) { self.server_info.worker_port = port; } pub fn add_job(&mut self, job: Job) { let job_id = job.job_id; assert!(self .base_task_id_to_job_id .insert(job.base_task_id, job_id) .is_none()); self.event_storage.on_job_submitted( job_id, JobInfo { name: job.name.clone(), job_desc: job.job_desc.clone(), base_task_id: job.base_task_id, task_ids: job.tasks.iter().map(|(id, _)| *id).collect(), max_fails: job.max_fails, log: job.log.clone(), submission_date: job.submission_date, }, ); assert!(self.jobs.insert(job_id, job).is_none()); if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_job_created(job_id); } } /// Completely forgets this job, in order to reduce memory usage. pub(crate) fn forget_job(&mut self, job_id: JobId) -> Option<Job> { let job = match self.jobs.remove(&job_id) { Some(job) => { assert!(job.is_terminated()); job } None => { log::error!("Trying to forget unknown job {job_id}"); return None; } }; self.base_task_id_to_job_id.remove(&job.base_task_id); Some(job) } pub fn get_job_mut_by_tako_task_id(&mut self, task_id: TakoTaskId) -> Option<&mut Job>
pub fn new_job_id(&mut self) -> JobId { let id = self.job_id_counter; self.job_id_counter += 1; id.into() } pub fn revert_to_job_id(&mut self, id: JobId) { self.job_id_counter = id.as_num(); } pub fn last_n_ids(&self, n: u32) -> impl Iterator<Item = JobId> { let n = min(n, self.job_id_counter - 1); ((self.job_id_counter - n)..self.job_id_counter).map(|id| id.into()) } pub fn new_task_id(&mut self, task_count: JobTaskCount) -> TakoTaskId { let id = self.task_id_counter; self.task_id_counter += task_count; id.into() } pub fn get_workers(&self) -> &Map<WorkerId, Worker> { &self.workers } pub fn get_worker(&self, worker_id: WorkerId) -> Option<&Worker> { self.workers.get(&worker_id) } pub fn get_worker_mut(&mut self, worker_id: WorkerId) -> Option<&mut Worker> { self.workers.get_mut(&worker_id) } pub fn process_task_failed( &mut self, state_ref: &StateRef, tako_ref: &Backend, msg: TaskFailedMessage, ) { log::debug!("Task id={} failed: {:?}", msg.id, msg.info); let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); for task_id in msg.cancelled_tasks { log::debug!( "Task id={} canceled because of task dependency fails", task_id ); job.set_cancel_state(task_id, tako_ref); } job.set_failed_state(msg.id, msg.info.message, tako_ref); if let Some(max_fails) = job.max_fails { if job.counters.n_failed_tasks > max_fails { let task_ids = job.non_finished_task_ids(); cancel_tasks_from_callback(state_ref, tako_ref, job.job_id, task_ids); } } self.event_storage.on_task_failed(msg.id); } pub fn process_task_update(&mut self, msg: TaskUpdate, backend: &Backend) { log::debug!("Task id={} updated {:?}", msg.id, msg.state); let (mut job_id, mut is_job_terminated): (Option<JobId>, bool) = (None, false); match msg.state { TaskState::Running { worker_ids, context, } => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_running_state(msg.id, worker_ids.clone(), context); // TODO: Prepare it for multi-node tasks // This (incomplete) version just takes the first worker as "the worker" for task self.event_storage.on_task_started(msg.id, worker_ids[0]); } TaskState::Finished => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_finished_state(msg.id, backend); (job_id, is_job_terminated) = (Some(job.job_id), job.is_terminated()); self.event_storage.on_task_finished(msg.id); } TaskState::Waiting => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_waiting_state(msg.id); } TaskState::Invalid => { unreachable!() } }; if is_job_terminated { self.event_storage .on_job_completed(job_id.unwrap(), chrono::offset::Utc::now()); } } pub fn process_worker_new(&mut self, msg: NewWorkerMessage) { log::debug!("New worker id={}", msg.worker_id); self.add_worker(Worker::new(msg.worker_id, msg.configuration.clone())); // TODO: use observer in event storage instead of sending these messages directly if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_worker_connected(msg.worker_id, &msg.configuration); } self.event_storage .on_worker_added(msg.worker_id, msg.configuration); } pub fn process_worker_lost( &mut self, _state_ref: &StateRef, _tako_ref: &Backend, msg: LostWorkerMessage, ) { log::debug!("Worker lost id={}", msg.worker_id); let worker = self.workers.get_mut(&msg.worker_id).unwrap(); worker.set_offline_state(msg.reason.clone()); if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_worker_lost( msg.worker_id, &worker.configuration, LostWorkerDetails { reason: msg.reason.clone(), lifetime: (Utc::now() - worker.started_at()).to_std().unwrap(), }, ); } for task_id in msg.running_tasks { let job = self.get_job_mut_by_tako_task_id(task_id).unwrap(); job.set_waiting_state(task_id); } self.event_storage.on_worker_lost(msg.worker_id, msg.reason); } pub fn stop_autoalloc(&mut self) { // Drop the sender self.autoalloc_service = None; } pub fn event_storage(&self) -> &EventStorage { &self.event_storage } pub fn event_storage_mut(&mut self) -> &mut EventStorage { &mut self.event_storage } pub fn autoalloc(&self) -> &AutoAllocService { self.autoalloc_service.as_ref().unwrap() } } impl StateRef { pub fn new(event_storage: EventStorage, server_info: ServerInfo) -> StateRef { Self(WrappedRcRefCell::wrap(State { jobs: Default::default(), workers: Default::default(), base_task_id_to_job_id: Default::default(), job_id_counter: 1, task_id_counter: 1, autoalloc_service: None, event_storage, server_info, })) } } #[cfg(test)] mod tests { use tako::program::{ProgramDefinition, StdioDef}; use crate::common::arraydef::IntArray; use crate::server::job::Job; use crate::server::state::State; use crate::tests::utils::create_hq_state; use crate::transfer::messages::{JobDescription, PinMode, TaskDescription}; use crate::{JobId, TakoTaskId}; fn dummy_program_definition() -> ProgramDefinition { ProgramDefinition { args: vec![], env: Default::default(), stdout: StdioDef::Null, stderr: StdioDef::Null, stdin: vec![], cwd: Default::default(), } } fn test_job<J: Into<JobId>, T: Into<TakoTaskId>>( ids: IntArray, job_id: J, base_task_id: T, ) -> Job { let job_desc = JobDescription::Array { ids, entries: None, task_desc: TaskDescription { program: dummy_program_definition(), resources: Default::default(), pin_mode: PinMode::None, task_dir: false, time_limit: None, priority: 0, crash_limit: 5, }, }; Job::new( job_desc, job_id.into(), base_task_id.into(), "".to_string(), None, None, Default::default(), ) } fn check_id<T: Into<TakoTaskId>>(state: &mut State, task_id: T, expected: Option<u32>) { assert_eq!( state .get_job_mut_by_tako_task_id(task_id.into()) .map(|j| j.job_id.as_num()), expected ); } #[test] fn test_find_job_id_by_task_id() { let state_ref = create_hq_state(); let mut state = state_ref.get_mut(); state.add_job(test_job(IntArray::from_range(0, 10), 223, 100)); state.add_job(test_job(IntArray::from_range(0, 15), 224, 110)); state.add_job(test_job(IntArray::from_id(0), 225, 125)); state.add_job(test_job(IntArray::from_id(0), 226, 126)); state.add_job(test_job(IntArray::from_id(0), 227, 130)); let state = &mut state; check_id(state, 99, None); check_id(state, 100, Some(223)); check_id(state, 101, Some(223)); check_id(state, 109, Some(223)); check_id(state, 110, Some(224)); check_id(state, 124, Some(224)); check_id(state, 125, Some(225)); check_id(state, 126, Some(226)); check_id(state, 127, None); check_id(state, 129, None); check_id(state, 130, Some(227)); check_id(state, 131, None); } }
{ let job_id: JobId = *self.base_task_id_to_job_id.range(..=task_id).next_back()?.1; let job = self.jobs.get_mut(&job_id)?; if task_id < TakoTaskId::new( job.base_task_id.as_num() + job.n_tasks() as <TaskId as ItemId>::IdType, ) { Some(job) } else { None } }
identifier_body
state.rs
use std::cmp::min; use std::collections::BTreeMap; use chrono::Utc; use tako::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use tako::ItemId; use tako::{define_wrapped_type, TaskId}; use crate::server::autoalloc::{AutoAllocService, LostWorkerDetails}; use crate::server::event::events::JobInfo; use crate::server::event::storage::EventStorage; use crate::server::job::Job; use crate::server::rpc::Backend; use crate::server::worker::Worker; use crate::transfer::messages::ServerInfo; use crate::WrappedRcRefCell; use crate::{JobId, JobTaskCount, Map, TakoTaskId, WorkerId}; pub struct State { jobs: crate::Map<JobId, Job>, workers: crate::Map<WorkerId, Worker>, // Here we store TaskId -> JobId data, but to make it sparse // we store ONLY the base_task_id there, i.e. each job has here // only one entry. // Example: // Real mapping: TaskId JobId // 1 -> 1 // 2 -> 1 // 3 -> 2 // 4 -> 2 // 5 -> 2 // The actual base_task_id_to_job will be 1 -> 1, 3 -> 2 // Therefore we need to find biggest key that is lower then a given task id // To make this query efficient, we use BTreeMap and not Map base_task_id_to_job_id: BTreeMap<TakoTaskId, JobId>, job_id_counter: <JobId as ItemId>::IdType, task_id_counter: <TaskId as ItemId>::IdType, pub(crate) autoalloc_service: Option<AutoAllocService>, event_storage: EventStorage, server_info: ServerInfo, } define_wrapped_type!(StateRef, State, pub); fn cancel_tasks_from_callback( state_ref: &StateRef, tako_ref: &Backend, job_id: JobId, tasks: Vec<TakoTaskId>, ) { if tasks.is_empty() { return; } log::debug!("Canceling {:?} tasks", tasks); let tako_ref = tako_ref.clone(); let state_ref = state_ref.clone(); tokio::task::spawn_local(async move { let message = FromGatewayMessage::CancelTasks(CancelTasks { tasks }); let response = tako_ref.send_tako_message(message).await.unwrap(); match response { ToGatewayMessage::CancelTasksResponse(msg) => { let mut state = state_ref.get_mut(); if let Some(job) = state.get_job_mut(job_id) { log::debug!("Tasks {:?} canceled", msg.cancelled_tasks); log::debug!("Tasks {:?} already finished", msg.already_finished); for tako_id in msg.cancelled_tasks { job.set_cancel_state(tako_id, &tako_ref); } } } ToGatewayMessage::Error(msg) => { log::debug!("Canceling job {} failed: {}", job_id, msg.message); } _ => { panic!("Invalid message"); } }; }); } impl State { pub fn get_job(&self, job_id: JobId) -> Option<&Job> { self.jobs.get(&job_id) } pub fn get_job_mut(&mut self, job_id: JobId) -> Option<&mut Job> { self.jobs.get_mut(&job_id) } pub fn jobs(&self) -> impl Iterator<Item = &Job> { self.jobs.values() } pub fn add_worker(&mut self, worker: Worker) { let worker_id = worker.worker_id(); assert!(self.workers.insert(worker_id, worker).is_none()) } pub fn server_info(&self) -> &ServerInfo { &self.server_info } pub fn set_worker_port(&mut self, port: u16) { self.server_info.worker_port = port; } pub fn add_job(&mut self, job: Job) { let job_id = job.job_id; assert!(self .base_task_id_to_job_id .insert(job.base_task_id, job_id) .is_none()); self.event_storage.on_job_submitted( job_id, JobInfo { name: job.name.clone(), job_desc: job.job_desc.clone(), base_task_id: job.base_task_id, task_ids: job.tasks.iter().map(|(id, _)| *id).collect(), max_fails: job.max_fails, log: job.log.clone(), submission_date: job.submission_date, }, ); assert!(self.jobs.insert(job_id, job).is_none()); if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_job_created(job_id); } } /// Completely forgets this job, in order to reduce memory usage. pub(crate) fn forget_job(&mut self, job_id: JobId) -> Option<Job> { let job = match self.jobs.remove(&job_id) { Some(job) => { assert!(job.is_terminated()); job } None => { log::error!("Trying to forget unknown job {job_id}"); return None; } }; self.base_task_id_to_job_id.remove(&job.base_task_id); Some(job) } pub fn get_job_mut_by_tako_task_id(&mut self, task_id: TakoTaskId) -> Option<&mut Job> { let job_id: JobId = *self.base_task_id_to_job_id.range(..=task_id).next_back()?.1; let job = self.jobs.get_mut(&job_id)?; if task_id < TakoTaskId::new( job.base_task_id.as_num() + job.n_tasks() as <TaskId as ItemId>::IdType, ) { Some(job) } else { None } } pub fn new_job_id(&mut self) -> JobId { let id = self.job_id_counter; self.job_id_counter += 1; id.into() } pub fn revert_to_job_id(&mut self, id: JobId) { self.job_id_counter = id.as_num(); } pub fn last_n_ids(&self, n: u32) -> impl Iterator<Item = JobId> { let n = min(n, self.job_id_counter - 1); ((self.job_id_counter - n)..self.job_id_counter).map(|id| id.into()) } pub fn new_task_id(&mut self, task_count: JobTaskCount) -> TakoTaskId { let id = self.task_id_counter; self.task_id_counter += task_count; id.into() } pub fn get_workers(&self) -> &Map<WorkerId, Worker> { &self.workers } pub fn get_worker(&self, worker_id: WorkerId) -> Option<&Worker> { self.workers.get(&worker_id) } pub fn get_worker_mut(&mut self, worker_id: WorkerId) -> Option<&mut Worker> { self.workers.get_mut(&worker_id) } pub fn process_task_failed( &mut self, state_ref: &StateRef, tako_ref: &Backend, msg: TaskFailedMessage, ) { log::debug!("Task id={} failed: {:?}", msg.id, msg.info); let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); for task_id in msg.cancelled_tasks { log::debug!( "Task id={} canceled because of task dependency fails", task_id ); job.set_cancel_state(task_id, tako_ref); } job.set_failed_state(msg.id, msg.info.message, tako_ref); if let Some(max_fails) = job.max_fails { if job.counters.n_failed_tasks > max_fails { let task_ids = job.non_finished_task_ids(); cancel_tasks_from_callback(state_ref, tako_ref, job.job_id, task_ids); } } self.event_storage.on_task_failed(msg.id); } pub fn
(&mut self, msg: TaskUpdate, backend: &Backend) { log::debug!("Task id={} updated {:?}", msg.id, msg.state); let (mut job_id, mut is_job_terminated): (Option<JobId>, bool) = (None, false); match msg.state { TaskState::Running { worker_ids, context, } => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_running_state(msg.id, worker_ids.clone(), context); // TODO: Prepare it for multi-node tasks // This (incomplete) version just takes the first worker as "the worker" for task self.event_storage.on_task_started(msg.id, worker_ids[0]); } TaskState::Finished => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_finished_state(msg.id, backend); (job_id, is_job_terminated) = (Some(job.job_id), job.is_terminated()); self.event_storage.on_task_finished(msg.id); } TaskState::Waiting => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_waiting_state(msg.id); } TaskState::Invalid => { unreachable!() } }; if is_job_terminated { self.event_storage .on_job_completed(job_id.unwrap(), chrono::offset::Utc::now()); } } pub fn process_worker_new(&mut self, msg: NewWorkerMessage) { log::debug!("New worker id={}", msg.worker_id); self.add_worker(Worker::new(msg.worker_id, msg.configuration.clone())); // TODO: use observer in event storage instead of sending these messages directly if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_worker_connected(msg.worker_id, &msg.configuration); } self.event_storage .on_worker_added(msg.worker_id, msg.configuration); } pub fn process_worker_lost( &mut self, _state_ref: &StateRef, _tako_ref: &Backend, msg: LostWorkerMessage, ) { log::debug!("Worker lost id={}", msg.worker_id); let worker = self.workers.get_mut(&msg.worker_id).unwrap(); worker.set_offline_state(msg.reason.clone()); if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_worker_lost( msg.worker_id, &worker.configuration, LostWorkerDetails { reason: msg.reason.clone(), lifetime: (Utc::now() - worker.started_at()).to_std().unwrap(), }, ); } for task_id in msg.running_tasks { let job = self.get_job_mut_by_tako_task_id(task_id).unwrap(); job.set_waiting_state(task_id); } self.event_storage.on_worker_lost(msg.worker_id, msg.reason); } pub fn stop_autoalloc(&mut self) { // Drop the sender self.autoalloc_service = None; } pub fn event_storage(&self) -> &EventStorage { &self.event_storage } pub fn event_storage_mut(&mut self) -> &mut EventStorage { &mut self.event_storage } pub fn autoalloc(&self) -> &AutoAllocService { self.autoalloc_service.as_ref().unwrap() } } impl StateRef { pub fn new(event_storage: EventStorage, server_info: ServerInfo) -> StateRef { Self(WrappedRcRefCell::wrap(State { jobs: Default::default(), workers: Default::default(), base_task_id_to_job_id: Default::default(), job_id_counter: 1, task_id_counter: 1, autoalloc_service: None, event_storage, server_info, })) } } #[cfg(test)] mod tests { use tako::program::{ProgramDefinition, StdioDef}; use crate::common::arraydef::IntArray; use crate::server::job::Job; use crate::server::state::State; use crate::tests::utils::create_hq_state; use crate::transfer::messages::{JobDescription, PinMode, TaskDescription}; use crate::{JobId, TakoTaskId}; fn dummy_program_definition() -> ProgramDefinition { ProgramDefinition { args: vec![], env: Default::default(), stdout: StdioDef::Null, stderr: StdioDef::Null, stdin: vec![], cwd: Default::default(), } } fn test_job<J: Into<JobId>, T: Into<TakoTaskId>>( ids: IntArray, job_id: J, base_task_id: T, ) -> Job { let job_desc = JobDescription::Array { ids, entries: None, task_desc: TaskDescription { program: dummy_program_definition(), resources: Default::default(), pin_mode: PinMode::None, task_dir: false, time_limit: None, priority: 0, crash_limit: 5, }, }; Job::new( job_desc, job_id.into(), base_task_id.into(), "".to_string(), None, None, Default::default(), ) } fn check_id<T: Into<TakoTaskId>>(state: &mut State, task_id: T, expected: Option<u32>) { assert_eq!( state .get_job_mut_by_tako_task_id(task_id.into()) .map(|j| j.job_id.as_num()), expected ); } #[test] fn test_find_job_id_by_task_id() { let state_ref = create_hq_state(); let mut state = state_ref.get_mut(); state.add_job(test_job(IntArray::from_range(0, 10), 223, 100)); state.add_job(test_job(IntArray::from_range(0, 15), 224, 110)); state.add_job(test_job(IntArray::from_id(0), 225, 125)); state.add_job(test_job(IntArray::from_id(0), 226, 126)); state.add_job(test_job(IntArray::from_id(0), 227, 130)); let state = &mut state; check_id(state, 99, None); check_id(state, 100, Some(223)); check_id(state, 101, Some(223)); check_id(state, 109, Some(223)); check_id(state, 110, Some(224)); check_id(state, 124, Some(224)); check_id(state, 125, Some(225)); check_id(state, 126, Some(226)); check_id(state, 127, None); check_id(state, 129, None); check_id(state, 130, Some(227)); check_id(state, 131, None); } }
process_task_update
identifier_name
state.rs
use std::cmp::min; use std::collections::BTreeMap; use chrono::Utc; use tako::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use tako::ItemId; use tako::{define_wrapped_type, TaskId}; use crate::server::autoalloc::{AutoAllocService, LostWorkerDetails}; use crate::server::event::events::JobInfo; use crate::server::event::storage::EventStorage; use crate::server::job::Job; use crate::server::rpc::Backend; use crate::server::worker::Worker; use crate::transfer::messages::ServerInfo; use crate::WrappedRcRefCell; use crate::{JobId, JobTaskCount, Map, TakoTaskId, WorkerId}; pub struct State { jobs: crate::Map<JobId, Job>, workers: crate::Map<WorkerId, Worker>, // Here we store TaskId -> JobId data, but to make it sparse // we store ONLY the base_task_id there, i.e. each job has here // only one entry. // Example: // Real mapping: TaskId JobId // 1 -> 1 // 2 -> 1 // 3 -> 2 // 4 -> 2 // 5 -> 2 // The actual base_task_id_to_job will be 1 -> 1, 3 -> 2 // Therefore we need to find biggest key that is lower then a given task id // To make this query efficient, we use BTreeMap and not Map base_task_id_to_job_id: BTreeMap<TakoTaskId, JobId>, job_id_counter: <JobId as ItemId>::IdType, task_id_counter: <TaskId as ItemId>::IdType, pub(crate) autoalloc_service: Option<AutoAllocService>, event_storage: EventStorage, server_info: ServerInfo, } define_wrapped_type!(StateRef, State, pub); fn cancel_tasks_from_callback( state_ref: &StateRef, tako_ref: &Backend, job_id: JobId, tasks: Vec<TakoTaskId>, ) { if tasks.is_empty() { return; } log::debug!("Canceling {:?} tasks", tasks); let tako_ref = tako_ref.clone(); let state_ref = state_ref.clone(); tokio::task::spawn_local(async move { let message = FromGatewayMessage::CancelTasks(CancelTasks { tasks }); let response = tako_ref.send_tako_message(message).await.unwrap(); match response { ToGatewayMessage::CancelTasksResponse(msg) => { let mut state = state_ref.get_mut(); if let Some(job) = state.get_job_mut(job_id) { log::debug!("Tasks {:?} canceled", msg.cancelled_tasks); log::debug!("Tasks {:?} already finished", msg.already_finished); for tako_id in msg.cancelled_tasks { job.set_cancel_state(tako_id, &tako_ref); } } } ToGatewayMessage::Error(msg) => { log::debug!("Canceling job {} failed: {}", job_id, msg.message); } _ => { panic!("Invalid message"); } }; }); } impl State { pub fn get_job(&self, job_id: JobId) -> Option<&Job> { self.jobs.get(&job_id) } pub fn get_job_mut(&mut self, job_id: JobId) -> Option<&mut Job> { self.jobs.get_mut(&job_id) } pub fn jobs(&self) -> impl Iterator<Item = &Job> { self.jobs.values() } pub fn add_worker(&mut self, worker: Worker) { let worker_id = worker.worker_id(); assert!(self.workers.insert(worker_id, worker).is_none()) } pub fn server_info(&self) -> &ServerInfo { &self.server_info } pub fn set_worker_port(&mut self, port: u16) { self.server_info.worker_port = port; } pub fn add_job(&mut self, job: Job) { let job_id = job.job_id; assert!(self .base_task_id_to_job_id .insert(job.base_task_id, job_id) .is_none()); self.event_storage.on_job_submitted( job_id, JobInfo { name: job.name.clone(), job_desc: job.job_desc.clone(), base_task_id: job.base_task_id, task_ids: job.tasks.iter().map(|(id, _)| *id).collect(), max_fails: job.max_fails, log: job.log.clone(), submission_date: job.submission_date, }, ); assert!(self.jobs.insert(job_id, job).is_none()); if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_job_created(job_id); } } /// Completely forgets this job, in order to reduce memory usage. pub(crate) fn forget_job(&mut self, job_id: JobId) -> Option<Job> { let job = match self.jobs.remove(&job_id) { Some(job) => { assert!(job.is_terminated()); job } None => { log::error!("Trying to forget unknown job {job_id}"); return None; } }; self.base_task_id_to_job_id.remove(&job.base_task_id); Some(job) } pub fn get_job_mut_by_tako_task_id(&mut self, task_id: TakoTaskId) -> Option<&mut Job> { let job_id: JobId = *self.base_task_id_to_job_id.range(..=task_id).next_back()?.1; let job = self.jobs.get_mut(&job_id)?; if task_id < TakoTaskId::new( job.base_task_id.as_num() + job.n_tasks() as <TaskId as ItemId>::IdType, ) { Some(job) } else { None } } pub fn new_job_id(&mut self) -> JobId { let id = self.job_id_counter; self.job_id_counter += 1; id.into() } pub fn revert_to_job_id(&mut self, id: JobId) { self.job_id_counter = id.as_num(); } pub fn last_n_ids(&self, n: u32) -> impl Iterator<Item = JobId> { let n = min(n, self.job_id_counter - 1); ((self.job_id_counter - n)..self.job_id_counter).map(|id| id.into()) } pub fn new_task_id(&mut self, task_count: JobTaskCount) -> TakoTaskId { let id = self.task_id_counter; self.task_id_counter += task_count; id.into() } pub fn get_workers(&self) -> &Map<WorkerId, Worker> { &self.workers } pub fn get_worker(&self, worker_id: WorkerId) -> Option<&Worker> { self.workers.get(&worker_id) } pub fn get_worker_mut(&mut self, worker_id: WorkerId) -> Option<&mut Worker> { self.workers.get_mut(&worker_id) } pub fn process_task_failed( &mut self, state_ref: &StateRef, tako_ref: &Backend, msg: TaskFailedMessage, ) { log::debug!("Task id={} failed: {:?}", msg.id, msg.info); let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); for task_id in msg.cancelled_tasks { log::debug!( "Task id={} canceled because of task dependency fails", task_id ); job.set_cancel_state(task_id, tako_ref); } job.set_failed_state(msg.id, msg.info.message, tako_ref); if let Some(max_fails) = job.max_fails { if job.counters.n_failed_tasks > max_fails { let task_ids = job.non_finished_task_ids(); cancel_tasks_from_callback(state_ref, tako_ref, job.job_id, task_ids); } } self.event_storage.on_task_failed(msg.id); } pub fn process_task_update(&mut self, msg: TaskUpdate, backend: &Backend) { log::debug!("Task id={} updated {:?}", msg.id, msg.state); let (mut job_id, mut is_job_terminated): (Option<JobId>, bool) = (None, false); match msg.state { TaskState::Running { worker_ids, context, } => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_running_state(msg.id, worker_ids.clone(), context); // TODO: Prepare it for multi-node tasks // This (incomplete) version just takes the first worker as "the worker" for task self.event_storage.on_task_started(msg.id, worker_ids[0]); } TaskState::Finished => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_finished_state(msg.id, backend); (job_id, is_job_terminated) = (Some(job.job_id), job.is_terminated()); self.event_storage.on_task_finished(msg.id); } TaskState::Waiting => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_waiting_state(msg.id); } TaskState::Invalid => { unreachable!() } }; if is_job_terminated { self.event_storage .on_job_completed(job_id.unwrap(), chrono::offset::Utc::now()); } } pub fn process_worker_new(&mut self, msg: NewWorkerMessage) { log::debug!("New worker id={}", msg.worker_id); self.add_worker(Worker::new(msg.worker_id, msg.configuration.clone())); // TODO: use observer in event storage instead of sending these messages directly if let Some(autoalloc) = &self.autoalloc_service
self.event_storage .on_worker_added(msg.worker_id, msg.configuration); } pub fn process_worker_lost( &mut self, _state_ref: &StateRef, _tako_ref: &Backend, msg: LostWorkerMessage, ) { log::debug!("Worker lost id={}", msg.worker_id); let worker = self.workers.get_mut(&msg.worker_id).unwrap(); worker.set_offline_state(msg.reason.clone()); if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_worker_lost( msg.worker_id, &worker.configuration, LostWorkerDetails { reason: msg.reason.clone(), lifetime: (Utc::now() - worker.started_at()).to_std().unwrap(), }, ); } for task_id in msg.running_tasks { let job = self.get_job_mut_by_tako_task_id(task_id).unwrap(); job.set_waiting_state(task_id); } self.event_storage.on_worker_lost(msg.worker_id, msg.reason); } pub fn stop_autoalloc(&mut self) { // Drop the sender self.autoalloc_service = None; } pub fn event_storage(&self) -> &EventStorage { &self.event_storage } pub fn event_storage_mut(&mut self) -> &mut EventStorage { &mut self.event_storage } pub fn autoalloc(&self) -> &AutoAllocService { self.autoalloc_service.as_ref().unwrap() } } impl StateRef { pub fn new(event_storage: EventStorage, server_info: ServerInfo) -> StateRef { Self(WrappedRcRefCell::wrap(State { jobs: Default::default(), workers: Default::default(), base_task_id_to_job_id: Default::default(), job_id_counter: 1, task_id_counter: 1, autoalloc_service: None, event_storage, server_info, })) } } #[cfg(test)] mod tests { use tako::program::{ProgramDefinition, StdioDef}; use crate::common::arraydef::IntArray; use crate::server::job::Job; use crate::server::state::State; use crate::tests::utils::create_hq_state; use crate::transfer::messages::{JobDescription, PinMode, TaskDescription}; use crate::{JobId, TakoTaskId}; fn dummy_program_definition() -> ProgramDefinition { ProgramDefinition { args: vec![], env: Default::default(), stdout: StdioDef::Null, stderr: StdioDef::Null, stdin: vec![], cwd: Default::default(), } } fn test_job<J: Into<JobId>, T: Into<TakoTaskId>>( ids: IntArray, job_id: J, base_task_id: T, ) -> Job { let job_desc = JobDescription::Array { ids, entries: None, task_desc: TaskDescription { program: dummy_program_definition(), resources: Default::default(), pin_mode: PinMode::None, task_dir: false, time_limit: None, priority: 0, crash_limit: 5, }, }; Job::new( job_desc, job_id.into(), base_task_id.into(), "".to_string(), None, None, Default::default(), ) } fn check_id<T: Into<TakoTaskId>>(state: &mut State, task_id: T, expected: Option<u32>) { assert_eq!( state .get_job_mut_by_tako_task_id(task_id.into()) .map(|j| j.job_id.as_num()), expected ); } #[test] fn test_find_job_id_by_task_id() { let state_ref = create_hq_state(); let mut state = state_ref.get_mut(); state.add_job(test_job(IntArray::from_range(0, 10), 223, 100)); state.add_job(test_job(IntArray::from_range(0, 15), 224, 110)); state.add_job(test_job(IntArray::from_id(0), 225, 125)); state.add_job(test_job(IntArray::from_id(0), 226, 126)); state.add_job(test_job(IntArray::from_id(0), 227, 130)); let state = &mut state; check_id(state, 99, None); check_id(state, 100, Some(223)); check_id(state, 101, Some(223)); check_id(state, 109, Some(223)); check_id(state, 110, Some(224)); check_id(state, 124, Some(224)); check_id(state, 125, Some(225)); check_id(state, 126, Some(226)); check_id(state, 127, None); check_id(state, 129, None); check_id(state, 130, Some(227)); check_id(state, 131, None); } }
{ autoalloc.on_worker_connected(msg.worker_id, &msg.configuration); }
conditional_block
state.rs
use std::cmp::min; use std::collections::BTreeMap; use chrono::Utc; use tako::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use tako::ItemId; use tako::{define_wrapped_type, TaskId}; use crate::server::autoalloc::{AutoAllocService, LostWorkerDetails}; use crate::server::event::events::JobInfo; use crate::server::event::storage::EventStorage; use crate::server::job::Job; use crate::server::rpc::Backend; use crate::server::worker::Worker; use crate::transfer::messages::ServerInfo; use crate::WrappedRcRefCell; use crate::{JobId, JobTaskCount, Map, TakoTaskId, WorkerId}; pub struct State { jobs: crate::Map<JobId, Job>, workers: crate::Map<WorkerId, Worker>, // Here we store TaskId -> JobId data, but to make it sparse // we store ONLY the base_task_id there, i.e. each job has here // only one entry. // Example: // Real mapping: TaskId JobId // 1 -> 1 // 2 -> 1 // 3 -> 2 // 4 -> 2 // 5 -> 2 // The actual base_task_id_to_job will be 1 -> 1, 3 -> 2 // Therefore we need to find biggest key that is lower then a given task id // To make this query efficient, we use BTreeMap and not Map base_task_id_to_job_id: BTreeMap<TakoTaskId, JobId>, job_id_counter: <JobId as ItemId>::IdType, task_id_counter: <TaskId as ItemId>::IdType, pub(crate) autoalloc_service: Option<AutoAllocService>, event_storage: EventStorage, server_info: ServerInfo, } define_wrapped_type!(StateRef, State, pub); fn cancel_tasks_from_callback( state_ref: &StateRef, tako_ref: &Backend, job_id: JobId, tasks: Vec<TakoTaskId>, ) { if tasks.is_empty() { return; } log::debug!("Canceling {:?} tasks", tasks); let tako_ref = tako_ref.clone(); let state_ref = state_ref.clone(); tokio::task::spawn_local(async move { let message = FromGatewayMessage::CancelTasks(CancelTasks { tasks }); let response = tako_ref.send_tako_message(message).await.unwrap(); match response { ToGatewayMessage::CancelTasksResponse(msg) => { let mut state = state_ref.get_mut(); if let Some(job) = state.get_job_mut(job_id) { log::debug!("Tasks {:?} canceled", msg.cancelled_tasks); log::debug!("Tasks {:?} already finished", msg.already_finished); for tako_id in msg.cancelled_tasks { job.set_cancel_state(tako_id, &tako_ref); } } } ToGatewayMessage::Error(msg) => { log::debug!("Canceling job {} failed: {}", job_id, msg.message); } _ => { panic!("Invalid message"); } }; }); } impl State { pub fn get_job(&self, job_id: JobId) -> Option<&Job> { self.jobs.get(&job_id) } pub fn get_job_mut(&mut self, job_id: JobId) -> Option<&mut Job> { self.jobs.get_mut(&job_id) } pub fn jobs(&self) -> impl Iterator<Item = &Job> { self.jobs.values() } pub fn add_worker(&mut self, worker: Worker) { let worker_id = worker.worker_id(); assert!(self.workers.insert(worker_id, worker).is_none()) } pub fn server_info(&self) -> &ServerInfo { &self.server_info } pub fn set_worker_port(&mut self, port: u16) { self.server_info.worker_port = port; } pub fn add_job(&mut self, job: Job) { let job_id = job.job_id; assert!(self .base_task_id_to_job_id .insert(job.base_task_id, job_id) .is_none()); self.event_storage.on_job_submitted( job_id, JobInfo { name: job.name.clone(), job_desc: job.job_desc.clone(), base_task_id: job.base_task_id, task_ids: job.tasks.iter().map(|(id, _)| *id).collect(), max_fails: job.max_fails, log: job.log.clone(), submission_date: job.submission_date, }, ); assert!(self.jobs.insert(job_id, job).is_none()); if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_job_created(job_id); } } /// Completely forgets this job, in order to reduce memory usage. pub(crate) fn forget_job(&mut self, job_id: JobId) -> Option<Job> { let job = match self.jobs.remove(&job_id) { Some(job) => { assert!(job.is_terminated()); job } None => { log::error!("Trying to forget unknown job {job_id}"); return None; } }; self.base_task_id_to_job_id.remove(&job.base_task_id); Some(job) } pub fn get_job_mut_by_tako_task_id(&mut self, task_id: TakoTaskId) -> Option<&mut Job> { let job_id: JobId = *self.base_task_id_to_job_id.range(..=task_id).next_back()?.1; let job = self.jobs.get_mut(&job_id)?; if task_id < TakoTaskId::new( job.base_task_id.as_num() + job.n_tasks() as <TaskId as ItemId>::IdType, ) { Some(job) } else { None } } pub fn new_job_id(&mut self) -> JobId { let id = self.job_id_counter; self.job_id_counter += 1; id.into() } pub fn revert_to_job_id(&mut self, id: JobId) { self.job_id_counter = id.as_num(); } pub fn last_n_ids(&self, n: u32) -> impl Iterator<Item = JobId> { let n = min(n, self.job_id_counter - 1); ((self.job_id_counter - n)..self.job_id_counter).map(|id| id.into()) } pub fn new_task_id(&mut self, task_count: JobTaskCount) -> TakoTaskId { let id = self.task_id_counter; self.task_id_counter += task_count; id.into() } pub fn get_workers(&self) -> &Map<WorkerId, Worker> { &self.workers } pub fn get_worker(&self, worker_id: WorkerId) -> Option<&Worker> { self.workers.get(&worker_id) } pub fn get_worker_mut(&mut self, worker_id: WorkerId) -> Option<&mut Worker> { self.workers.get_mut(&worker_id) } pub fn process_task_failed( &mut self, state_ref: &StateRef, tako_ref: &Backend, msg: TaskFailedMessage, ) { log::debug!("Task id={} failed: {:?}", msg.id, msg.info); let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); for task_id in msg.cancelled_tasks { log::debug!( "Task id={} canceled because of task dependency fails", task_id ); job.set_cancel_state(task_id, tako_ref); } job.set_failed_state(msg.id, msg.info.message, tako_ref); if let Some(max_fails) = job.max_fails { if job.counters.n_failed_tasks > max_fails { let task_ids = job.non_finished_task_ids(); cancel_tasks_from_callback(state_ref, tako_ref, job.job_id, task_ids); } } self.event_storage.on_task_failed(msg.id); } pub fn process_task_update(&mut self, msg: TaskUpdate, backend: &Backend) { log::debug!("Task id={} updated {:?}", msg.id, msg.state); let (mut job_id, mut is_job_terminated): (Option<JobId>, bool) = (None, false); match msg.state { TaskState::Running { worker_ids, context, } => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_running_state(msg.id, worker_ids.clone(), context); // TODO: Prepare it for multi-node tasks // This (incomplete) version just takes the first worker as "the worker" for task self.event_storage.on_task_started(msg.id, worker_ids[0]); } TaskState::Finished => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_finished_state(msg.id, backend); (job_id, is_job_terminated) = (Some(job.job_id), job.is_terminated()); self.event_storage.on_task_finished(msg.id); } TaskState::Waiting => { let job = self.get_job_mut_by_tako_task_id(msg.id).unwrap(); job.set_waiting_state(msg.id); } TaskState::Invalid => { unreachable!() } }; if is_job_terminated { self.event_storage .on_job_completed(job_id.unwrap(), chrono::offset::Utc::now()); } } pub fn process_worker_new(&mut self, msg: NewWorkerMessage) { log::debug!("New worker id={}", msg.worker_id); self.add_worker(Worker::new(msg.worker_id, msg.configuration.clone())); // TODO: use observer in event storage instead of sending these messages directly if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_worker_connected(msg.worker_id, &msg.configuration); } self.event_storage .on_worker_added(msg.worker_id, msg.configuration); } pub fn process_worker_lost( &mut self, _state_ref: &StateRef, _tako_ref: &Backend, msg: LostWorkerMessage, ) { log::debug!("Worker lost id={}", msg.worker_id); let worker = self.workers.get_mut(&msg.worker_id).unwrap(); worker.set_offline_state(msg.reason.clone()); if let Some(autoalloc) = &self.autoalloc_service { autoalloc.on_worker_lost( msg.worker_id, &worker.configuration, LostWorkerDetails { reason: msg.reason.clone(), lifetime: (Utc::now() - worker.started_at()).to_std().unwrap(), }, ); } for task_id in msg.running_tasks { let job = self.get_job_mut_by_tako_task_id(task_id).unwrap(); job.set_waiting_state(task_id); } self.event_storage.on_worker_lost(msg.worker_id, msg.reason); } pub fn stop_autoalloc(&mut self) { // Drop the sender self.autoalloc_service = None; } pub fn event_storage(&self) -> &EventStorage { &self.event_storage } pub fn event_storage_mut(&mut self) -> &mut EventStorage { &mut self.event_storage } pub fn autoalloc(&self) -> &AutoAllocService { self.autoalloc_service.as_ref().unwrap() } } impl StateRef { pub fn new(event_storage: EventStorage, server_info: ServerInfo) -> StateRef { Self(WrappedRcRefCell::wrap(State { jobs: Default::default(), workers: Default::default(), base_task_id_to_job_id: Default::default(), job_id_counter: 1, task_id_counter: 1, autoalloc_service: None, event_storage, server_info, })) } } #[cfg(test)] mod tests { use tako::program::{ProgramDefinition, StdioDef}; use crate::common::arraydef::IntArray; use crate::server::job::Job; use crate::server::state::State; use crate::tests::utils::create_hq_state; use crate::transfer::messages::{JobDescription, PinMode, TaskDescription}; use crate::{JobId, TakoTaskId}; fn dummy_program_definition() -> ProgramDefinition { ProgramDefinition { args: vec![], env: Default::default(), stdout: StdioDef::Null, stderr: StdioDef::Null, stdin: vec![], cwd: Default::default(), } } fn test_job<J: Into<JobId>, T: Into<TakoTaskId>>( ids: IntArray, job_id: J, base_task_id: T, ) -> Job { let job_desc = JobDescription::Array { ids, entries: None, task_desc: TaskDescription { program: dummy_program_definition(), resources: Default::default(), pin_mode: PinMode::None, task_dir: false, time_limit: None, priority: 0, crash_limit: 5, }, }; Job::new( job_desc, job_id.into(), base_task_id.into(), "".to_string(), None, None, Default::default(), ) } fn check_id<T: Into<TakoTaskId>>(state: &mut State, task_id: T, expected: Option<u32>) {
assert_eq!( state .get_job_mut_by_tako_task_id(task_id.into()) .map(|j| j.job_id.as_num()), expected ); } #[test] fn test_find_job_id_by_task_id() { let state_ref = create_hq_state(); let mut state = state_ref.get_mut(); state.add_job(test_job(IntArray::from_range(0, 10), 223, 100)); state.add_job(test_job(IntArray::from_range(0, 15), 224, 110)); state.add_job(test_job(IntArray::from_id(0), 225, 125)); state.add_job(test_job(IntArray::from_id(0), 226, 126)); state.add_job(test_job(IntArray::from_id(0), 227, 130)); let state = &mut state; check_id(state, 99, None); check_id(state, 100, Some(223)); check_id(state, 101, Some(223)); check_id(state, 109, Some(223)); check_id(state, 110, Some(224)); check_id(state, 124, Some(224)); check_id(state, 125, Some(225)); check_id(state, 126, Some(226)); check_id(state, 127, None); check_id(state, 129, None); check_id(state, 130, Some(227)); check_id(state, 131, None); } }
random_line_split
parse.rs
use crate::{ parse_utils::*, substitute::{substitute, Substitution}, SubstitutionGroup, }; use proc_macro::{token_stream::IntoIter, Ident, Span, TokenStream, TokenTree}; use std::{collections::HashSet, iter::Peekable}; /// Parses the attribute part of an invocation of duplicate, returning /// all the substitutions that should be made to the item. pub(crate) fn parse_attr( attr: TokenStream, stream_span: Span, ) -> Result<Vec<SubstitutionGroup>, (Span, String)> { if identify_syntax(attr.clone(), stream_span)? { validate_verbose_attr(attr) } else { let substitutions = validate_short_attr(attr)?; let mut reorder = Vec::new(); for _ in 0..substitutions[0].2.len() { reorder.push(SubstitutionGroup::new()); } for (ident, args, subs) in substitutions { for (idx, sub) in subs.into_iter().enumerate() { let substitution = Substitution::new(&args, sub.into_iter()); if let Ok(substitution) = substitution { reorder[idx].add_substitution( Ident::new(&ident.clone(), Span::call_site()), substitution, )?; } else { return Err((Span::call_site(), "Failed creating substitution".into())); } } } Ok(reorder) } } /// True is verbose, false is short fn identify_syntax(attr: TokenStream, stream_span: Span) -> Result<bool, (Span, String)> { if let Some(token) = next_token(&mut attr.into_iter(), "Could not identify syntax type.")? { match token { TokenTree::Group(_) => Ok(true), TokenTree::Ident(_) => Ok(false), TokenTree::Punct(p) if is_nested_invocation(&p) => Ok(true), _ => { Err(( token.span(), "Expected substitution identifier or group. Received neither.".into(), )) }, } } else { Err((stream_span, "No substitutions found.".into())) } } /// Validates that the attribute part of a duplicate invocation uses /// the verbose syntax, and returns all the substitutions that should be made. fn validate_verbose_attr(attr: TokenStream) -> Result<Vec<SubstitutionGroup>, (Span, String)> { if attr.is_empty() { return Err((Span::call_site(), "No substitutions found.".into())); } let mut sub_groups = Vec::new(); let mut iter = attr.into_iter(); let mut substitution_ids = None; loop { if let Some(tree) = next_token(&mut iter, "Expected substitution group.")? { match tree { TokenTree::Punct(p) if is_nested_invocation(&p) => { let nested_duplicated = invoke_nested(&mut iter, p.span())?; let subs = validate_verbose_attr(nested_duplicated)?; sub_groups.extend(subs.into_iter()); }, _ => { sub_groups.push(extract_verbose_substitutions(tree, &substitution_ids)?); if None == substitution_ids { substitution_ids = Some(sub_groups[0].identifiers().cloned().collect()) } }, } } else { break; } } Ok(sub_groups) } /// Extracts a substitution group in the verbose syntax. fn
( tree: TokenTree, existing: &Option<HashSet<String>>, ) -> Result<SubstitutionGroup, (Span, String)> { // Must get span now, before it's corrupted. let tree_span = tree.span(); let group = check_group( tree, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \ ]\n]", )?; if group.stream().into_iter().count() == 0 { return Err((group.span(), "No substitution groups found.".into())); } let mut substitutions = SubstitutionGroup::new(); let mut stream = group.stream().into_iter(); loop { if let Some(ident) = next_token(&mut stream, "Epected substitution identifier.")? { if let TokenTree::Ident(ident) = ident { let sub = parse_group( &mut stream, ident.span(), "Hint: A substitution identifier should be followed by a group containing the \ code to be inserted instead of any occurrence of the identifier.", )?; // Check have found the same as existing if let Some(idents) = existing { if!idents.contains(&ident.to_string()) { return Err(( ident.span(), "Unfamiliar substitution identifier. '{}' is not present in previous \ substitution groups." .into(), )); } } substitutions.add_substitution(ident, Substitution::new_simple(sub.stream()))?; } else { return Err(( ident.span(), "Expected substitution identifier, got something else.".into(), )); } } else { // Check no substitution idents are missing. if let Some(idents) = existing { let sub_idents = substitutions.identifiers().cloned().collect(); let diff: Vec<_> = idents.difference(&sub_idents).collect(); if diff.len() > 0 { let mut msg: String = "Missing substitutions. Previous substitutions groups \ had the following identifiers not present in this \ group: " .into(); for ident in diff { msg.push_str("'"); msg.push_str(&ident.to_string()); msg.push_str("' "); } return Err((tree_span, msg)); } } break; } } Ok(substitutions) } /// Validates that the attribute part of a duplicate invocation uses /// the short syntax and returns the substitution that should be made. fn validate_short_attr( attr: TokenStream, ) -> Result<Vec<(String, Vec<String>, Vec<TokenStream>)>, (Span, String)> { if attr.is_empty() { return Err((Span::call_site(), "No substitutions found.".into())); } let mut iter = attr.into_iter(); let (idents, span) = validate_short_get_identifiers(&mut iter, Span::call_site())?; let mut result: Vec<_> = idents .into_iter() .map(|(ident, args)| (ident, args, Vec::new())) .collect(); validate_short_get_all_substitution_goups(iter, span, &mut result)?; Ok(result) } /// Assuming use of the short syntax, gets the initial list of substitution /// identifiers. fn validate_short_get_identifiers( iter: &mut IntoIter, mut span: Span, ) -> Result<(Vec<(String, Vec<String>)>, Span), (Span, String)> { let mut iter = iter.peekable(); let mut result = Vec::new(); loop { if let Some(next_token) = next_token(&mut iter, "Expected substitution identifier or ';'.")? { span = next_token.span(); match next_token { TokenTree::Ident(ident) => { result.push(( ident.to_string(), validate_short_get_identifier_arguments(&mut iter)?, // Vec::new() )) }, TokenTree::Punct(p) if is_semicolon(&p) => break, _ => return Err((span, "Expected substitution identifier or ';'.".into())), } } else { return Err((span, "Expected substitution identifier or ';'.".into())); } } Ok((result, span)) } /// Assuming use of the short syntax, gets the list of identifier arguments. fn validate_short_get_identifier_arguments( iter: &mut Peekable<impl Iterator<Item = TokenTree>>, ) -> Result<Vec<String>, (Span, String)> { let mut result = Vec::new(); if let Some(token) = iter.peek() { if let TokenTree::Group(group) = token { if check_delimiter(group).is_ok() { let mut arg_iter = group.stream().into_iter(); while let Some(token) = arg_iter.next() { if let TokenTree::Ident(ident) = token { result.push(ident.to_string()); if let Some(token) = arg_iter.next() { match token { TokenTree::Punct(punct) if punct_is_char(&punct, ',') => (), _ => return Err((token.span(), "Expected ','.".into())), } } } else { return Err(( token.span(), "Expected substitution identifier argument as identifier.".into(), )); } } // Make sure to consume the group let _ = iter.next(); } } } Ok(result) } /// Gets all substitution groups in the short syntax and inserts /// them into the given vec. fn validate_short_get_all_substitution_goups<'a>( iter: impl Iterator<Item = TokenTree>, mut span: Span, result: &mut Vec<(String, Vec<String>, Vec<TokenStream>)>, ) -> Result<(), (Span, String)> { let mut iter = iter.peekable(); loop { if let Some(TokenTree::Punct(p)) = iter.peek() { if is_nested_invocation(&p) { let p_span = p.span(); // consume '#' iter.next(); let nested_duplicated = invoke_nested(&mut iter, p_span)?; validate_short_get_all_substitution_goups( &mut nested_duplicated.into_iter(), span.clone(), result, )?; } } else { validate_short_get_substitutions( &mut iter, span, result.iter_mut().map(|(_, _, vec)| { vec.push(TokenStream::new()); vec.last_mut().unwrap() }), )?; if let Some(token) = iter.next() { span = token.span(); if let TokenTree::Punct(p) = token { if is_semicolon(&p) { continue; } } return Err((span, "Expected ';'.".into())); } else { break; } } } Ok(()) } /// Extracts a substitution group in the short syntax and inserts it into /// the elements returned by the given groups iterator. fn validate_short_get_substitutions<'a>( iter: &mut impl Iterator<Item = TokenTree>, mut span: Span, mut groups: impl Iterator<Item = &'a mut TokenStream>, ) -> Result<Span, (Span, String)> { if let Some(token) = iter.next() { let group = check_group(token, "")?; span = group.span(); *groups.next().unwrap() = group.stream(); for stream in groups { let group = parse_group(iter, span, "")?; span = group.span(); *stream = group.stream(); } } Ok(span) } /// Invokes a nested invocation of duplicate, assuming the /// next group is the attribute part of the invocation and the /// group after that is the element. fn invoke_nested( iter: &mut impl Iterator<Item = TokenTree>, span: Span, ) -> Result<TokenStream, (Span, String)> { let hints = "Hint: '#' is a nested invocation of the macro and must therefore be followed by \ a group containing the invocation.\nExample:\n#[\n\tidentifier [ substitute1 ] [ \ substitute2 ]\n][\n\tCode to be substituted whenever 'identifier' occurs \n]"; let nested_attr = parse_group(iter, span, hints)?; let nested_subs = parse_attr(nested_attr.stream(), nested_attr.span())?; let nested_item = parse_group(iter, nested_attr.span(), hints)?; Ok(substitute(nested_item.stream(), nested_subs)) }
extract_verbose_substitutions
identifier_name
parse.rs
use crate::{ parse_utils::*, substitute::{substitute, Substitution}, SubstitutionGroup, }; use proc_macro::{token_stream::IntoIter, Ident, Span, TokenStream, TokenTree}; use std::{collections::HashSet, iter::Peekable}; /// Parses the attribute part of an invocation of duplicate, returning /// all the substitutions that should be made to the item. pub(crate) fn parse_attr( attr: TokenStream, stream_span: Span, ) -> Result<Vec<SubstitutionGroup>, (Span, String)> { if identify_syntax(attr.clone(), stream_span)? { validate_verbose_attr(attr) } else { let substitutions = validate_short_attr(attr)?; let mut reorder = Vec::new(); for _ in 0..substitutions[0].2.len() { reorder.push(SubstitutionGroup::new()); } for (ident, args, subs) in substitutions { for (idx, sub) in subs.into_iter().enumerate() { let substitution = Substitution::new(&args, sub.into_iter()); if let Ok(substitution) = substitution { reorder[idx].add_substitution( Ident::new(&ident.clone(), Span::call_site()), substitution, )?; } else { return Err((Span::call_site(), "Failed creating substitution".into())); } } } Ok(reorder) } } /// True is verbose, false is short fn identify_syntax(attr: TokenStream, stream_span: Span) -> Result<bool, (Span, String)> { if let Some(token) = next_token(&mut attr.into_iter(), "Could not identify syntax type.")? { match token { TokenTree::Group(_) => Ok(true), TokenTree::Ident(_) => Ok(false), TokenTree::Punct(p) if is_nested_invocation(&p) => Ok(true), _ => { Err(( token.span(), "Expected substitution identifier or group. Received neither.".into(), )) }, } } else { Err((stream_span, "No substitutions found.".into())) } } /// Validates that the attribute part of a duplicate invocation uses /// the verbose syntax, and returns all the substitutions that should be made. fn validate_verbose_attr(attr: TokenStream) -> Result<Vec<SubstitutionGroup>, (Span, String)> { if attr.is_empty() { return Err((Span::call_site(), "No substitutions found.".into())); } let mut sub_groups = Vec::new(); let mut iter = attr.into_iter(); let mut substitution_ids = None; loop { if let Some(tree) = next_token(&mut iter, "Expected substitution group.")? { match tree { TokenTree::Punct(p) if is_nested_invocation(&p) => { let nested_duplicated = invoke_nested(&mut iter, p.span())?; let subs = validate_verbose_attr(nested_duplicated)?; sub_groups.extend(subs.into_iter()); }, _ => { sub_groups.push(extract_verbose_substitutions(tree, &substitution_ids)?); if None == substitution_ids { substitution_ids = Some(sub_groups[0].identifiers().cloned().collect()) } }, } } else { break; } } Ok(sub_groups) } /// Extracts a substitution group in the verbose syntax. fn extract_verbose_substitutions( tree: TokenTree, existing: &Option<HashSet<String>>, ) -> Result<SubstitutionGroup, (Span, String)>
if let Some(ident) = next_token(&mut stream, "Epected substitution identifier.")? { if let TokenTree::Ident(ident) = ident { let sub = parse_group( &mut stream, ident.span(), "Hint: A substitution identifier should be followed by a group containing the \ code to be inserted instead of any occurrence of the identifier.", )?; // Check have found the same as existing if let Some(idents) = existing { if!idents.contains(&ident.to_string()) { return Err(( ident.span(), "Unfamiliar substitution identifier. '{}' is not present in previous \ substitution groups." .into(), )); } } substitutions.add_substitution(ident, Substitution::new_simple(sub.stream()))?; } else { return Err(( ident.span(), "Expected substitution identifier, got something else.".into(), )); } } else { // Check no substitution idents are missing. if let Some(idents) = existing { let sub_idents = substitutions.identifiers().cloned().collect(); let diff: Vec<_> = idents.difference(&sub_idents).collect(); if diff.len() > 0 { let mut msg: String = "Missing substitutions. Previous substitutions groups \ had the following identifiers not present in this \ group: " .into(); for ident in diff { msg.push_str("'"); msg.push_str(&ident.to_string()); msg.push_str("' "); } return Err((tree_span, msg)); } } break; } } Ok(substitutions) } /// Validates that the attribute part of a duplicate invocation uses /// the short syntax and returns the substitution that should be made. fn validate_short_attr( attr: TokenStream, ) -> Result<Vec<(String, Vec<String>, Vec<TokenStream>)>, (Span, String)> { if attr.is_empty() { return Err((Span::call_site(), "No substitutions found.".into())); } let mut iter = attr.into_iter(); let (idents, span) = validate_short_get_identifiers(&mut iter, Span::call_site())?; let mut result: Vec<_> = idents .into_iter() .map(|(ident, args)| (ident, args, Vec::new())) .collect(); validate_short_get_all_substitution_goups(iter, span, &mut result)?; Ok(result) } /// Assuming use of the short syntax, gets the initial list of substitution /// identifiers. fn validate_short_get_identifiers( iter: &mut IntoIter, mut span: Span, ) -> Result<(Vec<(String, Vec<String>)>, Span), (Span, String)> { let mut iter = iter.peekable(); let mut result = Vec::new(); loop { if let Some(next_token) = next_token(&mut iter, "Expected substitution identifier or ';'.")? { span = next_token.span(); match next_token { TokenTree::Ident(ident) => { result.push(( ident.to_string(), validate_short_get_identifier_arguments(&mut iter)?, // Vec::new() )) }, TokenTree::Punct(p) if is_semicolon(&p) => break, _ => return Err((span, "Expected substitution identifier or ';'.".into())), } } else { return Err((span, "Expected substitution identifier or ';'.".into())); } } Ok((result, span)) } /// Assuming use of the short syntax, gets the list of identifier arguments. fn validate_short_get_identifier_arguments( iter: &mut Peekable<impl Iterator<Item = TokenTree>>, ) -> Result<Vec<String>, (Span, String)> { let mut result = Vec::new(); if let Some(token) = iter.peek() { if let TokenTree::Group(group) = token { if check_delimiter(group).is_ok() { let mut arg_iter = group.stream().into_iter(); while let Some(token) = arg_iter.next() { if let TokenTree::Ident(ident) = token { result.push(ident.to_string()); if let Some(token) = arg_iter.next() { match token { TokenTree::Punct(punct) if punct_is_char(&punct, ',') => (), _ => return Err((token.span(), "Expected ','.".into())), } } } else { return Err(( token.span(), "Expected substitution identifier argument as identifier.".into(), )); } } // Make sure to consume the group let _ = iter.next(); } } } Ok(result) } /// Gets all substitution groups in the short syntax and inserts /// them into the given vec. fn validate_short_get_all_substitution_goups<'a>( iter: impl Iterator<Item = TokenTree>, mut span: Span, result: &mut Vec<(String, Vec<String>, Vec<TokenStream>)>, ) -> Result<(), (Span, String)> { let mut iter = iter.peekable(); loop { if let Some(TokenTree::Punct(p)) = iter.peek() { if is_nested_invocation(&p) { let p_span = p.span(); // consume '#' iter.next(); let nested_duplicated = invoke_nested(&mut iter, p_span)?; validate_short_get_all_substitution_goups( &mut nested_duplicated.into_iter(), span.clone(), result, )?; } } else { validate_short_get_substitutions( &mut iter, span, result.iter_mut().map(|(_, _, vec)| { vec.push(TokenStream::new()); vec.last_mut().unwrap() }), )?; if let Some(token) = iter.next() { span = token.span(); if let TokenTree::Punct(p) = token { if is_semicolon(&p) { continue; } } return Err((span, "Expected ';'.".into())); } else { break; } } } Ok(()) } /// Extracts a substitution group in the short syntax and inserts it into /// the elements returned by the given groups iterator. fn validate_short_get_substitutions<'a>( iter: &mut impl Iterator<Item = TokenTree>, mut span: Span, mut groups: impl Iterator<Item = &'a mut TokenStream>, ) -> Result<Span, (Span, String)> { if let Some(token) = iter.next() { let group = check_group(token, "")?; span = group.span(); *groups.next().unwrap() = group.stream(); for stream in groups { let group = parse_group(iter, span, "")?; span = group.span(); *stream = group.stream(); } } Ok(span) } /// Invokes a nested invocation of duplicate, assuming the /// next group is the attribute part of the invocation and the /// group after that is the element. fn invoke_nested( iter: &mut impl Iterator<Item = TokenTree>, span: Span, ) -> Result<TokenStream, (Span, String)> { let hints = "Hint: '#' is a nested invocation of the macro and must therefore be followed by \ a group containing the invocation.\nExample:\n#[\n\tidentifier [ substitute1 ] [ \ substitute2 ]\n][\n\tCode to be substituted whenever 'identifier' occurs \n]"; let nested_attr = parse_group(iter, span, hints)?; let nested_subs = parse_attr(nested_attr.stream(), nested_attr.span())?; let nested_item = parse_group(iter, nested_attr.span(), hints)?; Ok(substitute(nested_item.stream(), nested_subs)) }
{ // Must get span now, before it's corrupted. let tree_span = tree.span(); let group = check_group( tree, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \ ]\n]", )?; if group.stream().into_iter().count() == 0 { return Err((group.span(), "No substitution groups found.".into())); } let mut substitutions = SubstitutionGroup::new(); let mut stream = group.stream().into_iter(); loop {
identifier_body
parse.rs
use crate::{ parse_utils::*, substitute::{substitute, Substitution}, SubstitutionGroup, }; use proc_macro::{token_stream::IntoIter, Ident, Span, TokenStream, TokenTree}; use std::{collections::HashSet, iter::Peekable}; /// Parses the attribute part of an invocation of duplicate, returning /// all the substitutions that should be made to the item. pub(crate) fn parse_attr( attr: TokenStream, stream_span: Span, ) -> Result<Vec<SubstitutionGroup>, (Span, String)> { if identify_syntax(attr.clone(), stream_span)? { validate_verbose_attr(attr) } else { let substitutions = validate_short_attr(attr)?; let mut reorder = Vec::new(); for _ in 0..substitutions[0].2.len() { reorder.push(SubstitutionGroup::new()); } for (ident, args, subs) in substitutions { for (idx, sub) in subs.into_iter().enumerate() { let substitution = Substitution::new(&args, sub.into_iter()); if let Ok(substitution) = substitution { reorder[idx].add_substitution( Ident::new(&ident.clone(), Span::call_site()), substitution, )?; } else { return Err((Span::call_site(), "Failed creating substitution".into())); } } } Ok(reorder) } } /// True is verbose, false is short fn identify_syntax(attr: TokenStream, stream_span: Span) -> Result<bool, (Span, String)> { if let Some(token) = next_token(&mut attr.into_iter(), "Could not identify syntax type.")? { match token { TokenTree::Group(_) => Ok(true), TokenTree::Ident(_) => Ok(false), TokenTree::Punct(p) if is_nested_invocation(&p) => Ok(true), _ => { Err(( token.span(), "Expected substitution identifier or group. Received neither.".into(), )) }, } } else { Err((stream_span, "No substitutions found.".into())) } } /// Validates that the attribute part of a duplicate invocation uses /// the verbose syntax, and returns all the substitutions that should be made. fn validate_verbose_attr(attr: TokenStream) -> Result<Vec<SubstitutionGroup>, (Span, String)> { if attr.is_empty() { return Err((Span::call_site(), "No substitutions found.".into())); } let mut sub_groups = Vec::new(); let mut iter = attr.into_iter(); let mut substitution_ids = None; loop { if let Some(tree) = next_token(&mut iter, "Expected substitution group.")? { match tree { TokenTree::Punct(p) if is_nested_invocation(&p) => { let nested_duplicated = invoke_nested(&mut iter, p.span())?; let subs = validate_verbose_attr(nested_duplicated)?; sub_groups.extend(subs.into_iter()); }, _ => { sub_groups.push(extract_verbose_substitutions(tree, &substitution_ids)?); if None == substitution_ids { substitution_ids = Some(sub_groups[0].identifiers().cloned().collect()) } }, } } else { break; } } Ok(sub_groups) } /// Extracts a substitution group in the verbose syntax. fn extract_verbose_substitutions( tree: TokenTree, existing: &Option<HashSet<String>>,
let group = check_group( tree, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \ ]\n]", )?; if group.stream().into_iter().count() == 0 { return Err((group.span(), "No substitution groups found.".into())); } let mut substitutions = SubstitutionGroup::new(); let mut stream = group.stream().into_iter(); loop { if let Some(ident) = next_token(&mut stream, "Epected substitution identifier.")? { if let TokenTree::Ident(ident) = ident { let sub = parse_group( &mut stream, ident.span(), "Hint: A substitution identifier should be followed by a group containing the \ code to be inserted instead of any occurrence of the identifier.", )?; // Check have found the same as existing if let Some(idents) = existing { if!idents.contains(&ident.to_string()) { return Err(( ident.span(), "Unfamiliar substitution identifier. '{}' is not present in previous \ substitution groups." .into(), )); } } substitutions.add_substitution(ident, Substitution::new_simple(sub.stream()))?; } else { return Err(( ident.span(), "Expected substitution identifier, got something else.".into(), )); } } else { // Check no substitution idents are missing. if let Some(idents) = existing { let sub_idents = substitutions.identifiers().cloned().collect(); let diff: Vec<_> = idents.difference(&sub_idents).collect(); if diff.len() > 0 { let mut msg: String = "Missing substitutions. Previous substitutions groups \ had the following identifiers not present in this \ group: " .into(); for ident in diff { msg.push_str("'"); msg.push_str(&ident.to_string()); msg.push_str("' "); } return Err((tree_span, msg)); } } break; } } Ok(substitutions) } /// Validates that the attribute part of a duplicate invocation uses /// the short syntax and returns the substitution that should be made. fn validate_short_attr( attr: TokenStream, ) -> Result<Vec<(String, Vec<String>, Vec<TokenStream>)>, (Span, String)> { if attr.is_empty() { return Err((Span::call_site(), "No substitutions found.".into())); } let mut iter = attr.into_iter(); let (idents, span) = validate_short_get_identifiers(&mut iter, Span::call_site())?; let mut result: Vec<_> = idents .into_iter() .map(|(ident, args)| (ident, args, Vec::new())) .collect(); validate_short_get_all_substitution_goups(iter, span, &mut result)?; Ok(result) } /// Assuming use of the short syntax, gets the initial list of substitution /// identifiers. fn validate_short_get_identifiers( iter: &mut IntoIter, mut span: Span, ) -> Result<(Vec<(String, Vec<String>)>, Span), (Span, String)> { let mut iter = iter.peekable(); let mut result = Vec::new(); loop { if let Some(next_token) = next_token(&mut iter, "Expected substitution identifier or ';'.")? { span = next_token.span(); match next_token { TokenTree::Ident(ident) => { result.push(( ident.to_string(), validate_short_get_identifier_arguments(&mut iter)?, // Vec::new() )) }, TokenTree::Punct(p) if is_semicolon(&p) => break, _ => return Err((span, "Expected substitution identifier or ';'.".into())), } } else { return Err((span, "Expected substitution identifier or ';'.".into())); } } Ok((result, span)) } /// Assuming use of the short syntax, gets the list of identifier arguments. fn validate_short_get_identifier_arguments( iter: &mut Peekable<impl Iterator<Item = TokenTree>>, ) -> Result<Vec<String>, (Span, String)> { let mut result = Vec::new(); if let Some(token) = iter.peek() { if let TokenTree::Group(group) = token { if check_delimiter(group).is_ok() { let mut arg_iter = group.stream().into_iter(); while let Some(token) = arg_iter.next() { if let TokenTree::Ident(ident) = token { result.push(ident.to_string()); if let Some(token) = arg_iter.next() { match token { TokenTree::Punct(punct) if punct_is_char(&punct, ',') => (), _ => return Err((token.span(), "Expected ','.".into())), } } } else { return Err(( token.span(), "Expected substitution identifier argument as identifier.".into(), )); } } // Make sure to consume the group let _ = iter.next(); } } } Ok(result) } /// Gets all substitution groups in the short syntax and inserts /// them into the given vec. fn validate_short_get_all_substitution_goups<'a>( iter: impl Iterator<Item = TokenTree>, mut span: Span, result: &mut Vec<(String, Vec<String>, Vec<TokenStream>)>, ) -> Result<(), (Span, String)> { let mut iter = iter.peekable(); loop { if let Some(TokenTree::Punct(p)) = iter.peek() { if is_nested_invocation(&p) { let p_span = p.span(); // consume '#' iter.next(); let nested_duplicated = invoke_nested(&mut iter, p_span)?; validate_short_get_all_substitution_goups( &mut nested_duplicated.into_iter(), span.clone(), result, )?; } } else { validate_short_get_substitutions( &mut iter, span, result.iter_mut().map(|(_, _, vec)| { vec.push(TokenStream::new()); vec.last_mut().unwrap() }), )?; if let Some(token) = iter.next() { span = token.span(); if let TokenTree::Punct(p) = token { if is_semicolon(&p) { continue; } } return Err((span, "Expected ';'.".into())); } else { break; } } } Ok(()) } /// Extracts a substitution group in the short syntax and inserts it into /// the elements returned by the given groups iterator. fn validate_short_get_substitutions<'a>( iter: &mut impl Iterator<Item = TokenTree>, mut span: Span, mut groups: impl Iterator<Item = &'a mut TokenStream>, ) -> Result<Span, (Span, String)> { if let Some(token) = iter.next() { let group = check_group(token, "")?; span = group.span(); *groups.next().unwrap() = group.stream(); for stream in groups { let group = parse_group(iter, span, "")?; span = group.span(); *stream = group.stream(); } } Ok(span) } /// Invokes a nested invocation of duplicate, assuming the /// next group is the attribute part of the invocation and the /// group after that is the element. fn invoke_nested( iter: &mut impl Iterator<Item = TokenTree>, span: Span, ) -> Result<TokenStream, (Span, String)> { let hints = "Hint: '#' is a nested invocation of the macro and must therefore be followed by \ a group containing the invocation.\nExample:\n#[\n\tidentifier [ substitute1 ] [ \ substitute2 ]\n][\n\tCode to be substituted whenever 'identifier' occurs \n]"; let nested_attr = parse_group(iter, span, hints)?; let nested_subs = parse_attr(nested_attr.stream(), nested_attr.span())?; let nested_item = parse_group(iter, nested_attr.span(), hints)?; Ok(substitute(nested_item.stream(), nested_subs)) }
) -> Result<SubstitutionGroup, (Span, String)> { // Must get span now, before it's corrupted. let tree_span = tree.span();
random_line_split
imp.rs
use std::mem; use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder}; use memchr::{memchr, memchr2, memchr3, memmem}; use regex_syntax::hir::literal::{Literal, Literals}; /// A prefix extracted from a compiled regular expression. /// /// A regex prefix is a set of literal strings that *must* be matched at the /// beginning of a regex in order for the entire regex to match. Similarly /// for a regex suffix. #[derive(Clone, Debug)] pub struct LiteralSearcher { complete: bool, lcp: Memmem, lcs: Memmem, matcher: Matcher, } #[derive(Clone, Debug)] enum Matcher { /// No literals. (Never advances through the input.) Empty, /// A set of four or more single byte literals. Bytes(SingleByteSet), /// A single substring, using vector accelerated routines when available. Memmem(Memmem), /// An Aho-Corasick automaton. AC { ac: AhoCorasick<u32>, lits: Vec<Literal> }, /// A packed multiple substring searcher, using SIMD. /// /// Note that Aho-Corasick will actually use this packed searcher /// internally automatically, however, there is some overhead associated /// with going through the Aho-Corasick machinery. So using the packed /// searcher directly results in some gains. Packed { s: packed::Searcher, lits: Vec<Literal> }, } impl LiteralSearcher { /// Returns a matcher that never matches and never advances the input. pub fn empty() -> Self { Self::new(Literals::empty(), Matcher::Empty) } /// Returns a matcher for literal prefixes from the given set. pub fn prefixes(lits: Literals) -> Self { let matcher = Matcher::prefixes(&lits); Self::new(lits, matcher) } /// Returns a matcher for literal suffixes from the given set. pub fn suffixes(lits: Literals) -> Self { let matcher = Matcher::suffixes(&lits); Self::new(lits, matcher) } fn new(lits: Literals, matcher: Matcher) -> Self { let complete = lits.all_complete(); LiteralSearcher { complete, lcp: Memmem::new(lits.longest_common_prefix()), lcs: Memmem::new(lits.longest_common_suffix()), matcher, } } /// Returns true if all matches comprise the entire regular expression. /// /// This does not necessarily mean that a literal match implies a match /// of the regular expression. For example, the regular expression `^a` /// is comprised of a single complete literal `a`, but the regular /// expression demands that it only match at the beginning of a string. pub fn complete(&self) -> bool { self.complete &&!self.is_empty() } /// Find the position of a literal in `haystack` if it exists. #[cfg_attr(feature = "perf-inline", inline(always))] pub fn find(&self, haystack: &[u8]) -> Option<(usize, usize)> { use self::Matcher::*; match self.matcher { Empty => Some((0, 0)), Bytes(ref sset) => sset.find(haystack).map(|i| (i, i + 1)), Memmem(ref s) => s.find(haystack).map(|i| (i, i + s.len())), AC { ref ac,.. } => { ac.find(haystack).map(|m| (m.start(), m.end())) } Packed { ref s,.. } => { s.find(haystack).map(|m| (m.start(), m.end())) } } } /// Like find, except matches must start at index `0`. pub fn find_start(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[0..lit.len()] { return Some((0, lit.len())); } } None } /// Like find, except matches must end at index `haystack.len()`. pub fn find_end(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[haystack.len() - lit.len()..] { return Some((haystack.len() - lit.len(), haystack.len())); } } None } /// Returns an iterator over all literals to be matched. pub fn iter(&self) -> LiteralIter<'_> { match self.matcher { Matcher::Empty => LiteralIter::Empty, Matcher::Bytes(ref sset) => LiteralIter::Bytes(&sset.dense), Matcher::Memmem(ref s) => LiteralIter::Single(&s.finder.needle()), Matcher::AC { ref lits,.. } => LiteralIter::AC(lits), Matcher::Packed { ref lits,.. } => LiteralIter::Packed(lits), } } /// Returns a matcher for the longest common prefix of this matcher. pub fn lcp(&self) -> &Memmem { &self.lcp } /// Returns a matcher for the longest common suffix of this matcher. pub fn lcs(&self) -> &Memmem { &self.lcs } /// Returns true iff this prefix is empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the number of prefixes in this machine. pub fn len(&self) -> usize { use self::Matcher::*; match self.matcher { Empty => 0, Bytes(ref sset) => sset.dense.len(), Memmem(_) => 1, AC { ref ac,.. } => ac.pattern_count(), Packed { ref lits,.. } => lits.len(), } } /// Return the approximate heap usage of literals in bytes. pub fn approximate_size(&self) -> usize { use self::Matcher::*; match self.matcher { Empty => 0, Bytes(ref sset) => sset.approximate_size(), Memmem(ref single) => single.approximate_size(), AC { ref ac,.. } => ac.heap_bytes(), Packed { ref s,.. } => s.heap_bytes(), } } } impl Matcher { fn prefixes(lits: &Literals) -> Self { let sset = SingleByteSet::prefixes(lits); Matcher::new(lits, sset) } fn suffixes(lits: &Literals) -> Self { let sset = SingleByteSet::suffixes(lits); Matcher::new(lits, sset) } fn new(lits: &Literals, sset: SingleByteSet) -> Self
let pats = lits.literals().to_owned(); let is_aho_corasick_fast = sset.dense.len() <= 1 && sset.all_ascii; if lits.literals().len() <= 100 &&!is_aho_corasick_fast { let mut builder = packed::Config::new() .match_kind(packed::MatchKind::LeftmostFirst) .builder(); if let Some(s) = builder.extend(&pats).build() { return Matcher::Packed { s, lits: pats }; } } let ac = AhoCorasickBuilder::new() .match_kind(aho_corasick::MatchKind::LeftmostFirst) .dfa(true) .build_with_size::<u32, _, _>(&pats) .unwrap(); Matcher::AC { ac, lits: pats } } } #[derive(Debug)] pub enum LiteralIter<'a> { Empty, Bytes(&'a [u8]), Single(&'a [u8]), AC(&'a [Literal]), Packed(&'a [Literal]), } impl<'a> Iterator for LiteralIter<'a> { type Item = &'a [u8]; fn next(&mut self) -> Option<Self::Item> { match *self { LiteralIter::Empty => None, LiteralIter::Bytes(ref mut many) => { if many.is_empty() { None } else { let next = &many[0..1]; *many = &many[1..]; Some(next) } } LiteralIter::Single(ref mut one) => { if one.is_empty() { None } else { let next = &one[..]; *one = &[]; Some(next) } } LiteralIter::AC(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; *lits = &lits[1..]; Some(&**next) } } LiteralIter::Packed(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; *lits = &lits[1..]; Some(&**next) } } } } } #[derive(Clone, Debug)] struct SingleByteSet { sparse: Vec<bool>, dense: Vec<u8>, complete: bool, all_ascii: bool, } impl SingleByteSet { fn new() -> SingleByteSet { SingleByteSet { sparse: vec![false; 256], dense: vec![], complete: true, all_ascii: true, } } fn prefixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() == 1; if let Some(&b) = lit.get(0) { if!sset.sparse[b as usize] { if b > 0x7F { sset.all_ascii = false; } sset.dense.push(b); sset.sparse[b as usize] = true; } } } sset } fn suffixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() == 1; if let Some(&b) = lit.get(lit.len().checked_sub(1).unwrap()) { if!sset.sparse[b as usize] { if b > 0x7F { sset.all_ascii = false; } sset.dense.push(b); sset.sparse[b as usize] = true; } } } sset } /// Faster find that special cases certain sizes to use memchr. #[cfg_attr(feature = "perf-inline", inline(always))] fn find(&self, text: &[u8]) -> Option<usize> { match self.dense.len() { 0 => None, 1 => memchr(self.dense[0], text), 2 => memchr2(self.dense[0], self.dense[1], text), 3 => memchr3(self.dense[0], self.dense[1], self.dense[2], text), _ => self._find(text), } } /// Generic find that works on any sized set. fn _find(&self, haystack: &[u8]) -> Option<usize> { for (i, &b) in haystack.iter().enumerate() { if self.sparse[b as usize] { return Some(i); } } None } fn approximate_size(&self) -> usize { (self.dense.len() * mem::size_of::<u8>()) + (self.sparse.len() * mem::size_of::<bool>()) } } /// A simple wrapper around the memchr crate's memmem implementation. /// /// The API this exposes mirrors the API of previous substring searchers that /// this supplanted. #[derive(Clone, Debug)] pub struct Memmem { finder: memmem::Finder<'static>, char_len: usize, } impl Memmem { fn new(pat: &[u8]) -> Memmem { Memmem { finder: memmem::Finder::new(pat).into_owned(), char_len: char_len_lossy(pat), } } #[cfg_attr(feature = "perf-inline", inline(always))] pub fn find(&self, haystack: &[u8]) -> Option<usize> { self.finder.find(haystack) } #[cfg_attr(feature = "perf-inline", inline(always))] pub fn is_suffix(&self, text: &[u8]) -> bool { if text.len() < self.len() { return false; } &text[text.len() - self.len()..] == self.finder.needle() } pub fn len(&self) -> usize { self.finder.needle().len() } pub fn char_len(&self) -> usize { self.char_len } fn approximate_size(&self) -> usize { self.finder.needle().len() * mem::size_of::<u8>() } } fn char_len_lossy(bytes: &[u8]) -> usize { String::from_utf8_lossy(bytes).chars().count() }
{ if lits.literals().is_empty() { return Matcher::Empty; } if sset.dense.len() >= 26 { // Avoid trying to match a large number of single bytes. // This is *very* sensitive to a frequency analysis comparison // between the bytes in sset and the composition of the haystack. // No matter the size of sset, if its members all are rare in the // haystack, then it'd be worth using it. How to tune this... IDK. // ---AG return Matcher::Empty; } if sset.complete { return Matcher::Bytes(sset); } if lits.literals().len() == 1 { return Matcher::Memmem(Memmem::new(&lits.literals()[0])); }
identifier_body
imp.rs
use std::mem; use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder}; use memchr::{memchr, memchr2, memchr3, memmem}; use regex_syntax::hir::literal::{Literal, Literals}; /// A prefix extracted from a compiled regular expression. /// /// A regex prefix is a set of literal strings that *must* be matched at the /// beginning of a regex in order for the entire regex to match. Similarly /// for a regex suffix. #[derive(Clone, Debug)] pub struct LiteralSearcher { complete: bool, lcp: Memmem, lcs: Memmem, matcher: Matcher, } #[derive(Clone, Debug)] enum Matcher { /// No literals. (Never advances through the input.) Empty, /// A set of four or more single byte literals. Bytes(SingleByteSet), /// A single substring, using vector accelerated routines when available. Memmem(Memmem), /// An Aho-Corasick automaton. AC { ac: AhoCorasick<u32>, lits: Vec<Literal> }, /// A packed multiple substring searcher, using SIMD. /// /// Note that Aho-Corasick will actually use this packed searcher /// internally automatically, however, there is some overhead associated /// with going through the Aho-Corasick machinery. So using the packed /// searcher directly results in some gains. Packed { s: packed::Searcher, lits: Vec<Literal> }, } impl LiteralSearcher { /// Returns a matcher that never matches and never advances the input. pub fn empty() -> Self { Self::new(Literals::empty(), Matcher::Empty) } /// Returns a matcher for literal prefixes from the given set. pub fn prefixes(lits: Literals) -> Self { let matcher = Matcher::prefixes(&lits); Self::new(lits, matcher) } /// Returns a matcher for literal suffixes from the given set. pub fn suffixes(lits: Literals) -> Self { let matcher = Matcher::suffixes(&lits); Self::new(lits, matcher) } fn new(lits: Literals, matcher: Matcher) -> Self { let complete = lits.all_complete(); LiteralSearcher { complete, lcp: Memmem::new(lits.longest_common_prefix()), lcs: Memmem::new(lits.longest_common_suffix()), matcher, } } /// Returns true if all matches comprise the entire regular expression. /// /// This does not necessarily mean that a literal match implies a match /// of the regular expression. For example, the regular expression `^a` /// is comprised of a single complete literal `a`, but the regular /// expression demands that it only match at the beginning of a string. pub fn complete(&self) -> bool { self.complete &&!self.is_empty() } /// Find the position of a literal in `haystack` if it exists. #[cfg_attr(feature = "perf-inline", inline(always))] pub fn find(&self, haystack: &[u8]) -> Option<(usize, usize)> { use self::Matcher::*; match self.matcher { Empty => Some((0, 0)), Bytes(ref sset) => sset.find(haystack).map(|i| (i, i + 1)), Memmem(ref s) => s.find(haystack).map(|i| (i, i + s.len())), AC { ref ac,.. } => { ac.find(haystack).map(|m| (m.start(), m.end())) } Packed { ref s,.. } => { s.find(haystack).map(|m| (m.start(), m.end())) } } } /// Like find, except matches must start at index `0`. pub fn
(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[0..lit.len()] { return Some((0, lit.len())); } } None } /// Like find, except matches must end at index `haystack.len()`. pub fn find_end(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[haystack.len() - lit.len()..] { return Some((haystack.len() - lit.len(), haystack.len())); } } None } /// Returns an iterator over all literals to be matched. pub fn iter(&self) -> LiteralIter<'_> { match self.matcher { Matcher::Empty => LiteralIter::Empty, Matcher::Bytes(ref sset) => LiteralIter::Bytes(&sset.dense), Matcher::Memmem(ref s) => LiteralIter::Single(&s.finder.needle()), Matcher::AC { ref lits,.. } => LiteralIter::AC(lits), Matcher::Packed { ref lits,.. } => LiteralIter::Packed(lits), } } /// Returns a matcher for the longest common prefix of this matcher. pub fn lcp(&self) -> &Memmem { &self.lcp } /// Returns a matcher for the longest common suffix of this matcher. pub fn lcs(&self) -> &Memmem { &self.lcs } /// Returns true iff this prefix is empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the number of prefixes in this machine. pub fn len(&self) -> usize { use self::Matcher::*; match self.matcher { Empty => 0, Bytes(ref sset) => sset.dense.len(), Memmem(_) => 1, AC { ref ac,.. } => ac.pattern_count(), Packed { ref lits,.. } => lits.len(), } } /// Return the approximate heap usage of literals in bytes. pub fn approximate_size(&self) -> usize { use self::Matcher::*; match self.matcher { Empty => 0, Bytes(ref sset) => sset.approximate_size(), Memmem(ref single) => single.approximate_size(), AC { ref ac,.. } => ac.heap_bytes(), Packed { ref s,.. } => s.heap_bytes(), } } } impl Matcher { fn prefixes(lits: &Literals) -> Self { let sset = SingleByteSet::prefixes(lits); Matcher::new(lits, sset) } fn suffixes(lits: &Literals) -> Self { let sset = SingleByteSet::suffixes(lits); Matcher::new(lits, sset) } fn new(lits: &Literals, sset: SingleByteSet) -> Self { if lits.literals().is_empty() { return Matcher::Empty; } if sset.dense.len() >= 26 { // Avoid trying to match a large number of single bytes. // This is *very* sensitive to a frequency analysis comparison // between the bytes in sset and the composition of the haystack. // No matter the size of sset, if its members all are rare in the // haystack, then it'd be worth using it. How to tune this... IDK. // ---AG return Matcher::Empty; } if sset.complete { return Matcher::Bytes(sset); } if lits.literals().len() == 1 { return Matcher::Memmem(Memmem::new(&lits.literals()[0])); } let pats = lits.literals().to_owned(); let is_aho_corasick_fast = sset.dense.len() <= 1 && sset.all_ascii; if lits.literals().len() <= 100 &&!is_aho_corasick_fast { let mut builder = packed::Config::new() .match_kind(packed::MatchKind::LeftmostFirst) .builder(); if let Some(s) = builder.extend(&pats).build() { return Matcher::Packed { s, lits: pats }; } } let ac = AhoCorasickBuilder::new() .match_kind(aho_corasick::MatchKind::LeftmostFirst) .dfa(true) .build_with_size::<u32, _, _>(&pats) .unwrap(); Matcher::AC { ac, lits: pats } } } #[derive(Debug)] pub enum LiteralIter<'a> { Empty, Bytes(&'a [u8]), Single(&'a [u8]), AC(&'a [Literal]), Packed(&'a [Literal]), } impl<'a> Iterator for LiteralIter<'a> { type Item = &'a [u8]; fn next(&mut self) -> Option<Self::Item> { match *self { LiteralIter::Empty => None, LiteralIter::Bytes(ref mut many) => { if many.is_empty() { None } else { let next = &many[0..1]; *many = &many[1..]; Some(next) } } LiteralIter::Single(ref mut one) => { if one.is_empty() { None } else { let next = &one[..]; *one = &[]; Some(next) } } LiteralIter::AC(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; *lits = &lits[1..]; Some(&**next) } } LiteralIter::Packed(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; *lits = &lits[1..]; Some(&**next) } } } } } #[derive(Clone, Debug)] struct SingleByteSet { sparse: Vec<bool>, dense: Vec<u8>, complete: bool, all_ascii: bool, } impl SingleByteSet { fn new() -> SingleByteSet { SingleByteSet { sparse: vec![false; 256], dense: vec![], complete: true, all_ascii: true, } } fn prefixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() == 1; if let Some(&b) = lit.get(0) { if!sset.sparse[b as usize] { if b > 0x7F { sset.all_ascii = false; } sset.dense.push(b); sset.sparse[b as usize] = true; } } } sset } fn suffixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() == 1; if let Some(&b) = lit.get(lit.len().checked_sub(1).unwrap()) { if!sset.sparse[b as usize] { if b > 0x7F { sset.all_ascii = false; } sset.dense.push(b); sset.sparse[b as usize] = true; } } } sset } /// Faster find that special cases certain sizes to use memchr. #[cfg_attr(feature = "perf-inline", inline(always))] fn find(&self, text: &[u8]) -> Option<usize> { match self.dense.len() { 0 => None, 1 => memchr(self.dense[0], text), 2 => memchr2(self.dense[0], self.dense[1], text), 3 => memchr3(self.dense[0], self.dense[1], self.dense[2], text), _ => self._find(text), } } /// Generic find that works on any sized set. fn _find(&self, haystack: &[u8]) -> Option<usize> { for (i, &b) in haystack.iter().enumerate() { if self.sparse[b as usize] { return Some(i); } } None } fn approximate_size(&self) -> usize { (self.dense.len() * mem::size_of::<u8>()) + (self.sparse.len() * mem::size_of::<bool>()) } } /// A simple wrapper around the memchr crate's memmem implementation. /// /// The API this exposes mirrors the API of previous substring searchers that /// this supplanted. #[derive(Clone, Debug)] pub struct Memmem { finder: memmem::Finder<'static>, char_len: usize, } impl Memmem { fn new(pat: &[u8]) -> Memmem { Memmem { finder: memmem::Finder::new(pat).into_owned(), char_len: char_len_lossy(pat), } } #[cfg_attr(feature = "perf-inline", inline(always))] pub fn find(&self, haystack: &[u8]) -> Option<usize> { self.finder.find(haystack) } #[cfg_attr(feature = "perf-inline", inline(always))] pub fn is_suffix(&self, text: &[u8]) -> bool { if text.len() < self.len() { return false; } &text[text.len() - self.len()..] == self.finder.needle() } pub fn len(&self) -> usize { self.finder.needle().len() } pub fn char_len(&self) -> usize { self.char_len } fn approximate_size(&self) -> usize { self.finder.needle().len() * mem::size_of::<u8>() } } fn char_len_lossy(bytes: &[u8]) -> usize { String::from_utf8_lossy(bytes).chars().count() }
find_start
identifier_name
imp.rs
use std::mem; use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder}; use memchr::{memchr, memchr2, memchr3, memmem}; use regex_syntax::hir::literal::{Literal, Literals}; /// A prefix extracted from a compiled regular expression. /// /// A regex prefix is a set of literal strings that *must* be matched at the /// beginning of a regex in order for the entire regex to match. Similarly /// for a regex suffix. #[derive(Clone, Debug)] pub struct LiteralSearcher { complete: bool, lcp: Memmem, lcs: Memmem, matcher: Matcher, } #[derive(Clone, Debug)] enum Matcher { /// No literals. (Never advances through the input.) Empty, /// A set of four or more single byte literals. Bytes(SingleByteSet), /// A single substring, using vector accelerated routines when available. Memmem(Memmem), /// An Aho-Corasick automaton. AC { ac: AhoCorasick<u32>, lits: Vec<Literal> }, /// A packed multiple substring searcher, using SIMD. /// /// Note that Aho-Corasick will actually use this packed searcher /// internally automatically, however, there is some overhead associated /// with going through the Aho-Corasick machinery. So using the packed /// searcher directly results in some gains. Packed { s: packed::Searcher, lits: Vec<Literal> }, } impl LiteralSearcher { /// Returns a matcher that never matches and never advances the input. pub fn empty() -> Self { Self::new(Literals::empty(), Matcher::Empty) } /// Returns a matcher for literal prefixes from the given set. pub fn prefixes(lits: Literals) -> Self { let matcher = Matcher::prefixes(&lits); Self::new(lits, matcher) } /// Returns a matcher for literal suffixes from the given set. pub fn suffixes(lits: Literals) -> Self { let matcher = Matcher::suffixes(&lits); Self::new(lits, matcher) } fn new(lits: Literals, matcher: Matcher) -> Self { let complete = lits.all_complete(); LiteralSearcher { complete, lcp: Memmem::new(lits.longest_common_prefix()), lcs: Memmem::new(lits.longest_common_suffix()), matcher, } } /// Returns true if all matches comprise the entire regular expression. /// /// This does not necessarily mean that a literal match implies a match /// of the regular expression. For example, the regular expression `^a` /// is comprised of a single complete literal `a`, but the regular /// expression demands that it only match at the beginning of a string. pub fn complete(&self) -> bool { self.complete &&!self.is_empty() } /// Find the position of a literal in `haystack` if it exists. #[cfg_attr(feature = "perf-inline", inline(always))] pub fn find(&self, haystack: &[u8]) -> Option<(usize, usize)> { use self::Matcher::*; match self.matcher { Empty => Some((0, 0)), Bytes(ref sset) => sset.find(haystack).map(|i| (i, i + 1)), Memmem(ref s) => s.find(haystack).map(|i| (i, i + s.len())), AC { ref ac,.. } => { ac.find(haystack).map(|m| (m.start(), m.end())) } Packed { ref s,.. } => { s.find(haystack).map(|m| (m.start(), m.end())) } } } /// Like find, except matches must start at index `0`. pub fn find_start(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[0..lit.len()] { return Some((0, lit.len())); } } None } /// Like find, except matches must end at index `haystack.len()`. pub fn find_end(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[haystack.len() - lit.len()..] { return Some((haystack.len() - lit.len(), haystack.len())); } } None } /// Returns an iterator over all literals to be matched. pub fn iter(&self) -> LiteralIter<'_> { match self.matcher { Matcher::Empty => LiteralIter::Empty, Matcher::Bytes(ref sset) => LiteralIter::Bytes(&sset.dense), Matcher::Memmem(ref s) => LiteralIter::Single(&s.finder.needle()), Matcher::AC { ref lits,.. } => LiteralIter::AC(lits), Matcher::Packed { ref lits,.. } => LiteralIter::Packed(lits), } } /// Returns a matcher for the longest common prefix of this matcher. pub fn lcp(&self) -> &Memmem { &self.lcp } /// Returns a matcher for the longest common suffix of this matcher. pub fn lcs(&self) -> &Memmem { &self.lcs } /// Returns true iff this prefix is empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the number of prefixes in this machine. pub fn len(&self) -> usize { use self::Matcher::*; match self.matcher { Empty => 0, Bytes(ref sset) => sset.dense.len(), Memmem(_) => 1, AC { ref ac,.. } => ac.pattern_count(), Packed { ref lits,.. } => lits.len(), } } /// Return the approximate heap usage of literals in bytes. pub fn approximate_size(&self) -> usize { use self::Matcher::*; match self.matcher { Empty => 0, Bytes(ref sset) => sset.approximate_size(), Memmem(ref single) => single.approximate_size(), AC { ref ac,.. } => ac.heap_bytes(), Packed { ref s,.. } => s.heap_bytes(), } } } impl Matcher { fn prefixes(lits: &Literals) -> Self { let sset = SingleByteSet::prefixes(lits); Matcher::new(lits, sset) } fn suffixes(lits: &Literals) -> Self { let sset = SingleByteSet::suffixes(lits); Matcher::new(lits, sset) } fn new(lits: &Literals, sset: SingleByteSet) -> Self { if lits.literals().is_empty() { return Matcher::Empty; } if sset.dense.len() >= 26 { // Avoid trying to match a large number of single bytes. // This is *very* sensitive to a frequency analysis comparison // between the bytes in sset and the composition of the haystack. // No matter the size of sset, if its members all are rare in the // haystack, then it'd be worth using it. How to tune this... IDK. // ---AG return Matcher::Empty; } if sset.complete { return Matcher::Bytes(sset); } if lits.literals().len() == 1 { return Matcher::Memmem(Memmem::new(&lits.literals()[0])); } let pats = lits.literals().to_owned(); let is_aho_corasick_fast = sset.dense.len() <= 1 && sset.all_ascii; if lits.literals().len() <= 100 &&!is_aho_corasick_fast { let mut builder = packed::Config::new() .match_kind(packed::MatchKind::LeftmostFirst) .builder(); if let Some(s) = builder.extend(&pats).build() { return Matcher::Packed { s, lits: pats }; } } let ac = AhoCorasickBuilder::new() .match_kind(aho_corasick::MatchKind::LeftmostFirst) .dfa(true) .build_with_size::<u32, _, _>(&pats) .unwrap(); Matcher::AC { ac, lits: pats } } } #[derive(Debug)] pub enum LiteralIter<'a> { Empty, Bytes(&'a [u8]), Single(&'a [u8]), AC(&'a [Literal]), Packed(&'a [Literal]), } impl<'a> Iterator for LiteralIter<'a> { type Item = &'a [u8]; fn next(&mut self) -> Option<Self::Item> { match *self { LiteralIter::Empty => None, LiteralIter::Bytes(ref mut many) => { if many.is_empty() { None } else { let next = &many[0..1]; *many = &many[1..]; Some(next) } } LiteralIter::Single(ref mut one) => { if one.is_empty() { None } else { let next = &one[..]; *one = &[]; Some(next) } } LiteralIter::AC(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; *lits = &lits[1..]; Some(&**next) } } LiteralIter::Packed(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; *lits = &lits[1..]; Some(&**next) } } } } } #[derive(Clone, Debug)] struct SingleByteSet { sparse: Vec<bool>, dense: Vec<u8>, complete: bool, all_ascii: bool, } impl SingleByteSet { fn new() -> SingleByteSet { SingleByteSet { sparse: vec![false; 256], dense: vec![],
} } fn prefixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() == 1; if let Some(&b) = lit.get(0) { if!sset.sparse[b as usize] { if b > 0x7F { sset.all_ascii = false; } sset.dense.push(b); sset.sparse[b as usize] = true; } } } sset } fn suffixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() == 1; if let Some(&b) = lit.get(lit.len().checked_sub(1).unwrap()) { if!sset.sparse[b as usize] { if b > 0x7F { sset.all_ascii = false; } sset.dense.push(b); sset.sparse[b as usize] = true; } } } sset } /// Faster find that special cases certain sizes to use memchr. #[cfg_attr(feature = "perf-inline", inline(always))] fn find(&self, text: &[u8]) -> Option<usize> { match self.dense.len() { 0 => None, 1 => memchr(self.dense[0], text), 2 => memchr2(self.dense[0], self.dense[1], text), 3 => memchr3(self.dense[0], self.dense[1], self.dense[2], text), _ => self._find(text), } } /// Generic find that works on any sized set. fn _find(&self, haystack: &[u8]) -> Option<usize> { for (i, &b) in haystack.iter().enumerate() { if self.sparse[b as usize] { return Some(i); } } None } fn approximate_size(&self) -> usize { (self.dense.len() * mem::size_of::<u8>()) + (self.sparse.len() * mem::size_of::<bool>()) } } /// A simple wrapper around the memchr crate's memmem implementation. /// /// The API this exposes mirrors the API of previous substring searchers that /// this supplanted. #[derive(Clone, Debug)] pub struct Memmem { finder: memmem::Finder<'static>, char_len: usize, } impl Memmem { fn new(pat: &[u8]) -> Memmem { Memmem { finder: memmem::Finder::new(pat).into_owned(), char_len: char_len_lossy(pat), } } #[cfg_attr(feature = "perf-inline", inline(always))] pub fn find(&self, haystack: &[u8]) -> Option<usize> { self.finder.find(haystack) } #[cfg_attr(feature = "perf-inline", inline(always))] pub fn is_suffix(&self, text: &[u8]) -> bool { if text.len() < self.len() { return false; } &text[text.len() - self.len()..] == self.finder.needle() } pub fn len(&self) -> usize { self.finder.needle().len() } pub fn char_len(&self) -> usize { self.char_len } fn approximate_size(&self) -> usize { self.finder.needle().len() * mem::size_of::<u8>() } } fn char_len_lossy(bytes: &[u8]) -> usize { String::from_utf8_lossy(bytes).chars().count() }
complete: true, all_ascii: true,
random_line_split
imp.rs
use std::mem; use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder}; use memchr::{memchr, memchr2, memchr3, memmem}; use regex_syntax::hir::literal::{Literal, Literals}; /// A prefix extracted from a compiled regular expression. /// /// A regex prefix is a set of literal strings that *must* be matched at the /// beginning of a regex in order for the entire regex to match. Similarly /// for a regex suffix. #[derive(Clone, Debug)] pub struct LiteralSearcher { complete: bool, lcp: Memmem, lcs: Memmem, matcher: Matcher, } #[derive(Clone, Debug)] enum Matcher { /// No literals. (Never advances through the input.) Empty, /// A set of four or more single byte literals. Bytes(SingleByteSet), /// A single substring, using vector accelerated routines when available. Memmem(Memmem), /// An Aho-Corasick automaton. AC { ac: AhoCorasick<u32>, lits: Vec<Literal> }, /// A packed multiple substring searcher, using SIMD. /// /// Note that Aho-Corasick will actually use this packed searcher /// internally automatically, however, there is some overhead associated /// with going through the Aho-Corasick machinery. So using the packed /// searcher directly results in some gains. Packed { s: packed::Searcher, lits: Vec<Literal> }, } impl LiteralSearcher { /// Returns a matcher that never matches and never advances the input. pub fn empty() -> Self { Self::new(Literals::empty(), Matcher::Empty) } /// Returns a matcher for literal prefixes from the given set. pub fn prefixes(lits: Literals) -> Self { let matcher = Matcher::prefixes(&lits); Self::new(lits, matcher) } /// Returns a matcher for literal suffixes from the given set. pub fn suffixes(lits: Literals) -> Self { let matcher = Matcher::suffixes(&lits); Self::new(lits, matcher) } fn new(lits: Literals, matcher: Matcher) -> Self { let complete = lits.all_complete(); LiteralSearcher { complete, lcp: Memmem::new(lits.longest_common_prefix()), lcs: Memmem::new(lits.longest_common_suffix()), matcher, } } /// Returns true if all matches comprise the entire regular expression. /// /// This does not necessarily mean that a literal match implies a match /// of the regular expression. For example, the regular expression `^a` /// is comprised of a single complete literal `a`, but the regular /// expression demands that it only match at the beginning of a string. pub fn complete(&self) -> bool { self.complete &&!self.is_empty() } /// Find the position of a literal in `haystack` if it exists. #[cfg_attr(feature = "perf-inline", inline(always))] pub fn find(&self, haystack: &[u8]) -> Option<(usize, usize)> { use self::Matcher::*; match self.matcher { Empty => Some((0, 0)), Bytes(ref sset) => sset.find(haystack).map(|i| (i, i + 1)), Memmem(ref s) => s.find(haystack).map(|i| (i, i + s.len())), AC { ref ac,.. } => { ac.find(haystack).map(|m| (m.start(), m.end())) } Packed { ref s,.. } => { s.find(haystack).map(|m| (m.start(), m.end())) } } } /// Like find, except matches must start at index `0`. pub fn find_start(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[0..lit.len()] { return Some((0, lit.len())); } } None } /// Like find, except matches must end at index `haystack.len()`. pub fn find_end(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[haystack.len() - lit.len()..] { return Some((haystack.len() - lit.len(), haystack.len())); } } None } /// Returns an iterator over all literals to be matched. pub fn iter(&self) -> LiteralIter<'_> { match self.matcher { Matcher::Empty => LiteralIter::Empty, Matcher::Bytes(ref sset) => LiteralIter::Bytes(&sset.dense), Matcher::Memmem(ref s) => LiteralIter::Single(&s.finder.needle()), Matcher::AC { ref lits,.. } => LiteralIter::AC(lits), Matcher::Packed { ref lits,.. } => LiteralIter::Packed(lits), } } /// Returns a matcher for the longest common prefix of this matcher. pub fn lcp(&self) -> &Memmem { &self.lcp } /// Returns a matcher for the longest common suffix of this matcher. pub fn lcs(&self) -> &Memmem { &self.lcs } /// Returns true iff this prefix is empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the number of prefixes in this machine. pub fn len(&self) -> usize { use self::Matcher::*; match self.matcher { Empty => 0, Bytes(ref sset) => sset.dense.len(), Memmem(_) => 1, AC { ref ac,.. } => ac.pattern_count(), Packed { ref lits,.. } => lits.len(), } } /// Return the approximate heap usage of literals in bytes. pub fn approximate_size(&self) -> usize { use self::Matcher::*; match self.matcher { Empty => 0, Bytes(ref sset) => sset.approximate_size(), Memmem(ref single) => single.approximate_size(), AC { ref ac,.. } => ac.heap_bytes(), Packed { ref s,.. } => s.heap_bytes(), } } } impl Matcher { fn prefixes(lits: &Literals) -> Self { let sset = SingleByteSet::prefixes(lits); Matcher::new(lits, sset) } fn suffixes(lits: &Literals) -> Self { let sset = SingleByteSet::suffixes(lits); Matcher::new(lits, sset) } fn new(lits: &Literals, sset: SingleByteSet) -> Self { if lits.literals().is_empty() { return Matcher::Empty; } if sset.dense.len() >= 26 { // Avoid trying to match a large number of single bytes. // This is *very* sensitive to a frequency analysis comparison // between the bytes in sset and the composition of the haystack. // No matter the size of sset, if its members all are rare in the // haystack, then it'd be worth using it. How to tune this... IDK. // ---AG return Matcher::Empty; } if sset.complete { return Matcher::Bytes(sset); } if lits.literals().len() == 1 { return Matcher::Memmem(Memmem::new(&lits.literals()[0])); } let pats = lits.literals().to_owned(); let is_aho_corasick_fast = sset.dense.len() <= 1 && sset.all_ascii; if lits.literals().len() <= 100 &&!is_aho_corasick_fast { let mut builder = packed::Config::new() .match_kind(packed::MatchKind::LeftmostFirst) .builder(); if let Some(s) = builder.extend(&pats).build() { return Matcher::Packed { s, lits: pats }; } } let ac = AhoCorasickBuilder::new() .match_kind(aho_corasick::MatchKind::LeftmostFirst) .dfa(true) .build_with_size::<u32, _, _>(&pats) .unwrap(); Matcher::AC { ac, lits: pats } } } #[derive(Debug)] pub enum LiteralIter<'a> { Empty, Bytes(&'a [u8]), Single(&'a [u8]), AC(&'a [Literal]), Packed(&'a [Literal]), } impl<'a> Iterator for LiteralIter<'a> { type Item = &'a [u8]; fn next(&mut self) -> Option<Self::Item> { match *self { LiteralIter::Empty => None, LiteralIter::Bytes(ref mut many) => { if many.is_empty() { None } else { let next = &many[0..1]; *many = &many[1..]; Some(next) } } LiteralIter::Single(ref mut one) => { if one.is_empty()
else { let next = &one[..]; *one = &[]; Some(next) } } LiteralIter::AC(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; *lits = &lits[1..]; Some(&**next) } } LiteralIter::Packed(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; *lits = &lits[1..]; Some(&**next) } } } } } #[derive(Clone, Debug)] struct SingleByteSet { sparse: Vec<bool>, dense: Vec<u8>, complete: bool, all_ascii: bool, } impl SingleByteSet { fn new() -> SingleByteSet { SingleByteSet { sparse: vec![false; 256], dense: vec![], complete: true, all_ascii: true, } } fn prefixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() == 1; if let Some(&b) = lit.get(0) { if!sset.sparse[b as usize] { if b > 0x7F { sset.all_ascii = false; } sset.dense.push(b); sset.sparse[b as usize] = true; } } } sset } fn suffixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() == 1; if let Some(&b) = lit.get(lit.len().checked_sub(1).unwrap()) { if!sset.sparse[b as usize] { if b > 0x7F { sset.all_ascii = false; } sset.dense.push(b); sset.sparse[b as usize] = true; } } } sset } /// Faster find that special cases certain sizes to use memchr. #[cfg_attr(feature = "perf-inline", inline(always))] fn find(&self, text: &[u8]) -> Option<usize> { match self.dense.len() { 0 => None, 1 => memchr(self.dense[0], text), 2 => memchr2(self.dense[0], self.dense[1], text), 3 => memchr3(self.dense[0], self.dense[1], self.dense[2], text), _ => self._find(text), } } /// Generic find that works on any sized set. fn _find(&self, haystack: &[u8]) -> Option<usize> { for (i, &b) in haystack.iter().enumerate() { if self.sparse[b as usize] { return Some(i); } } None } fn approximate_size(&self) -> usize { (self.dense.len() * mem::size_of::<u8>()) + (self.sparse.len() * mem::size_of::<bool>()) } } /// A simple wrapper around the memchr crate's memmem implementation. /// /// The API this exposes mirrors the API of previous substring searchers that /// this supplanted. #[derive(Clone, Debug)] pub struct Memmem { finder: memmem::Finder<'static>, char_len: usize, } impl Memmem { fn new(pat: &[u8]) -> Memmem { Memmem { finder: memmem::Finder::new(pat).into_owned(), char_len: char_len_lossy(pat), } } #[cfg_attr(feature = "perf-inline", inline(always))] pub fn find(&self, haystack: &[u8]) -> Option<usize> { self.finder.find(haystack) } #[cfg_attr(feature = "perf-inline", inline(always))] pub fn is_suffix(&self, text: &[u8]) -> bool { if text.len() < self.len() { return false; } &text[text.len() - self.len()..] == self.finder.needle() } pub fn len(&self) -> usize { self.finder.needle().len() } pub fn char_len(&self) -> usize { self.char_len } fn approximate_size(&self) -> usize { self.finder.needle().len() * mem::size_of::<u8>() } } fn char_len_lossy(bytes: &[u8]) -> usize { String::from_utf8_lossy(bytes).chars().count() }
{ None }
conditional_block
synchronizer.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::committee::*; use super::error::*; use super::messages::*; use super::types::*; use bincode::Error; use crypto::Digest; use futures::future::{Fuse, FutureExt}; use futures::select; use futures::stream::futures_unordered::FuturesUnordered; use futures::stream::StreamExt; use futures::{future::FusedFuture, pin_mut}; use log::*; use rand::seq::SliceRandom; use std::cmp::max; use std::cmp::min; use std::collections::HashSet; use store::Store; use tokio::sync::mpsc; use tokio::sync::mpsc::{Receiver, Sender}; use tokio::time::{sleep, Duration}; type DBValue = Vec<u8>; /// A service that keeps watching for the dependencies of blocks. pub async fn header_waiter_process( mut store: Store, // A copy of the inner store genesis: Vec<Certificate>, // The genesis set of certs mut rx: mpsc::UnboundedReceiver<(SignedBlockHeader, BlockHeader)>, // A channel to receive Headers loopback_commands: Sender<PrimaryMessage>, ) { // Register the genesis certs... for cert in &genesis { // let bytes: Vec<u8> = bincode::serialize(&cert)?; let digest_in_store = PartialCertificate::make_digest(&cert.digest, 0, cert.primary_id); let _ = store .write(digest_in_store.0.to_vec(), digest_in_store.0.to_vec()) //digest_in_store.0.to_vec() --> bytes? .await; } // Create an unordered set of futures let mut waiting_headers = FuturesUnordered::new(); // Now process headers and also headers with satisfied dependencies loop { select! { signer_header_result = waiting_headers.select_next_some() => { // Once we have all header dependencies, we try to re-inject this signed header if let Ok(signed_header) = signer_header_result { if let Err(e) = loopback_commands.send(PrimaryMessage::Header(signed_header)).await { error!("Error sending loopback command: {}", e); } } else { error!("Error in waiter."); } } msg = rx.recv().fuse() => { if let Some((signed_header, header)) = msg { let i2_store = store.clone(); let fut = header_waiter(i2_store, signed_header, header); waiting_headers.push(fut); } else { // Channel is closed, so we exit. // Our primary is gone! warn!("Exiting digest waiter process."); break; } } } } } /// The future that waits for a set of headers and digest associated with a header. pub async fn header_waiter( mut store: Store, // A copy of the store signed_header: SignedBlockHeader, // The signed header structure header: BlockHeader, // The header for which we wait for dependencies. ) -> Result<SignedBlockHeader, DagError> { debug!( "[DEP] ASK H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); //Note: we now store different digests for header and certificates to avoid false positive. for (other_primary_id, digest) in &header.parents { let digest_in_store = PartialCertificate::make_digest(&digest, header.round - 1, *other_primary_id); if store.notify_read(digest_in_store.0.to_vec()).await.is_err() { return Err(DagError::StorageFailure { error: "Error in reading store from 'header_waiter'.".to_string(), }); } } for (digest, _) in &header.transactions_digest { if store.notify_read(digest.0.to_vec()).await.is_err() { return Err(DagError::StorageFailure { error: "Error in reading store from 'header_waiter'.".to_string(), }); } } debug!( "[DEP] GOT H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); Ok(signed_header) } pub async fn dag_synchronizer_process( mut get_from_dag: Receiver<SyncMessage>, dag_synchronizer: DagSynchronizer, ) { let mut digests_to_sync: Vec<Digest> = Vec::new(); let mut round_to_sync: RoundNumber = 0; let mut last_synced_round: RoundNumber = 0; let mut rollback_stop_round: RoundNumber = 1; let mut sq: SyncNumber = 0; let rollback_fut = Fuse::terminated(); pin_mut!(rollback_fut); loop { select! { msg = get_from_dag.recv().fuse() => { if let Some(SyncMessage::SyncUpToRound(round, digests, last_gc_round)) = msg { if round > round_to_sync { debug!("DAG sync: received request to sync digests: {:?} up to round {}", digests, round); round_to_sync = round; digests_to_sync = digests; rollback_stop_round = max(last_gc_round+1, 1); if rollback_fut.is_terminated(){ last_synced_round = round_to_sync; rollback_fut.set(rollback_headers(dag_synchronizer.clone(), digests_to_sync.clone(), round_to_sync, rollback_stop_round, sq).fuse()); debug!("DAG sync: go."); } else { debug!("DAG sync: drop."); } } } else{
warn!("Exiting DagSynchronizer::start()."); break; } } res = rollback_fut => { if let Err(e) = res{ error!("rollback_headers returns error: {:?}", e); } else{ sq += 1; if round_to_sync > last_synced_round{ last_synced_round = round_to_sync; // rollback_stop_round = max(last_synced_round, 1); rollback_fut.set(rollback_headers(dag_synchronizer.clone(), digests_to_sync.clone(), round_to_sync, rollback_stop_round, sq).fuse()); } } } } } } pub async fn handle_header_digest( mut dag_synchronizer: DagSynchronizer, digest: Digest, rollback_stop_round: RoundNumber, sq: SyncNumber, ) -> Result<Option<Vec<Digest>>, DagError> { //TODO: issue: should we try the processor first? we need concurrent access to it... if let Ok(dbvalue) = dag_synchronizer.store.read(digest.to_vec()).await { match dbvalue { None => { debug!("invoking send_sync_header_requests: {:?}", digest); dag_synchronizer .send_sync_header_requests(digest.clone(), sq) .await?; // Exponential backoff delay let mut delay = 50; loop { select! { ret = dag_synchronizer.store.notify_read(digest.to_vec()).fuse() =>{ if let Ok(record_header) = ret { return Ok(dag_synchronizer.handle_record_header(record_header, rollback_stop_round).await?); } else { //handle the error. error!("Read returned an error: {:?}", ret); } } _ = sleep(Duration::from_millis(delay)).fuse() => { debug!("Trigger Sync on {:?}", digest); dag_synchronizer.send_sync_header_requests(digest.clone(), sq).await?; delay *= 4; } } } } // HERE Some(record_header) => { let result: Result<HeaderPrimaryRecord, Error> = bincode::deserialize(&record_header); if let Err(e) = result { panic!("Reading digest {:?} from store gives us a struct that we cannot deserialize: {}", digest, e); } return Ok(dag_synchronizer .handle_record_header(record_header, rollback_stop_round) .await?); } } } else { //handle the error. } Ok(None) } //sync all digests' causal history and pass to consensus pub async fn rollback_headers( mut dag_synchronizer: DagSynchronizer, digests: Vec<Digest>, round: RoundNumber, rollback_stop_round: RoundNumber, sq: SyncNumber, ) -> Result<(), DagError> { let mut asked_for: HashSet<Digest> = HashSet::new(); let mut digests_in_process = FuturesUnordered::new(); for digest in digests { let fut = handle_header_digest(dag_synchronizer.clone(), digest, rollback_stop_round, sq); digests_in_process.push(fut); } while!digests_in_process.is_empty() { // let option = digests_in_process.select_next_some().await?; let option = match digests_in_process.select_next_some().await { Ok(option) => option, Err(e) => panic!("Panix {}", e), }; if let Some(parents_digests) = option { for digest in parents_digests { // Only ask for each digest once per rollback. if asked_for.contains(&digest) { continue; } asked_for.insert(digest.clone()); if!dag_synchronizer.pending_digests.contains(&digest) { debug!("Seems so {}", digest); dag_synchronizer.pending_digests.insert(digest.clone()); let fut = handle_header_digest( dag_synchronizer.clone(), digest, rollback_stop_round, sq, ); digests_in_process.push(fut); } } } } let msg = ConsensusMessage::SyncDone(round); dag_synchronizer.send_to_consensus(msg).await?; info!("DAG sync: sent to consensus SyncDone for round {}", round); Ok(()) } #[derive(Clone)] pub struct DagSynchronizer { pub id: NodeID, pub send_to_consensus_channel: Sender<ConsensusMessage>, pub send_to_network: Sender<(RoundNumber, PrimaryMessage)>, pub store: Store, pub committee: Committee, pub pending_digests: HashSet<Digest>, } impl DagSynchronizer { pub fn new( id: NodeID, committee: Committee, store: Store, send_to_consensus_channel: Sender<ConsensusMessage>, send_to_network: Sender<(RoundNumber, PrimaryMessage)>, ) -> Self { DagSynchronizer { id, send_to_consensus_channel, send_to_network, store, committee, pending_digests: HashSet::new(), } } pub async fn send_sync_header_requests( &mut self, digest: Digest, sq: SyncNumber, ) -> Result<(), DagError> { //Pick random 3 validators. Hopefully one will have the header. We can implement different strategies. let authorities = self.committee.authorities.choose_multiple( &mut rand::thread_rng(), min(self.committee.quorum_threshold() / 2, 3), ); // self.committee.quorum_threshold()); debug!("asking for header with digest: {:?}", digest); for source in authorities { if source.primary.name == self.id { continue; } let msg = PrimaryMessage::SyncHeaderRequest(digest.clone(), self.id, source.primary.name); // info!("Sync Request (Conse): {:?} from {:?}", digest.clone(), source.primary.name); if let Err(e) = self.send_to_network.send((sq, msg)).await { panic!("error: {}", e); } } Ok(()) } pub async fn handle_record_header( &mut self, record_header: DBValue, rollback_stop_round: RoundNumber, ) -> Result<Option<Vec<Digest>>, DagError> { // let mut record_header: HeaderPrimaryRecord = bincode::deserialize(&record_header[..])?; let mut record_header: HeaderPrimaryRecord = bincode::deserialize(&record_header) .expect("Deserialization of primary record failure"); if self.pending_digests.contains(&record_header.digest) { self.pending_digests.remove(&record_header.digest); } if!record_header.passed_to_consensus { let msg = ConsensusMessage::Header( record_header.header.clone(), record_header.digest.clone(), ); self.send_to_consensus(msg) .await .expect("Fail to send to consensus channel"); record_header.passed_to_consensus = true; self.store .write(record_header.digest.0.to_vec(), record_header.to_bytes()) .await; return if record_header.header.round <= rollback_stop_round || record_header.header.round <= 1 { //no need need to sync parents because we gc them and consensus does not going to order them. Ok(None) } else { let digests: Vec<Digest> = record_header .header .parents .iter() .clone() .map(|(_, digest)| digest.clone()) .collect(); Ok(Some(digests)) }; } Ok(None) } pub async fn send_to_consensus(&mut self, msg: ConsensusMessage) -> Result<(), DagError> { self.send_to_consensus_channel .send(msg) .await .map_err(|e| DagError::ChannelError { error: format!("{}", e), })?; Ok(()) } }
random_line_split
synchronizer.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::committee::*; use super::error::*; use super::messages::*; use super::types::*; use bincode::Error; use crypto::Digest; use futures::future::{Fuse, FutureExt}; use futures::select; use futures::stream::futures_unordered::FuturesUnordered; use futures::stream::StreamExt; use futures::{future::FusedFuture, pin_mut}; use log::*; use rand::seq::SliceRandom; use std::cmp::max; use std::cmp::min; use std::collections::HashSet; use store::Store; use tokio::sync::mpsc; use tokio::sync::mpsc::{Receiver, Sender}; use tokio::time::{sleep, Duration}; type DBValue = Vec<u8>; /// A service that keeps watching for the dependencies of blocks. pub async fn header_waiter_process( mut store: Store, // A copy of the inner store genesis: Vec<Certificate>, // The genesis set of certs mut rx: mpsc::UnboundedReceiver<(SignedBlockHeader, BlockHeader)>, // A channel to receive Headers loopback_commands: Sender<PrimaryMessage>, ) { // Register the genesis certs... for cert in &genesis { // let bytes: Vec<u8> = bincode::serialize(&cert)?; let digest_in_store = PartialCertificate::make_digest(&cert.digest, 0, cert.primary_id); let _ = store .write(digest_in_store.0.to_vec(), digest_in_store.0.to_vec()) //digest_in_store.0.to_vec() --> bytes? .await; } // Create an unordered set of futures let mut waiting_headers = FuturesUnordered::new(); // Now process headers and also headers with satisfied dependencies loop { select! { signer_header_result = waiting_headers.select_next_some() => { // Once we have all header dependencies, we try to re-inject this signed header if let Ok(signed_header) = signer_header_result { if let Err(e) = loopback_commands.send(PrimaryMessage::Header(signed_header)).await { error!("Error sending loopback command: {}", e); } } else { error!("Error in waiter."); } } msg = rx.recv().fuse() => { if let Some((signed_header, header)) = msg { let i2_store = store.clone(); let fut = header_waiter(i2_store, signed_header, header); waiting_headers.push(fut); } else { // Channel is closed, so we exit. // Our primary is gone! warn!("Exiting digest waiter process."); break; } } } } } /// The future that waits for a set of headers and digest associated with a header. pub async fn header_waiter( mut store: Store, // A copy of the store signed_header: SignedBlockHeader, // The signed header structure header: BlockHeader, // The header for which we wait for dependencies. ) -> Result<SignedBlockHeader, DagError> { debug!( "[DEP] ASK H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); //Note: we now store different digests for header and certificates to avoid false positive. for (other_primary_id, digest) in &header.parents { let digest_in_store = PartialCertificate::make_digest(&digest, header.round - 1, *other_primary_id); if store.notify_read(digest_in_store.0.to_vec()).await.is_err() { return Err(DagError::StorageFailure { error: "Error in reading store from 'header_waiter'.".to_string(), }); } } for (digest, _) in &header.transactions_digest { if store.notify_read(digest.0.to_vec()).await.is_err() { return Err(DagError::StorageFailure { error: "Error in reading store from 'header_waiter'.".to_string(), }); } } debug!( "[DEP] GOT H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); Ok(signed_header) } pub async fn dag_synchronizer_process( mut get_from_dag: Receiver<SyncMessage>, dag_synchronizer: DagSynchronizer, ) { let mut digests_to_sync: Vec<Digest> = Vec::new(); let mut round_to_sync: RoundNumber = 0; let mut last_synced_round: RoundNumber = 0; let mut rollback_stop_round: RoundNumber = 1; let mut sq: SyncNumber = 0; let rollback_fut = Fuse::terminated(); pin_mut!(rollback_fut); loop { select! { msg = get_from_dag.recv().fuse() => { if let Some(SyncMessage::SyncUpToRound(round, digests, last_gc_round)) = msg { if round > round_to_sync { debug!("DAG sync: received request to sync digests: {:?} up to round {}", digests, round); round_to_sync = round; digests_to_sync = digests; rollback_stop_round = max(last_gc_round+1, 1); if rollback_fut.is_terminated(){ last_synced_round = round_to_sync; rollback_fut.set(rollback_headers(dag_synchronizer.clone(), digests_to_sync.clone(), round_to_sync, rollback_stop_round, sq).fuse()); debug!("DAG sync: go."); } else { debug!("DAG sync: drop."); } } } else{ warn!("Exiting DagSynchronizer::start()."); break; } } res = rollback_fut => { if let Err(e) = res{ error!("rollback_headers returns error: {:?}", e); } else{ sq += 1; if round_to_sync > last_synced_round{ last_synced_round = round_to_sync; // rollback_stop_round = max(last_synced_round, 1); rollback_fut.set(rollback_headers(dag_synchronizer.clone(), digests_to_sync.clone(), round_to_sync, rollback_stop_round, sq).fuse()); } } } } } } pub async fn
( mut dag_synchronizer: DagSynchronizer, digest: Digest, rollback_stop_round: RoundNumber, sq: SyncNumber, ) -> Result<Option<Vec<Digest>>, DagError> { //TODO: issue: should we try the processor first? we need concurrent access to it... if let Ok(dbvalue) = dag_synchronizer.store.read(digest.to_vec()).await { match dbvalue { None => { debug!("invoking send_sync_header_requests: {:?}", digest); dag_synchronizer .send_sync_header_requests(digest.clone(), sq) .await?; // Exponential backoff delay let mut delay = 50; loop { select! { ret = dag_synchronizer.store.notify_read(digest.to_vec()).fuse() =>{ if let Ok(record_header) = ret { return Ok(dag_synchronizer.handle_record_header(record_header, rollback_stop_round).await?); } else { //handle the error. error!("Read returned an error: {:?}", ret); } } _ = sleep(Duration::from_millis(delay)).fuse() => { debug!("Trigger Sync on {:?}", digest); dag_synchronizer.send_sync_header_requests(digest.clone(), sq).await?; delay *= 4; } } } } // HERE Some(record_header) => { let result: Result<HeaderPrimaryRecord, Error> = bincode::deserialize(&record_header); if let Err(e) = result { panic!("Reading digest {:?} from store gives us a struct that we cannot deserialize: {}", digest, e); } return Ok(dag_synchronizer .handle_record_header(record_header, rollback_stop_round) .await?); } } } else { //handle the error. } Ok(None) } //sync all digests' causal history and pass to consensus pub async fn rollback_headers( mut dag_synchronizer: DagSynchronizer, digests: Vec<Digest>, round: RoundNumber, rollback_stop_round: RoundNumber, sq: SyncNumber, ) -> Result<(), DagError> { let mut asked_for: HashSet<Digest> = HashSet::new(); let mut digests_in_process = FuturesUnordered::new(); for digest in digests { let fut = handle_header_digest(dag_synchronizer.clone(), digest, rollback_stop_round, sq); digests_in_process.push(fut); } while!digests_in_process.is_empty() { // let option = digests_in_process.select_next_some().await?; let option = match digests_in_process.select_next_some().await { Ok(option) => option, Err(e) => panic!("Panix {}", e), }; if let Some(parents_digests) = option { for digest in parents_digests { // Only ask for each digest once per rollback. if asked_for.contains(&digest) { continue; } asked_for.insert(digest.clone()); if!dag_synchronizer.pending_digests.contains(&digest) { debug!("Seems so {}", digest); dag_synchronizer.pending_digests.insert(digest.clone()); let fut = handle_header_digest( dag_synchronizer.clone(), digest, rollback_stop_round, sq, ); digests_in_process.push(fut); } } } } let msg = ConsensusMessage::SyncDone(round); dag_synchronizer.send_to_consensus(msg).await?; info!("DAG sync: sent to consensus SyncDone for round {}", round); Ok(()) } #[derive(Clone)] pub struct DagSynchronizer { pub id: NodeID, pub send_to_consensus_channel: Sender<ConsensusMessage>, pub send_to_network: Sender<(RoundNumber, PrimaryMessage)>, pub store: Store, pub committee: Committee, pub pending_digests: HashSet<Digest>, } impl DagSynchronizer { pub fn new( id: NodeID, committee: Committee, store: Store, send_to_consensus_channel: Sender<ConsensusMessage>, send_to_network: Sender<(RoundNumber, PrimaryMessage)>, ) -> Self { DagSynchronizer { id, send_to_consensus_channel, send_to_network, store, committee, pending_digests: HashSet::new(), } } pub async fn send_sync_header_requests( &mut self, digest: Digest, sq: SyncNumber, ) -> Result<(), DagError> { //Pick random 3 validators. Hopefully one will have the header. We can implement different strategies. let authorities = self.committee.authorities.choose_multiple( &mut rand::thread_rng(), min(self.committee.quorum_threshold() / 2, 3), ); // self.committee.quorum_threshold()); debug!("asking for header with digest: {:?}", digest); for source in authorities { if source.primary.name == self.id { continue; } let msg = PrimaryMessage::SyncHeaderRequest(digest.clone(), self.id, source.primary.name); // info!("Sync Request (Conse): {:?} from {:?}", digest.clone(), source.primary.name); if let Err(e) = self.send_to_network.send((sq, msg)).await { panic!("error: {}", e); } } Ok(()) } pub async fn handle_record_header( &mut self, record_header: DBValue, rollback_stop_round: RoundNumber, ) -> Result<Option<Vec<Digest>>, DagError> { // let mut record_header: HeaderPrimaryRecord = bincode::deserialize(&record_header[..])?; let mut record_header: HeaderPrimaryRecord = bincode::deserialize(&record_header) .expect("Deserialization of primary record failure"); if self.pending_digests.contains(&record_header.digest) { self.pending_digests.remove(&record_header.digest); } if!record_header.passed_to_consensus { let msg = ConsensusMessage::Header( record_header.header.clone(), record_header.digest.clone(), ); self.send_to_consensus(msg) .await .expect("Fail to send to consensus channel"); record_header.passed_to_consensus = true; self.store .write(record_header.digest.0.to_vec(), record_header.to_bytes()) .await; return if record_header.header.round <= rollback_stop_round || record_header.header.round <= 1 { //no need need to sync parents because we gc them and consensus does not going to order them. Ok(None) } else { let digests: Vec<Digest> = record_header .header .parents .iter() .clone() .map(|(_, digest)| digest.clone()) .collect(); Ok(Some(digests)) }; } Ok(None) } pub async fn send_to_consensus(&mut self, msg: ConsensusMessage) -> Result<(), DagError> { self.send_to_consensus_channel .send(msg) .await .map_err(|e| DagError::ChannelError { error: format!("{}", e), })?; Ok(()) } }
handle_header_digest
identifier_name
synchronizer.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::committee::*; use super::error::*; use super::messages::*; use super::types::*; use bincode::Error; use crypto::Digest; use futures::future::{Fuse, FutureExt}; use futures::select; use futures::stream::futures_unordered::FuturesUnordered; use futures::stream::StreamExt; use futures::{future::FusedFuture, pin_mut}; use log::*; use rand::seq::SliceRandom; use std::cmp::max; use std::cmp::min; use std::collections::HashSet; use store::Store; use tokio::sync::mpsc; use tokio::sync::mpsc::{Receiver, Sender}; use tokio::time::{sleep, Duration}; type DBValue = Vec<u8>; /// A service that keeps watching for the dependencies of blocks. pub async fn header_waiter_process( mut store: Store, // A copy of the inner store genesis: Vec<Certificate>, // The genesis set of certs mut rx: mpsc::UnboundedReceiver<(SignedBlockHeader, BlockHeader)>, // A channel to receive Headers loopback_commands: Sender<PrimaryMessage>, ) { // Register the genesis certs... for cert in &genesis { // let bytes: Vec<u8> = bincode::serialize(&cert)?; let digest_in_store = PartialCertificate::make_digest(&cert.digest, 0, cert.primary_id); let _ = store .write(digest_in_store.0.to_vec(), digest_in_store.0.to_vec()) //digest_in_store.0.to_vec() --> bytes? .await; } // Create an unordered set of futures let mut waiting_headers = FuturesUnordered::new(); // Now process headers and also headers with satisfied dependencies loop { select! { signer_header_result = waiting_headers.select_next_some() => { // Once we have all header dependencies, we try to re-inject this signed header if let Ok(signed_header) = signer_header_result { if let Err(e) = loopback_commands.send(PrimaryMessage::Header(signed_header)).await { error!("Error sending loopback command: {}", e); } } else { error!("Error in waiter."); } } msg = rx.recv().fuse() => { if let Some((signed_header, header)) = msg { let i2_store = store.clone(); let fut = header_waiter(i2_store, signed_header, header); waiting_headers.push(fut); } else { // Channel is closed, so we exit. // Our primary is gone! warn!("Exiting digest waiter process."); break; } } } } } /// The future that waits for a set of headers and digest associated with a header. pub async fn header_waiter( mut store: Store, // A copy of the store signed_header: SignedBlockHeader, // The signed header structure header: BlockHeader, // The header for which we wait for dependencies. ) -> Result<SignedBlockHeader, DagError>
}); } } debug!( "[DEP] GOT H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); Ok(signed_header) } pub async fn dag_synchronizer_process( mut get_from_dag: Receiver<SyncMessage>, dag_synchronizer: DagSynchronizer, ) { let mut digests_to_sync: Vec<Digest> = Vec::new(); let mut round_to_sync: RoundNumber = 0; let mut last_synced_round: RoundNumber = 0; let mut rollback_stop_round: RoundNumber = 1; let mut sq: SyncNumber = 0; let rollback_fut = Fuse::terminated(); pin_mut!(rollback_fut); loop { select! { msg = get_from_dag.recv().fuse() => { if let Some(SyncMessage::SyncUpToRound(round, digests, last_gc_round)) = msg { if round > round_to_sync { debug!("DAG sync: received request to sync digests: {:?} up to round {}", digests, round); round_to_sync = round; digests_to_sync = digests; rollback_stop_round = max(last_gc_round+1, 1); if rollback_fut.is_terminated(){ last_synced_round = round_to_sync; rollback_fut.set(rollback_headers(dag_synchronizer.clone(), digests_to_sync.clone(), round_to_sync, rollback_stop_round, sq).fuse()); debug!("DAG sync: go."); } else { debug!("DAG sync: drop."); } } } else{ warn!("Exiting DagSynchronizer::start()."); break; } } res = rollback_fut => { if let Err(e) = res{ error!("rollback_headers returns error: {:?}", e); } else{ sq += 1; if round_to_sync > last_synced_round{ last_synced_round = round_to_sync; // rollback_stop_round = max(last_synced_round, 1); rollback_fut.set(rollback_headers(dag_synchronizer.clone(), digests_to_sync.clone(), round_to_sync, rollback_stop_round, sq).fuse()); } } } } } } pub async fn handle_header_digest( mut dag_synchronizer: DagSynchronizer, digest: Digest, rollback_stop_round: RoundNumber, sq: SyncNumber, ) -> Result<Option<Vec<Digest>>, DagError> { //TODO: issue: should we try the processor first? we need concurrent access to it... if let Ok(dbvalue) = dag_synchronizer.store.read(digest.to_vec()).await { match dbvalue { None => { debug!("invoking send_sync_header_requests: {:?}", digest); dag_synchronizer .send_sync_header_requests(digest.clone(), sq) .await?; // Exponential backoff delay let mut delay = 50; loop { select! { ret = dag_synchronizer.store.notify_read(digest.to_vec()).fuse() =>{ if let Ok(record_header) = ret { return Ok(dag_synchronizer.handle_record_header(record_header, rollback_stop_round).await?); } else { //handle the error. error!("Read returned an error: {:?}", ret); } } _ = sleep(Duration::from_millis(delay)).fuse() => { debug!("Trigger Sync on {:?}", digest); dag_synchronizer.send_sync_header_requests(digest.clone(), sq).await?; delay *= 4; } } } } // HERE Some(record_header) => { let result: Result<HeaderPrimaryRecord, Error> = bincode::deserialize(&record_header); if let Err(e) = result { panic!("Reading digest {:?} from store gives us a struct that we cannot deserialize: {}", digest, e); } return Ok(dag_synchronizer .handle_record_header(record_header, rollback_stop_round) .await?); } } } else { //handle the error. } Ok(None) } //sync all digests' causal history and pass to consensus pub async fn rollback_headers( mut dag_synchronizer: DagSynchronizer, digests: Vec<Digest>, round: RoundNumber, rollback_stop_round: RoundNumber, sq: SyncNumber, ) -> Result<(), DagError> { let mut asked_for: HashSet<Digest> = HashSet::new(); let mut digests_in_process = FuturesUnordered::new(); for digest in digests { let fut = handle_header_digest(dag_synchronizer.clone(), digest, rollback_stop_round, sq); digests_in_process.push(fut); } while!digests_in_process.is_empty() { // let option = digests_in_process.select_next_some().await?; let option = match digests_in_process.select_next_some().await { Ok(option) => option, Err(e) => panic!("Panix {}", e), }; if let Some(parents_digests) = option { for digest in parents_digests { // Only ask for each digest once per rollback. if asked_for.contains(&digest) { continue; } asked_for.insert(digest.clone()); if!dag_synchronizer.pending_digests.contains(&digest) { debug!("Seems so {}", digest); dag_synchronizer.pending_digests.insert(digest.clone()); let fut = handle_header_digest( dag_synchronizer.clone(), digest, rollback_stop_round, sq, ); digests_in_process.push(fut); } } } } let msg = ConsensusMessage::SyncDone(round); dag_synchronizer.send_to_consensus(msg).await?; info!("DAG sync: sent to consensus SyncDone for round {}", round); Ok(()) } #[derive(Clone)] pub struct DagSynchronizer { pub id: NodeID, pub send_to_consensus_channel: Sender<ConsensusMessage>, pub send_to_network: Sender<(RoundNumber, PrimaryMessage)>, pub store: Store, pub committee: Committee, pub pending_digests: HashSet<Digest>, } impl DagSynchronizer { pub fn new( id: NodeID, committee: Committee, store: Store, send_to_consensus_channel: Sender<ConsensusMessage>, send_to_network: Sender<(RoundNumber, PrimaryMessage)>, ) -> Self { DagSynchronizer { id, send_to_consensus_channel, send_to_network, store, committee, pending_digests: HashSet::new(), } } pub async fn send_sync_header_requests( &mut self, digest: Digest, sq: SyncNumber, ) -> Result<(), DagError> { //Pick random 3 validators. Hopefully one will have the header. We can implement different strategies. let authorities = self.committee.authorities.choose_multiple( &mut rand::thread_rng(), min(self.committee.quorum_threshold() / 2, 3), ); // self.committee.quorum_threshold()); debug!("asking for header with digest: {:?}", digest); for source in authorities { if source.primary.name == self.id { continue; } let msg = PrimaryMessage::SyncHeaderRequest(digest.clone(), self.id, source.primary.name); // info!("Sync Request (Conse): {:?} from {:?}", digest.clone(), source.primary.name); if let Err(e) = self.send_to_network.send((sq, msg)).await { panic!("error: {}", e); } } Ok(()) } pub async fn handle_record_header( &mut self, record_header: DBValue, rollback_stop_round: RoundNumber, ) -> Result<Option<Vec<Digest>>, DagError> { // let mut record_header: HeaderPrimaryRecord = bincode::deserialize(&record_header[..])?; let mut record_header: HeaderPrimaryRecord = bincode::deserialize(&record_header) .expect("Deserialization of primary record failure"); if self.pending_digests.contains(&record_header.digest) { self.pending_digests.remove(&record_header.digest); } if!record_header.passed_to_consensus { let msg = ConsensusMessage::Header( record_header.header.clone(), record_header.digest.clone(), ); self.send_to_consensus(msg) .await .expect("Fail to send to consensus channel"); record_header.passed_to_consensus = true; self.store .write(record_header.digest.0.to_vec(), record_header.to_bytes()) .await; return if record_header.header.round <= rollback_stop_round || record_header.header.round <= 1 { //no need need to sync parents because we gc them and consensus does not going to order them. Ok(None) } else { let digests: Vec<Digest> = record_header .header .parents .iter() .clone() .map(|(_, digest)| digest.clone()) .collect(); Ok(Some(digests)) }; } Ok(None) } pub async fn send_to_consensus(&mut self, msg: ConsensusMessage) -> Result<(), DagError> { self.send_to_consensus_channel .send(msg) .await .map_err(|e| DagError::ChannelError { error: format!("{}", e), })?; Ok(()) } }
{ debug!( "[DEP] ASK H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); //Note: we now store different digests for header and certificates to avoid false positive. for (other_primary_id, digest) in &header.parents { let digest_in_store = PartialCertificate::make_digest(&digest, header.round - 1, *other_primary_id); if store.notify_read(digest_in_store.0.to_vec()).await.is_err() { return Err(DagError::StorageFailure { error: "Error in reading store from 'header_waiter'.".to_string(), }); } } for (digest, _) in &header.transactions_digest { if store.notify_read(digest.0.to_vec()).await.is_err() { return Err(DagError::StorageFailure { error: "Error in reading store from 'header_waiter'.".to_string(),
identifier_body
lib.rs
(mut start_chars, mut end_chars) = (a.chars(), b.chars()); // We need to keep track of this, because: // In the case of `a` == `"a"` and `b` == `"aab"`, // we actually need to compare `""` to `"b"` later on, not `""` to `"a"`. let mut last_start_char = '\0'; // Counting to get the index. let mut i: usize = 0; loop { // Advance the iterators... match (start_chars.next(), end_chars.next()) { // As long as there's two characters that match, increment i. (Some(sc), Some(ec)) if sc == ec => { last_start_char = sc; i += 1; continue; } // If start_chars have run out, but end_chars haven't, check // if the current end char matches the last start char. // If it does, we still need to increment our counter. (None, Some(ec)) if ec == last_start_char => { i += 1; continue; } // break with i as soon as any mismatch happens or both iterators run out. // matching_count will either be 0, indicating that there's // no leading common pattern, or something other than 0, in // that case it's the count of common characters. (None, None) | (Some(_), None) | (None, Some(_)) | (Some(_), Some(_)) => { break i } } } }; // Count the number to add to the total requests amount. // If a or b is empty, we need one item less in the pool; // two items less if both are empty. let non_empty_input_count = [a, b].iter().filter(|s|!s.is_empty()).count(); // For convenience let computed_amount = || amount.get() + non_empty_input_count; // Calculate the distance between the first non-matching characters. // If matching_count is greater than 0, we have leading common chars, // so we skip those, but add the amount to the depth base. let branching_factor = self.distance_between_first_chars( // v--- matching_count might be higher than a.len() // vvv because we might count past a's end &a[std::cmp::min(matching_count, a.len())..], &b[matching_count..], )?; // We also add matching_count to the depth because if we're starting // with a common prefix, we have at least x leading characters that // will be the same for all substrings. let mut depth = depth_for(dbg!(branching_factor), dbg!(computed_amount())) + dbg!(matching_count); // if branching_factor == 1 { // // This should only be the case when we have an input like `"z", ""`. // // In this case, we can generate strings after the z, but we need // // to go one level deeper in any case. // depth += 1; // } // TODO: Maybe keeping this as an iterator would be more efficient, // but it would have to be cloned at least once to get the pool length. let pool: Vec<String> = self.traverse("".into(), a, b, dbg!(depth)).collect(); let pool = if (pool.len() as isize).saturating_sub(non_empty_input_count as isize) < amount.get() as isize { depth += depth_for(branching_factor, computed_amount() + pool.len()); dbg!(self.traverse("".into(), a, b, dbg!(depth)).collect()) } else { pool }; if (pool.len() as isize).saturating_sub(non_empty_input_count as isize) < amount.get() as isize { // We still don't have enough items, so bail panic!( "Internal error: Failed to calculate the correct tree depth! This is a bug. Please report it at: https://github.com/Follpvosten/mudders/issues and make sure to include the following information: Symbols in table: {symbols:?} Given inputs: {a:?}, {b:?}, amount: {amount} matching_count: {m_count} non_empty_input_count: {ne_input_count} required pool length (computed amount): {comp_amount} branching_factor: {b_factor} final depth: {depth} pool: {pool:?} (length: {pool_len})", symbols = self.0.iter().map(|i| *i as char).collect::<Box<[_]>>(), a = a, b = b, amount = amount, m_count = matching_count, ne_input_count = non_empty_input_count, comp_amount = computed_amount(), b_factor = branching_factor, depth = depth, pool = pool, pool_len = pool.len(), ) } Ok(if amount.get() == 1 { pool.get(pool.len() / 2) .map(|item| vec![item.clone()]) .ok_or_else(|| FailedToGetMiddle)? } else { let step = computed_amount() as f64 / pool.len() as f64; let mut counter = 0f64; let mut last_value = 0; let result: Vec<_> = pool .into_iter() .filter(|_| { counter += step; let new_value = counter.floor() as usize; if new_value > last_value { last_value = new_value; true } else { false } }) .take(amount.into()) .collect(); ensure! { result.len() == amount.get(), NotEnoughItemsInPool }; result }) } /// Convenience wrapper around `mudder` to generate exactly one string. /// /// # Safety /// This function calls `NonZeroUsize::new_unchecked(1)`. pub fn mudder_one(&self, a: &str, b: &str) -> Result<String, GenerationError> { self.mudder(a, b, unsafe { NonZeroUsize::new_unchecked(1) }) .map(|mut vec| vec.remove(0)) } /// Convenience wrapper around `mudder` to generate an amount of fresh strings. /// /// `SymbolTable.generate(amount)` is equivalent to `SymbolTable.mudder("", "", amount)`. pub fn generate(&self, amount: NonZeroUsize) -> Result<Vec<String>, GenerationError> { self.mudder("", "", amount) } /// Traverses a virtual tree of strings to the given depth. fn traverse<'a>( &'a self, curr_key: String, start: &'a str, end: &'a str, depth: usize, ) -> Box<dyn Iterator<Item = String> + 'a> { if depth == 0 { // If we've reached depth 0, we don't go futher. Box::new(std::iter::empty()) } else { // Generate all possible mutations on the current depth Box::new( self.0 .iter() .filter_map(move |c| -> Option<Box<dyn Iterator<Item = String>>> { // TODO: Performance - this probably still isn't the best option. let key = { let the_char = *c as char; let mut string = String::with_capacity(curr_key.len() + the_char.len_utf8()); string.push_str(&curr_key); string.push(the_char); string }; // After the end key, we definitely do not continue. if key.as_str() > end &&!end.is_empty() { None } else if key.as_str() < start { // If we're prior to the start key... //...and the start key is a subkey of the current key... if start.starts_with(&key) { //...only traverse the subtree, ignoring the key itself. Some(Box::new(self.traverse(key, start, end, depth - 1))) } else { None } } else { // Traverse normally, returning both the parent and sub key, // in all other cases. if key.len() < 2 { let iter = std::iter::once(key.clone()); Some(if key == end { Box::new(iter) } else { Box::new(iter.chain(self.traverse(key, start, end, depth - 1))) }) } else { let first = key.chars().next().unwrap(); Some(if key.chars().all(|c| c == first) { // If our characters are all the same, // don't add key to the list, only the subtree. Box::new(self.traverse(key, start, end, depth - 1)) } else { Box::new(std::iter::once(key.clone()).chain(self.traverse( key, start, end, depth - 1, ))) }) } } }) .flatten(), ) } } fn distance_between_first_chars( &self, start: &str, end: &str, ) -> Result<usize, GenerationError> { use InternalError::WrongCharOrder; // check the first character of both strings... Ok(match (start.chars().next(), end.chars().next()) { // if both have a first char, compare them. (Some(start_char), Some(end_char)) => { ensure! { start_char < end_char, WrongCharOrder(start_char, end_char) } let distance = try_ascii_u8_from_char(end_char)? - try_ascii_u8_from_char(start_char)?; distance as usize + 1 } // if only the start has a first char, compare it to our last possible symbol. (Some(start_char), None) => { let end_u8 = self.0.last().unwrap(); // In this case, we allow the start and end char to be equal. // This is because you can generate something after the last char, // but not before the first char. // vv ensure! { start_char <= *end_u8 as char, WrongCharOrder(start_char, *end_u8 as char) } let distance = end_u8 - try_ascii_u8_from_char(start_char)?; if distance == 0 { 2 } else { distance as usize + 1 } } // if only the end has a first char, compare it to our first possible symbol. (None, Some(end_char)) => { let start_u8 = self.0.first().unwrap(); ensure! { *start_u8 <= end_char as u8, WrongCharOrder(*start_u8 as char, end_char) } let distance = try_ascii_u8_from_char(end_char)? - start_u8; if distance == 0 { 2 } else { distance as usize + 1 } } // if there's no characters given, the whole symboltable is our range. _ => self.0.len(), }) } fn contains_all_chars(&self, chars: impl AsRef<[u8]>) -> bool { chars.as_ref().iter().all(|c| self.0.contains(c)) } } /// Calculate the required depth for the given values. /// /// `branching_factor` is used as the logarithm base, `n_elements` as the /// value, and the result is rounded up and cast to usize. fn depth_for(branching_factor: usize, n_elements: usize) -> usize { f64::log(n_elements as f64, branching_factor as f64).ceil() as usize } fn try_ascii_u8_from_char(c: char) -> Result<u8, NonAsciiError> { u8::try_from(c as u32).map_err(NonAsciiError::from) } fn all_chars_ascii(chars: impl AsRef<[u8]>) -> bool { chars.as_ref().iter().all(|i| i.is_ascii()) } impl FromStr for SymbolTable { type Err = CreationError; fn from_str(s: &str) -> Result<Self, CreationError> { Self::from_chars(&s.chars().collect::<Box<[_]>>()) } } #[cfg(test)] mod tests { use super::*; use std::num::NonZeroUsize; /// Create and unwrap a NonZeroUsize from the given usize. fn n(n: usize) -> NonZeroUsize { NonZeroUsize::new(n).unwrap() } // Public API tests: #[test] #[allow(clippy::char_lit_as_u8)] fn valid_tables_work() { assert!(SymbolTable::new(&[1, 2, 3, 4, 5]).is_ok()); assert!(SymbolTable::new(&[125, 126, 127]).is_ok()); // Possible, but to be discouraged assert!(SymbolTable::new(&['a' as u8, 'f' as u8]).is_ok()); assert!(SymbolTable::from_chars(&['a', 'b', 'c']).is_ok()); assert!(SymbolTable::from_str("0123").is_ok()); } #[test] fn invalid_tables_error() { assert!(SymbolTable::from_str("🍅😂👶🏻").is_err()); assert!(SymbolTable::from_chars(&['🍌', '🍣', '⛈']).is_err()); assert!(SymbolTable::new(&[128, 129, 130]).is_err()); assert!(SymbolTable::new(&[]).is_err()); assert!(SymbolTable::from_chars(&[]).is_err()); assert!(SymbolTable::from_str("").is_err()); } #[test] fn unknown_chars_error() { use error::GenerationError::UnknownCharacters; // You cannot pass in strings with characters not in the SymbolTable: let table = SymbolTable::alphabet(); assert_eq!( table.mudder_one("123", "()/"), Err(UnknownCharacters("123".into())) ); assert_eq!( table.mudder_one("a", "123"), Err(UnknownCharacters("123".into())) ); assert_eq!( table.mudder_one("0)(", "b"), Err(UnknownCharacters("0)(".into())) ); let table = SymbolTable::from_str("123").unwrap(); assert_eq!( table.mudder_one("a", "b"), Err(UnknownCharacters("a".into())) ); assert_eq!( table.mudder_one("456", "1"), Err(UnknownCharacters("456".into())) ); assert_eq!( table.mudder_one("2", "abc"), Err(UnknownCharacters("abc".into())) ); } #[test] fn equal_strings_error() { use error::GenerationError::MatchingStrings; let table = SymbolTable::alphabet(); assert_eq!( table.mudder_one("abc", "abc"), Err(MatchingStrings("abc".into())) ); assert_eq!( table.mudder_one("xyz", "xyz"), Err(MatchingStrings("xyz".into())) ); } // TODO: Make this test work. // I need to find out how to tell if two strings are lexicographically inseparable. // #[test] // fn lexicographically_adjacent_strings_error() { // assert!(SymbolTable::alphabet().mudder("ba", "baa", n(1)).is_err()); // } #[test] fn reasonable_values() { let table =
SymbolTable::from_str("ab").unwrap(); let result = table.mudder_one("a", "b").unwrap(); assert_eq!(result, "ab"); let table = SymbolTable::from_str("0123456789").unwrap(); let result = table.mudder_one("1", "2").unwrap(); assert_eq!(result, "15"); } #[test] fn o
identifier_body
lib.rs
// SymbolTable::mudder() returns a Vec containing `amount` Strings. let result = table.mudder_one("a", "z").unwrap(); // These strings are always lexicographically placed between `start` and `end`. let one_str = result.as_str(); assert!(one_str > "a"); assert!(one_str < "z"); // You can also define your own symbol tables let table = SymbolTable::from_chars(&['a', 'b']).unwrap(); let result = table.mudder("a", "b", NonZeroUsize::new(2).unwrap()).unwrap(); assert_eq!(result.len(), 2); assert!(result[0].as_str() > "a" && result[1].as_str() > "a"); assert!(result[0].as_str() < "b" && result[1].as_str() < "b"); // The strings *should* be evenly-spaced and as short as they can be. let table = SymbolTable::alphabet(); let result = table.mudder("anhui", "azazel", NonZeroUsize::new(3).unwrap()).unwrap(); assert_eq!(result.len(), 3); assert_eq!(vec!["aq", "as", "av"], result); ``` ## Notes The most notable difference to Mudder.js is that currently, mudders only supports ASCII characters (because 127 characters ought to be enough for everyone™). Our default `::alphabet()` also only has lowercase letters. */ use core::num::NonZeroUsize; use std::{convert::TryFrom, str::FromStr}; #[macro_use] pub mod error; use error::*; /// The functionality of the crate lives here. /// /// A symbol table is, internally, a vector of valid ASCII bytes that are used /// to generate lexicographically evenly-spaced strings. #[derive(Clone, Debug)] pub struct SymbolTable(Vec<u8>); impl SymbolTable { /// Creates a new symbol table from the given byte slice. /// The slice is internally sorted using `.sort()`. /// /// An error is returned if one of the given bytes is out of ASCII range. pub fn new(source: &[u8]) -> Result<Self, CreationError> { ensure! {!source.is_empty(), CreationError::EmptySlice } ensure! { all_chars_ascii(&source), NonAsciiError::NonAsciiU8 } // Copy the values, we need to own them anyways... let mut vec: Vec<_> = source.iter().copied().collect(); // Sort them so they're actually in order. // (You can pass in ['b', 'a'], but that's not usable internally I think.) vec.sort(); vec.dedup(); Ok(Self(vec)) } /// Creates a new symbol table from the given characters. /// The slice is internally sorted using `.sort()`. /// /// An error is returned if one of the given characters is not ASCII. pub fn from_chars(source: &[char]) -> Result<Self, CreationError> { let inner: Box<[u8]> = source .iter() .map(|c| try_ascii_u8_from_char(*c)) .collect::<Result<_, _>>()?; Ok(Self::new(&inner)?) } /// Returns a SymbolTable which contains the lowercase latin alphabet (`[a-z]`). #[allow(clippy::char_lit_as_u8)] pub fn alphabet() -> Self { Self::new(&('a' as u8..='z' as u8).collect::<Box<[_]>>()).unwrap() } /// Generate `amount` strings that lexicographically sort between `start` and `end`. /// The algorithm will try to make them as evenly-spaced as possible. /// /// When both parameters are empty strings, `amount` new strings that are /// in lexicographical order are returned. /// /// If parameter `b` is lexicographically before `a`, they are swapped internally. /// /// ``` /// # use mudders::SymbolTable; /// # use std::num::NonZeroUsize; /// // Using the included alphabet table /// let table = SymbolTable::alphabet(); /// // Generate 10 strings from scratch /// let results = table.mudder("", "", NonZeroUsize::new(10).unwrap()).unwrap(); /// assert!(results.len() == 10); /// // results should look something like ["b", "d", "f",..., "r", "t"] /// ``` pub fn mudder( &self, a: &str, b: &str, amount: NonZeroUsize, ) -> Result<Vec<String>, GenerationError> { use error::InternalError::*; use GenerationError::*; ensure! { all_chars_ascii(a), NonAsciiError::NonAsciiU8 } ensure! { all_chars_ascii(b), NonAsciiError::NonAsciiU8 } ensure! { self.contains_all_chars(a), UnknownCharacters(a.to_string()) } ensure! { self.contains_all_chars(b), UnknownCharacters(b.to_string()) } let (a, b) = if a.is_empty() || b.is_empty() { // If an argument is empty, keep the order (a, b) } else if b < a { // If they're not empty and b is lexicographically prior to a, swap them (b, a) } else { // You can't generate values between two matching strings. ensure! { a!= b, MatchingStrings(a.to_string()) } // In any other case, keep the order (a, b) }; // TODO: Check for lexicographical adjacency! //ensure! {!lex_adjacent(a, b), LexAdjacentStrings(a.to_string(), b.to_string()) } // Count the characters start and end have in common. let matching_count: usize = { // Iterate through the chars of both given inputs... let (mut start_chars, mut end_chars) = (a.chars(), b.chars()); // We need to keep track of this, because: // In the case of `a` == `"a"` and `b` == `"aab"`, // we actually need to compare `""` to `"b"` later on, not `""` to `"a"`. let mut last_start_char = '\0'; // Counting to get the index. let mut i: usize = 0; loop { // Advance the iterators... match (start_chars.next(), end_chars.next()) { // As long as there's two characters that match, increment i. (Some(sc), Some(ec)) if sc == ec => { last_start_char = sc; i += 1; continue; } // If start_chars have run out, but end_chars haven't, check // if the current end char matches the last start char. // If it does, we still need to increment our counter. (None, Some(ec)) if ec == last_start_char => { i += 1; continue; } // break with i as soon as any mismatch happens or both iterators run out. // matching_count will either be 0, indicating that there's // no leading common pattern, or something other than 0, in // that case it's the count of common characters. (None, None) | (Some(_), None) | (None, Some(_)) | (Some(_), Some(_)) => { break i } } } }; // Count the number to add to the total requests amount. // If a or b is empty, we need one item less in the pool; // two items less if both are empty. let non_empty_input_count = [a, b].iter().filter(|s|!s.is_empty()).count(); // For convenience let computed_amount = || amount.get() + non_empty_input_count; // Calculate the distance between the first non-matching characters. // If matching_count is greater than 0, we have leading common chars, // so we skip those, but add the amount to the depth base. let branching_factor = self.distance_between_first_chars( // v--- matching_count might be higher than a.len() // vvv because we might count past a's end &a[std::cmp::min(matching_count, a.len())..], &b[matching_count..], )?; // We also add matching_count to the depth because if we're starting // with a common prefix, we have at least x leading characters that // will be the same for all substrings. let mut depth = depth_for(dbg!(branching_factor), dbg!(computed_amount())) + dbg!(matching_count); // if branching_factor == 1 { // // This should only be the case when we have an input like `"z", ""`. // // In this case, we can generate strings after the z, but we need // // to go one level deeper in any case. // depth += 1; // } // TODO: Maybe keeping this as an iterator would be more efficient, // but it would have to be cloned at least once to get the pool length. let pool: Vec<String> = self.traverse("".into(), a, b, dbg!(depth)).collect(); let pool = if (pool.len() as isize).saturating_sub(non_empty_input_count as isize) < amount.get() as isize { depth += depth_for(branching_factor, computed_amount() + pool.len()); dbg!(self.traverse("".into(), a, b, dbg!(depth)).collect()) } else { pool }; if (pool.len() as isize).saturating_sub(non_empty_input_count as isize) < amount.get() as isize { // We still don't have enough items, so bail panic!( "Internal error: Failed to calculate the correct tree depth! This is a bug. Please report it at: https://github.com/Follpvosten/mudders/issues and make sure to include the following information: Symbols in table: {symbols:?} Given inputs: {a:?}, {b:?}, amount: {amount} matching_count: {m_count} non_empty_input_count: {ne_input_count} required pool length (computed amount): {comp_amount} branching_factor: {b_factor} final depth: {depth} pool: {pool:?} (length: {pool_len})", symbols = self.0.iter().map(|i| *i as char).collect::<Box<[_]>>(), a = a, b = b, amount = amount, m_count = matching_count, ne_input_count = non_empty_input_count, comp_amount = computed_amount(), b_factor = branching_factor, depth = depth, pool = pool, pool_len = pool.len(), ) } Ok(if amount.get() == 1 { pool.get(pool.len() / 2) .map(|item| vec![item.clone()]) .ok_or_else(|| FailedToGetMiddle)? } else { let step = computed_amount() as f64 / pool.len() as f64; let mut counter = 0f64; let mut last_value = 0; let result: Vec<_> = pool .into_iter() .filter(|_| { counter += step; let new_value = counter.floor() as usize; if new_value > last_value { last_value = new_value; true } else { false } }) .take(amount.into()) .collect(); ensure! { result.len() == amount.get(), NotEnoughItemsInPool }; result }) } /// Convenience wrapper around `mudder` to generate exactly one string. /// /// # Safety /// This function calls `NonZeroUsize::new_unchecked(1)`. pub fn mudder_one(&self, a: &str, b: &str) -> Result<String, GenerationError> { self.mudder(a, b, unsafe { NonZeroUsize::new_unchecked(1) }) .map(|mut vec| vec.remove(0)) } /// Convenience wrapper around `mudder` to generate an amount of fresh strings. /// /// `SymbolTable.generate(amount)` is equivalent to `SymbolTable.mudder("", "", amount)`. pub fn generate(&self, amount: NonZeroUsize) -> Result<Vec<String>, GenerationError> { self.mudder("", "", amount) } /// Traverses a virtual tree of strings to the given depth. fn traverse<'a>( &'a self, curr_key: String, start: &'a str, end: &'a str, depth: usize, ) -> Box<dyn Iterator<Item = String> + 'a> { if depth == 0 { // If we've reached depth 0, we don't go futher. Box::new(std::iter::empty()) } else { // Generate all possible mutations on the current depth Box::new( self.0 .iter() .filter_map(move |c| -> Option<Box<dyn Iterator<Item = String>>> { // TODO: Performance - this probably still isn't the best option. let key = { let the_char = *c as char; let mut string = String::with_capacity(curr_key.len() + the_char.len_utf8()); string.push_str(&curr_key); string.push(the_char); string }; // After the end key, we definitely do not continue. if key.as_str() > end &&!end.is_empty() { None } else if key.as_str() < start { // If we're prior to the start key... //...and the start key is a subkey of the current key... if start.starts_with(&key) { //...only traverse the subtree, ignoring the key itself. Some(Box::new(self.traverse(key, start, end, depth - 1))) } else { None } } else { // Traverse normally, returning both the parent and sub key, // in all other cases. if key.len() < 2 { let iter = std::iter::once(key.clone()); Some(if key == end { Box::new(iter) } else { Box::new(iter.chain(self.traverse(key, start, end, depth - 1))) }) } else { let first = key.chars().next().unwrap(); Some(if key.chars().all(|c| c == first) { // If our characters are all the same, // don't add key to the list, only the subtree. Box::new(self.traverse(key, start, end, depth - 1)) } else { Box::new(std::iter::once(key.clone()).chain(self.traverse( key, start, end, depth - 1, ))) }) } } }) .flatten(), ) } } fn distance_between_first_chars( &self, start: &str, end: &str, ) -> Result<usize, GenerationError> { use InternalError::WrongCharOrder; // check the first character of both strings... Ok(match (start.chars().next(), end.chars().next()) { // if both have a first char, compare them. (Some(start_char), Some(end_char)) => { ensure! { start_char < end_char, WrongCharOrder(start_char, end_char) } let distance = try_ascii_u8_from_char(end_char)? - try_ascii_u8_from_char(start_char)?; distance as usize + 1 } // if only the start has a first char, compare it to our last possible symbol. (Some(start_char), None) => { let end_u8 = self.0.last().unwrap(); // In this case, we allow the start and end char to be equal. // This is because you can generate something after the last char, // but not before the first char. // vv ensure! { start_char <= *end_u8 as char, WrongCharOrder(start_char, *end_u8 as char) } let distance = end_u8 - try_ascii_u8_from_char(start_char)?; if distance == 0 { 2 } else { distance as usize + 1 } } // if only the end has a first char, compare it to our first possible symbol. (None, Some(end_char)) => { let start_u8 = self.0.first().unwrap(); ensure! { *start_u8 <= end_char as u8, WrongCharOrder(*start_u8 as char, end_char) } let distance = try_ascii_u8_from_char(end_char)? - start_u8; if distance == 0 { 2 } else { distance
// so you cannot pass in an invalid value. use std::num::NonZeroUsize; // You can use the included alphabet table let table = SymbolTable::alphabet();
random_line_split
lib.rs
..., "r", "t"] /// ``` pub fn mudder( &self, a: &str, b: &str, amount: NonZeroUsize, ) -> Result<Vec<String>, GenerationError> { use error::InternalError::*; use GenerationError::*; ensure! { all_chars_ascii(a), NonAsciiError::NonAsciiU8 } ensure! { all_chars_ascii(b), NonAsciiError::NonAsciiU8 } ensure! { self.contains_all_chars(a), UnknownCharacters(a.to_string()) } ensure! { self.contains_all_chars(b), UnknownCharacters(b.to_string()) } let (a, b) = if a.is_empty() || b.is_empty() { // If an argument is empty, keep the order (a, b) } else if b < a { // If they're not empty and b is lexicographically prior to a, swap them (b, a) } else { // You can't generate values between two matching strings. ensure! { a!= b, MatchingStrings(a.to_string()) } // In any other case, keep the order (a, b) }; // TODO: Check for lexicographical adjacency! //ensure! {!lex_adjacent(a, b), LexAdjacentStrings(a.to_string(), b.to_string()) } // Count the characters start and end have in common. let matching_count: usize = { // Iterate through the chars of both given inputs... let (mut start_chars, mut end_chars) = (a.chars(), b.chars()); // We need to keep track of this, because: // In the case of `a` == `"a"` and `b` == `"aab"`, // we actually need to compare `""` to `"b"` later on, not `""` to `"a"`. let mut last_start_char = '\0'; // Counting to get the index. let mut i: usize = 0; loop { // Advance the iterators... match (start_chars.next(), end_chars.next()) { // As long as there's two characters that match, increment i. (Some(sc), Some(ec)) if sc == ec => { last_start_char = sc; i += 1; continue; } // If start_chars have run out, but end_chars haven't, check // if the current end char matches the last start char. // If it does, we still need to increment our counter. (None, Some(ec)) if ec == last_start_char => { i += 1; continue; } // break with i as soon as any mismatch happens or both iterators run out. // matching_count will either be 0, indicating that there's // no leading common pattern, or something other than 0, in // that case it's the count of common characters. (None, None) | (Some(_), None) | (None, Some(_)) | (Some(_), Some(_)) => { break i } } } }; // Count the number to add to the total requests amount. // If a or b is empty, we need one item less in the pool; // two items less if both are empty. let non_empty_input_count = [a, b].iter().filter(|s|!s.is_empty()).count(); // For convenience let computed_amount = || amount.get() + non_empty_input_count; // Calculate the distance between the first non-matching characters. // If matching_count is greater than 0, we have leading common chars, // so we skip those, but add the amount to the depth base. let branching_factor = self.distance_between_first_chars( // v--- matching_count might be higher than a.len() // vvv because we might count past a's end &a[std::cmp::min(matching_count, a.len())..], &b[matching_count..], )?; // We also add matching_count to the depth because if we're starting // with a common prefix, we have at least x leading characters that // will be the same for all substrings. let mut depth = depth_for(dbg!(branching_factor), dbg!(computed_amount())) + dbg!(matching_count); // if branching_factor == 1 { // // This should only be the case when we have an input like `"z", ""`. // // In this case, we can generate strings after the z, but we need // // to go one level deeper in any case. // depth += 1; // } // TODO: Maybe keeping this as an iterator would be more efficient, // but it would have to be cloned at least once to get the pool length. let pool: Vec<String> = self.traverse("".into(), a, b, dbg!(depth)).collect(); let pool = if (pool.len() as isize).saturating_sub(non_empty_input_count as isize) < amount.get() as isize { depth += depth_for(branching_factor, computed_amount() + pool.len()); dbg!(self.traverse("".into(), a, b, dbg!(depth)).collect()) } else { pool }; if (pool.len() as isize).saturating_sub(non_empty_input_count as isize) < amount.get() as isize {
comp_amount = computed_amount(), b_factor = branching_factor, depth = depth, pool = pool, pool_len = pool.len(), ) } Ok(if amount.get() == 1 { pool.get(pool.len() / 2) .map(|item| vec![item.clone()]) .ok_or_else(|| FailedToGetMiddle)? } else { let step = computed_amount() as f64 / pool.len() as f64; let mut counter = 0f64; let mut last_value = 0; let result: Vec<_> = pool .into_iter() .filter(|_| { counter += step; let new_value = counter.floor() as usize; if new_value > last_value { last_value = new_value; true } else { false } }) .take(amount.into()) .collect(); ensure! { result.len() == amount.get(), NotEnoughItemsInPool }; result }) } /// Convenience wrapper around `mudder` to generate exactly one string. /// /// # Safety /// This function calls `NonZeroUsize::new_unchecked(1)`. pub fn mudder_one(&self, a: &str, b: &str) -> Result<String, GenerationError> { self.mudder(a, b, unsafe { NonZeroUsize::new_unchecked(1) }) .map(|mut vec| vec.remove(0)) } /// Convenience wrapper around `mudder` to generate an amount of fresh strings. /// /// `SymbolTable.generate(amount)` is equivalent to `SymbolTable.mudder("", "", amount)`. pub fn generate(&self, amount: NonZeroUsize) -> Result<Vec<String>, GenerationError> { self.mudder("", "", amount) } /// Traverses a virtual tree of strings to the given depth. fn traverse<'a>( &'a self, curr_key: String, start: &'a str, end: &'a str, depth: usize, ) -> Box<dyn Iterator<Item = String> + 'a> { if depth == 0 { // If we've reached depth 0, we don't go futher. Box::new(std::iter::empty()) } else { // Generate all possible mutations on the current depth Box::new( self.0 .iter() .filter_map(move |c| -> Option<Box<dyn Iterator<Item = String>>> { // TODO: Performance - this probably still isn't the best option. let key = { let the_char = *c as char; let mut string = String::with_capacity(curr_key.len() + the_char.len_utf8()); string.push_str(&curr_key); string.push(the_char); string }; // After the end key, we definitely do not continue. if key.as_str() > end &&!end.is_empty() { None } else if key.as_str() < start { // If we're prior to the start key... //...and the start key is a subkey of the current key... if start.starts_with(&key) { //...only traverse the subtree, ignoring the key itself. Some(Box::new(self.traverse(key, start, end, depth - 1))) } else { None } } else { // Traverse normally, returning both the parent and sub key, // in all other cases. if key.len() < 2 { let iter = std::iter::once(key.clone()); Some(if key == end { Box::new(iter) } else { Box::new(iter.chain(self.traverse(key, start, end, depth - 1))) }) } else { let first = key.chars().next().unwrap(); Some(if key.chars().all(|c| c == first) { // If our characters are all the same, // don't add key to the list, only the subtree. Box::new(self.traverse(key, start, end, depth - 1)) } else { Box::new(std::iter::once(key.clone()).chain(self.traverse( key, start, end, depth - 1, ))) }) } } }) .flatten(), ) } } fn distance_between_first_chars( &self, start: &str, end: &str, ) -> Result<usize, GenerationError> { use InternalError::WrongCharOrder; // check the first character of both strings... Ok(match (start.chars().next(), end.chars().next()) { // if both have a first char, compare them. (Some(start_char), Some(end_char)) => { ensure! { start_char < end_char, WrongCharOrder(start_char, end_char) } let distance = try_ascii_u8_from_char(end_char)? - try_ascii_u8_from_char(start_char)?; distance as usize + 1 } // if only the start has a first char, compare it to our last possible symbol. (Some(start_char), None) => { let end_u8 = self.0.last().unwrap(); // In this case, we allow the start and end char to be equal. // This is because you can generate something after the last char, // but not before the first char. // vv ensure! { start_char <= *end_u8 as char, WrongCharOrder(start_char, *end_u8 as char) } let distance = end_u8 - try_ascii_u8_from_char(start_char)?; if distance == 0 { 2 } else { distance as usize + 1 } } // if only the end has a first char, compare it to our first possible symbol. (None, Some(end_char)) => { let start_u8 = self.0.first().unwrap(); ensure! { *start_u8 <= end_char as u8, WrongCharOrder(*start_u8 as char, end_char) } let distance = try_ascii_u8_from_char(end_char)? - start_u8; if distance == 0 { 2 } else { distance as usize + 1 } } // if there's no characters given, the whole symboltable is our range. _ => self.0.len(), }) } fn contains_all_chars(&self, chars: impl AsRef<[u8]>) -> bool { chars.as_ref().iter().all(|c| self.0.contains(c)) } } /// Calculate the required depth for the given values. /// /// `branching_factor` is used as the logarithm base, `n_elements` as the /// value, and the result is rounded up and cast to usize. fn depth_for(branching_factor: usize, n_elements: usize) -> usize { f64::log(n_elements as f64, branching_factor as f64).ceil() as usize } fn try_ascii_u8_from_char(c: char) -> Result<u8, NonAsciiError> { u8::try_from(c as u32).map_err(NonAsciiError::from) } fn all_chars_ascii(chars: impl AsRef<[u8]>) -> bool { chars.as_ref().iter().all(|i| i.is_ascii()) } impl FromStr for SymbolTable { type Err = CreationError; fn from_str(s: &str) -> Result<Self, CreationError> { Self::from_chars(&s.chars().collect::<Box<[_]>>()) } } #[cfg(test)] mod tests { use super::*; use std::num::NonZeroUsize; /// Create and unwrap a NonZeroUsize from the given usize. fn n(n: usize) -> NonZeroUsize { NonZeroUsize::new(n).unwrap() } // Public API tests: #[test] #[allow(clippy::char_lit_as_u8)] fn valid_tables_work() { assert!(SymbolTable::new(&[1, 2, 3, 4, 5]).is_ok()); assert!(SymbolTable::new(&[125, 126, 127]).is_ok()); // Possible, but to be discouraged assert!(SymbolTable::new(&['a' as u8, 'f' as u8]).is_ok()); assert!(SymbolTable::from_chars(&['a', 'b', 'c']).is_ok()); assert!(SymbolTable::from_str("0123").is_ok()); } #[test] fn invalid_tables_error() { assert!(SymbolTable::from_str("🍅😂👶🏻").is_err()); assert!(SymbolTable::from_chars(&['🍌', '🍣', '⛈']).is_err()); assert!(SymbolTable::new(&[128, 129, 130]).is_err()); assert!(SymbolTable::new(&[]).is_err()); assert!(SymbolTable::from_chars(&[]).is_err()); assert!(SymbolTable::from_str("").is_err()); } #[test] fn unknown_chars_error() { use error::GenerationError::UnknownCharacters; // You cannot pass in strings with characters not in the SymbolTable: let table = SymbolTable::alphabet(); assert_eq!( table.mudder_one("123", "()/"), Err(UnknownCharacters("123".into())) ); assert_eq!( table.mudder_one("a", "123"), Err(UnknownCharacters("123".into())) ); assert_eq!( table.mudder_one("0)(", "b"), Err(UnknownCharacters("0)(".into())) ); let table = SymbolTable::from_str("123").unwrap(); assert_eq!( table.mudder_one("a", "b"), Err(UnknownCharacters("a".into())) );
// We still don't have enough items, so bail panic!( "Internal error: Failed to calculate the correct tree depth! This is a bug. Please report it at: https://github.com/Follpvosten/mudders/issues and make sure to include the following information: Symbols in table: {symbols:?} Given inputs: {a:?}, {b:?}, amount: {amount} matching_count: {m_count} non_empty_input_count: {ne_input_count} required pool length (computed amount): {comp_amount} branching_factor: {b_factor} final depth: {depth} pool: {pool:?} (length: {pool_len})", symbols = self.0.iter().map(|i| *i as char).collect::<Box<[_]>>(), a = a, b = b, amount = amount, m_count = matching_count, ne_input_count = non_empty_input_count,
conditional_block
lib.rs
-> Self { Self::new(&('a' as u8..='z' as u8).collect::<Box<[_]>>()).unwrap() } /// Generate `amount` strings that lexicographically sort between `start` and `end`. /// The algorithm will try to make them as evenly-spaced as possible. /// /// When both parameters are empty strings, `amount` new strings that are /// in lexicographical order are returned. /// /// If parameter `b` is lexicographically before `a`, they are swapped internally. /// /// ``` /// # use mudders::SymbolTable; /// # use std::num::NonZeroUsize; /// // Using the included alphabet table /// let table = SymbolTable::alphabet(); /// // Generate 10 strings from scratch /// let results = table.mudder("", "", NonZeroUsize::new(10).unwrap()).unwrap(); /// assert!(results.len() == 10); /// // results should look something like ["b", "d", "f",..., "r", "t"] /// ``` pub fn mudder( &self, a: &str, b: &str, amount: NonZeroUsize, ) -> Result<Vec<String>, GenerationError> { use error::InternalError::*; use GenerationError::*; ensure! { all_chars_ascii(a), NonAsciiError::NonAsciiU8 } ensure! { all_chars_ascii(b), NonAsciiError::NonAsciiU8 } ensure! { self.contains_all_chars(a), UnknownCharacters(a.to_string()) } ensure! { self.contains_all_chars(b), UnknownCharacters(b.to_string()) } let (a, b) = if a.is_empty() || b.is_empty() { // If an argument is empty, keep the order (a, b) } else if b < a { // If they're not empty and b is lexicographically prior to a, swap them (b, a) } else { // You can't generate values between two matching strings. ensure! { a!= b, MatchingStrings(a.to_string()) } // In any other case, keep the order (a, b) }; // TODO: Check for lexicographical adjacency! //ensure! {!lex_adjacent(a, b), LexAdjacentStrings(a.to_string(), b.to_string()) } // Count the characters start and end have in common. let matching_count: usize = { // Iterate through the chars of both given inputs... let (mut start_chars, mut end_chars) = (a.chars(), b.chars()); // We need to keep track of this, because: // In the case of `a` == `"a"` and `b` == `"aab"`, // we actually need to compare `""` to `"b"` later on, not `""` to `"a"`. let mut last_start_char = '\0'; // Counting to get the index. let mut i: usize = 0; loop { // Advance the iterators... match (start_chars.next(), end_chars.next()) { // As long as there's two characters that match, increment i. (Some(sc), Some(ec)) if sc == ec => { last_start_char = sc; i += 1; continue; } // If start_chars have run out, but end_chars haven't, check // if the current end char matches the last start char. // If it does, we still need to increment our counter. (None, Some(ec)) if ec == last_start_char => { i += 1; continue; } // break with i as soon as any mismatch happens or both iterators run out. // matching_count will either be 0, indicating that there's // no leading common pattern, or something other than 0, in // that case it's the count of common characters. (None, None) | (Some(_), None) | (None, Some(_)) | (Some(_), Some(_)) => { break i } } } }; // Count the number to add to the total requests amount. // If a or b is empty, we need one item less in the pool; // two items less if both are empty. let non_empty_input_count = [a, b].iter().filter(|s|!s.is_empty()).count(); // For convenience let computed_amount = || amount.get() + non_empty_input_count; // Calculate the distance between the first non-matching characters. // If matching_count is greater than 0, we have leading common chars, // so we skip those, but add the amount to the depth base. let branching_factor = self.distance_between_first_chars( // v--- matching_count might be higher than a.len() // vvv because we might count past a's end &a[std::cmp::min(matching_count, a.len())..], &b[matching_count..], )?; // We also add matching_count to the depth because if we're starting // with a common prefix, we have at least x leading characters that // will be the same for all substrings. let mut depth = depth_for(dbg!(branching_factor), dbg!(computed_amount())) + dbg!(matching_count); // if branching_factor == 1 { // // This should only be the case when we have an input like `"z", ""`. // // In this case, we can generate strings after the z, but we need // // to go one level deeper in any case. // depth += 1; // } // TODO: Maybe keeping this as an iterator would be more efficient, // but it would have to be cloned at least once to get the pool length. let pool: Vec<String> = self.traverse("".into(), a, b, dbg!(depth)).collect(); let pool = if (pool.len() as isize).saturating_sub(non_empty_input_count as isize) < amount.get() as isize { depth += depth_for(branching_factor, computed_amount() + pool.len()); dbg!(self.traverse("".into(), a, b, dbg!(depth)).collect()) } else { pool }; if (pool.len() as isize).saturating_sub(non_empty_input_count as isize) < amount.get() as isize { // We still don't have enough items, so bail panic!( "Internal error: Failed to calculate the correct tree depth! This is a bug. Please report it at: https://github.com/Follpvosten/mudders/issues and make sure to include the following information: Symbols in table: {symbols:?} Given inputs: {a:?}, {b:?}, amount: {amount} matching_count: {m_count} non_empty_input_count: {ne_input_count} required pool length (computed amount): {comp_amount} branching_factor: {b_factor} final depth: {depth} pool: {pool:?} (length: {pool_len})", symbols = self.0.iter().map(|i| *i as char).collect::<Box<[_]>>(), a = a, b = b, amount = amount, m_count = matching_count, ne_input_count = non_empty_input_count, comp_amount = computed_amount(), b_factor = branching_factor, depth = depth, pool = pool, pool_len = pool.len(), ) } Ok(if amount.get() == 1 { pool.get(pool.len() / 2) .map(|item| vec![item.clone()]) .ok_or_else(|| FailedToGetMiddle)? } else { let step = computed_amount() as f64 / pool.len() as f64; let mut counter = 0f64; let mut last_value = 0; let result: Vec<_> = pool .into_iter() .filter(|_| { counter += step; let new_value = counter.floor() as usize; if new_value > last_value { last_value = new_value; true } else { false } }) .take(amount.into()) .collect(); ensure! { result.len() == amount.get(), NotEnoughItemsInPool }; result }) } /// Convenience wrapper around `mudder` to generate exactly one string. /// /// # Safety /// This function calls `NonZeroUsize::new_unchecked(1)`. pub fn mudder_one(&self, a: &str, b: &str) -> Result<String, GenerationError> { self.mudder(a, b, unsafe { NonZeroUsize::new_unchecked(1) }) .map(|mut vec| vec.remove(0)) } /// Convenience wrapper around `mudder` to generate an amount of fresh strings. /// /// `SymbolTable.generate(amount)` is equivalent to `SymbolTable.mudder("", "", amount)`. pub fn generate(&self, amount: NonZeroUsize) -> Result<Vec<String>, GenerationError> { self.mudder("", "", amount) } /// Traverses a virtual tree of strings to the given depth. fn traverse<'a>( &'a self, curr_key: String, start: &'a str, end: &'a str, depth: usize, ) -> Box<dyn Iterator<Item = String> + 'a> { if depth == 0 { // If we've reached depth 0, we don't go futher. Box::new(std::iter::empty()) } else { // Generate all possible mutations on the current depth Box::new( self.0 .iter() .filter_map(move |c| -> Option<Box<dyn Iterator<Item = String>>> { // TODO: Performance - this probably still isn't the best option. let key = { let the_char = *c as char; let mut string = String::with_capacity(curr_key.len() + the_char.len_utf8()); string.push_str(&curr_key); string.push(the_char); string }; // After the end key, we definitely do not continue. if key.as_str() > end &&!end.is_empty() { None } else if key.as_str() < start { // If we're prior to the start key... //...and the start key is a subkey of the current key... if start.starts_with(&key) { //...only traverse the subtree, ignoring the key itself. Some(Box::new(self.traverse(key, start, end, depth - 1))) } else { None } } else { // Traverse normally, returning both the parent and sub key, // in all other cases. if key.len() < 2 { let iter = std::iter::once(key.clone()); Some(if key == end { Box::new(iter) } else { Box::new(iter.chain(self.traverse(key, start, end, depth - 1))) }) } else { let first = key.chars().next().unwrap(); Some(if key.chars().all(|c| c == first) { // If our characters are all the same, // don't add key to the list, only the subtree. Box::new(self.traverse(key, start, end, depth - 1)) } else { Box::new(std::iter::once(key.clone()).chain(self.traverse( key, start, end, depth - 1, ))) }) } } }) .flatten(), ) } } fn distance_between_first_chars( &self, start: &str, end: &str, ) -> Result<usize, GenerationError> { use InternalError::WrongCharOrder; // check the first character of both strings... Ok(match (start.chars().next(), end.chars().next()) { // if both have a first char, compare them. (Some(start_char), Some(end_char)) => { ensure! { start_char < end_char, WrongCharOrder(start_char, end_char) } let distance = try_ascii_u8_from_char(end_char)? - try_ascii_u8_from_char(start_char)?; distance as usize + 1 } // if only the start has a first char, compare it to our last possible symbol. (Some(start_char), None) => { let end_u8 = self.0.last().unwrap(); // In this case, we allow the start and end char to be equal. // This is because you can generate something after the last char, // but not before the first char. // vv ensure! { start_char <= *end_u8 as char, WrongCharOrder(start_char, *end_u8 as char) } let distance = end_u8 - try_ascii_u8_from_char(start_char)?; if distance == 0 { 2 } else { distance as usize + 1 } } // if only the end has a first char, compare it to our first possible symbol. (None, Some(end_char)) => { let start_u8 = self.0.first().unwrap(); ensure! { *start_u8 <= end_char as u8, WrongCharOrder(*start_u8 as char, end_char) } let distance = try_ascii_u8_from_char(end_char)? - start_u8; if distance == 0 { 2 } else { distance as usize + 1 } } // if there's no characters given, the whole symboltable is our range. _ => self.0.len(), }) } fn contains_all_chars(&self, chars: impl AsRef<[u8]>) -> bool { chars.as_ref().iter().all(|c| self.0.contains(c)) } } /// Calculate the required depth for the given values. /// /// `branching_factor` is used as the logarithm base, `n_elements` as the /// value, and the result is rounded up and cast to usize. fn depth_for(branching_factor: usize, n_elements: usize) -> usize { f64::log(n_elements as f64, branching_factor as f64).ceil() as usize } fn try_ascii_u8_from_char(c: char) -> Result<u8, NonAsciiError> { u8::try_from(c as u32).map_err(NonAsciiError::from) } fn all_chars_ascii(chars: impl AsRef<[u8]>) -> bool { chars.as_ref().iter().all(|i| i.is_ascii()) } impl FromStr for SymbolTable { type Err = CreationError; fn from_str(s: &str) -> Result<Self, CreationError> { Self::from_chars(&s.chars().collect::<Box<[_]>>()) } } #[cfg(test)] mod tests { use super::*; use std::num::NonZeroUsize; /// Create and unwrap a NonZeroUsize from the given usize. fn n(n: usize) -> NonZeroUsize { NonZeroUsize::new(n).unwrap() } // Public API tests: #[test] #[allow(clippy::char_lit_as_u8)] fn valid_tables_work() { assert!(SymbolTable::new(&[1, 2, 3, 4, 5]).is_ok()); assert!(SymbolTable::new(&[125, 126, 127]).is_ok()); // Possible, but to be discouraged assert!(SymbolTable::new(&['a' as u8, 'f' as u8]).is_ok()); assert!(SymbolTable::from_chars(&['a', 'b', 'c']).is_ok()); assert!(SymbolTable::from_str("0123").is_ok()); } #[test] fn invalid_tables_error() { assert!(SymbolTable::from_str("🍅😂👶🏻").is_err()); assert!(SymbolTable::from_chars(&['🍌', '🍣', '⛈']).is_err()); assert!(SymbolTable::new(&[128, 129, 130]).is_err()); assert!(SymbolTable::new(&[]).is_err()); assert!(SymbolTable::from_chars(&[]).is_err()); assert!(SymbolTable::from_str("").is_err()); } #[test] fn unknown_chars_error() { use error::GenerationError::UnknownCharacters; // You cannot pass in strings with characters not in the SymbolTable: let table = SymbolTable::alphabet();
phabet()
identifier_name
session.rs
use crypto::digest::Digest; use crypto::sha1::Sha1; use crypto::hmac::Hmac; use crypto::mac::Mac; use eventual; use eventual::Future; use eventual::Async; use protobuf::{self, Message}; use rand::thread_rng; use rand::Rng; use std::io::{Read, Write, Cursor}; use std::result::Result; use std::sync::{Mutex, RwLock, Arc, mpsc}; use album_cover::AlbumCover; use apresolve::apresolve; use audio_key::{AudioKeyManager, AudioKey, AudioKeyError}; use audio_file::AudioFile; use authentication::Credentials; use cache::Cache; use connection::{self, PlainConnection, CipherConnection}; use diffie_hellman::DHLocalKeys; use mercury::{MercuryManager, MercuryRequest, MercuryResponse}; use metadata::{MetadataManager, MetadataRef, MetadataTrait}; use protocol; use stream::StreamManager; use util::{self, SpotifyId, FileId, ReadSeek}; use version; use stream; pub enum Bitrate { Bitrate96, Bitrate160, Bitrate320, } pub struct Config { pub application_key: Vec<u8>, pub user_agent: String, pub device_name: String, pub bitrate: Bitrate, } pub struct SessionData { country: String, canonical_username: String, } pub struct SessionInternal { config: Config, device_id: String, data: RwLock<SessionData>, cache: Box<Cache + Send + Sync>, mercury: Mutex<MercuryManager>, metadata: Mutex<MetadataManager>, stream: Mutex<StreamManager>, audio_key: Mutex<AudioKeyManager>, rx_connection: Mutex<Option<CipherConnection>>, tx_connection: Mutex<Option<CipherConnection>>,
pub struct Session(pub Arc<SessionInternal>); impl Session { pub fn new(config: Config, cache: Box<Cache + Send + Sync>) -> Session { let device_id = { let mut h = Sha1::new(); h.input_str(&config.device_name); h.result_str() }; Session(Arc::new(SessionInternal { config: config, device_id: device_id, data: RwLock::new(SessionData { country: String::new(), canonical_username: String::new(), }), rx_connection: Mutex::new(None), tx_connection: Mutex::new(None), cache: cache, mercury: Mutex::new(MercuryManager::new()), metadata: Mutex::new(MetadataManager::new()), stream: Mutex::new(StreamManager::new()), audio_key: Mutex::new(AudioKeyManager::new()), })) } fn connect(&self) -> CipherConnection { let local_keys = DHLocalKeys::random(&mut thread_rng()); let aps = apresolve().unwrap(); let ap = thread_rng().choose(&aps).expect("No APs found"); info!("Connecting to AP {}", ap); let mut connection = PlainConnection::connect(ap).unwrap(); let request = protobuf_init!(protocol::keyexchange::ClientHello::new(), { build_info => { product: protocol::keyexchange::Product::PRODUCT_LIBSPOTIFY_EMBEDDED, platform: protocol::keyexchange::Platform::PLATFORM_LINUX_X86, version: 0x10800000000, }, /* fingerprints_supported => [ protocol::keyexchange::Fingerprint::FINGERPRINT_GRAIN ], */ cryptosuites_supported => [ protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_SHANNON, //protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_RC4_SHA1_HMAC ], /* powschemes_supported => [ protocol::keyexchange::Powscheme::POW_HASH_CASH ], */ login_crypto_hello.diffie_hellman => { gc: local_keys.public_key(), server_keys_known: 1, }, client_nonce: util::rand_vec(&mut thread_rng(), 0x10), padding: vec![0x1e], feature_set => { autoupdate2: true, } }); let init_client_packet = connection.send_packet_prefix(&[0, 4], &request.write_to_bytes().unwrap()) .unwrap(); let init_server_packet = connection.recv_packet().unwrap(); let response: protocol::keyexchange::APResponseMessage = protobuf::parse_from_bytes(&init_server_packet[4..]).unwrap(); let remote_key = response.get_challenge() .get_login_crypto_challenge() .get_diffie_hellman() .get_gs(); let shared_secret = local_keys.shared_secret(remote_key); let (challenge, send_key, recv_key) = { let mut data = Vec::with_capacity(0x64); let mut mac = Hmac::new(Sha1::new(), &shared_secret); for i in 1..6 { mac.input(&init_client_packet); mac.input(&init_server_packet); mac.input(&[i]); data.write(&mac.result().code()).unwrap(); mac.reset(); } mac = Hmac::new(Sha1::new(), &data[..0x14]); mac.input(&init_client_packet); mac.input(&init_server_packet); (mac.result().code().to_vec(), data[0x14..0x34].to_vec(), data[0x34..0x54].to_vec()) }; let packet = protobuf_init!(protocol::keyexchange::ClientResponsePlaintext::new(), { login_crypto_response.diffie_hellman => { hmac: challenge }, pow_response => {}, crypto_response => {}, }); connection.send_packet(&packet.write_to_bytes().unwrap()).unwrap(); CipherConnection::new(connection.into_stream(), &send_key, &recv_key) } pub fn login(&self, credentials: Credentials) -> Result<Credentials, ()> { let packet = protobuf_init!(protocol::authentication::ClientResponseEncrypted::new(), { login_credentials => { username: credentials.username, typ: credentials.auth_type, auth_data: credentials.auth_data, }, system_info => { cpu_family: protocol::authentication::CpuFamily::CPU_UNKNOWN, os: protocol::authentication::Os::OS_UNKNOWN, system_information_string: "librespot".to_owned(), device_id: self.device_id().to_owned(), }, version_string: version::version_string(), appkey => { version: self.config().application_key[0] as u32, devkey: self.config().application_key[0x1..0x81].to_vec(), signature: self.config().application_key[0x81..0x141].to_vec(), useragent: self.config().user_agent.clone(), callback_hash: vec![0; 20], } }); let mut connection = self.connect(); connection.send_packet(0xab, &packet.write_to_bytes().unwrap()).unwrap(); let (cmd, data) = connection.recv_packet().unwrap(); match cmd { 0xac => { let welcome_data: protocol::authentication::APWelcome = protobuf::parse_from_bytes(&data).unwrap(); let username = welcome_data.get_canonical_username().to_owned(); self.0.data.write().unwrap().canonical_username = username.clone(); *self.0.rx_connection.lock().unwrap() = Some(connection.clone()); *self.0.tx_connection.lock().unwrap() = Some(connection); info!("Authenticated!"); let reusable_credentials = Credentials { username: username, auth_type: welcome_data.get_reusable_auth_credentials_type(), auth_data: welcome_data.get_reusable_auth_credentials().to_owned(), }; self.0.cache.put_credentials(&reusable_credentials); Ok(reusable_credentials) } 0xad => { let msg: protocol::keyexchange::APLoginFailed = protobuf::parse_from_bytes(&data).unwrap(); error!("Authentication failed, {:?}", msg); Err(()) } _ => { error!("Unexpected message {:x}", cmd); Err(()) } } } pub fn poll(&self) { let (cmd, data) = self.recv(); match cmd { 0x4 => self.send_packet(0x49, &data).unwrap(), 0x4a => (), 0x9 | 0xa => self.0.stream.lock().unwrap().handle(cmd, data, self), 0xd | 0xe => self.0.audio_key.lock().unwrap().handle(cmd, data, self), 0x1b => { self.0.data.write().unwrap().country = String::from_utf8(data).unwrap(); } 0xb2...0xb6 => self.0.mercury.lock().unwrap().handle(cmd, data, self), _ => (), } } pub fn recv(&self) -> (u8, Vec<u8>) { self.0.rx_connection.lock().unwrap().as_mut().unwrap().recv_packet().unwrap() } pub fn send_packet(&self, cmd: u8, data: &[u8]) -> connection::Result<()> { self.0.tx_connection.lock().unwrap().as_mut().unwrap().send_packet(cmd, data) } pub fn audio_key(&self, track: SpotifyId, file_id: FileId) -> Future<AudioKey, AudioKeyError> { self.0.cache .get_audio_key(track, file_id) .map(Future::of) .unwrap_or_else(|| { let self_ = self.clone(); self.0.audio_key.lock().unwrap() .request(self, track, file_id) .map(move |key| { self_.0.cache.put_audio_key(track, file_id, key); key }) }) } pub fn audio_file(&self, file_id: FileId) -> Box<ReadSeek> { self.0.cache .get_file(file_id) .unwrap_or_else(|| { let (audio_file, complete_rx) = AudioFile::new(self, file_id); let self_ = self.clone(); complete_rx.map(move |mut complete_file| { self_.0.cache.put_file(file_id, &mut complete_file) }).fire(); Box::new(audio_file.await().unwrap()) }) } pub fn album_cover(&self, file_id: FileId) -> eventual::Future<Vec<u8>, ()> { self.0.cache .get_file(file_id) .map(|mut f| { let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); Future::of(data) }) .unwrap_or_else(|| { let self_ = self.clone(); AlbumCover::get(file_id, self) .map(move |data| { self_.0.cache.put_file(file_id, &mut Cursor::new(&data)); data }) }) } pub fn stream(&self, handler: Box<stream::Handler>) { self.0.stream.lock().unwrap().create(handler, self) } pub fn metadata<T: MetadataTrait>(&self, id: SpotifyId) -> MetadataRef<T> { self.0.metadata.lock().unwrap().get(self, id) } pub fn mercury(&self, req: MercuryRequest) -> Future<MercuryResponse, ()> { self.0.mercury.lock().unwrap().request(self, req) } pub fn mercury_sub(&self, uri: String) -> mpsc::Receiver<MercuryResponse> { self.0.mercury.lock().unwrap().subscribe(self, uri) } pub fn cache(&self) -> &Cache { self.0.cache.as_ref() } pub fn config(&self) -> &Config { &self.0.config } pub fn username(&self) -> String { self.0.data.read().unwrap().canonical_username.clone() } pub fn country(&self) -> String { self.0.data.read().unwrap().country.clone() } pub fn device_id(&self) -> &str { &self.0.device_id } } pub trait PacketHandler { fn handle(&mut self, cmd: u8, data: Vec<u8>, session: &Session); }
} #[derive(Clone)]
random_line_split
session.rs
use crypto::digest::Digest; use crypto::sha1::Sha1; use crypto::hmac::Hmac; use crypto::mac::Mac; use eventual; use eventual::Future; use eventual::Async; use protobuf::{self, Message}; use rand::thread_rng; use rand::Rng; use std::io::{Read, Write, Cursor}; use std::result::Result; use std::sync::{Mutex, RwLock, Arc, mpsc}; use album_cover::AlbumCover; use apresolve::apresolve; use audio_key::{AudioKeyManager, AudioKey, AudioKeyError}; use audio_file::AudioFile; use authentication::Credentials; use cache::Cache; use connection::{self, PlainConnection, CipherConnection}; use diffie_hellman::DHLocalKeys; use mercury::{MercuryManager, MercuryRequest, MercuryResponse}; use metadata::{MetadataManager, MetadataRef, MetadataTrait}; use protocol; use stream::StreamManager; use util::{self, SpotifyId, FileId, ReadSeek}; use version; use stream; pub enum Bitrate { Bitrate96, Bitrate160, Bitrate320, } pub struct Config { pub application_key: Vec<u8>, pub user_agent: String, pub device_name: String, pub bitrate: Bitrate, } pub struct SessionData { country: String, canonical_username: String, } pub struct
{ config: Config, device_id: String, data: RwLock<SessionData>, cache: Box<Cache + Send + Sync>, mercury: Mutex<MercuryManager>, metadata: Mutex<MetadataManager>, stream: Mutex<StreamManager>, audio_key: Mutex<AudioKeyManager>, rx_connection: Mutex<Option<CipherConnection>>, tx_connection: Mutex<Option<CipherConnection>>, } #[derive(Clone)] pub struct Session(pub Arc<SessionInternal>); impl Session { pub fn new(config: Config, cache: Box<Cache + Send + Sync>) -> Session { let device_id = { let mut h = Sha1::new(); h.input_str(&config.device_name); h.result_str() }; Session(Arc::new(SessionInternal { config: config, device_id: device_id, data: RwLock::new(SessionData { country: String::new(), canonical_username: String::new(), }), rx_connection: Mutex::new(None), tx_connection: Mutex::new(None), cache: cache, mercury: Mutex::new(MercuryManager::new()), metadata: Mutex::new(MetadataManager::new()), stream: Mutex::new(StreamManager::new()), audio_key: Mutex::new(AudioKeyManager::new()), })) } fn connect(&self) -> CipherConnection { let local_keys = DHLocalKeys::random(&mut thread_rng()); let aps = apresolve().unwrap(); let ap = thread_rng().choose(&aps).expect("No APs found"); info!("Connecting to AP {}", ap); let mut connection = PlainConnection::connect(ap).unwrap(); let request = protobuf_init!(protocol::keyexchange::ClientHello::new(), { build_info => { product: protocol::keyexchange::Product::PRODUCT_LIBSPOTIFY_EMBEDDED, platform: protocol::keyexchange::Platform::PLATFORM_LINUX_X86, version: 0x10800000000, }, /* fingerprints_supported => [ protocol::keyexchange::Fingerprint::FINGERPRINT_GRAIN ], */ cryptosuites_supported => [ protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_SHANNON, //protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_RC4_SHA1_HMAC ], /* powschemes_supported => [ protocol::keyexchange::Powscheme::POW_HASH_CASH ], */ login_crypto_hello.diffie_hellman => { gc: local_keys.public_key(), server_keys_known: 1, }, client_nonce: util::rand_vec(&mut thread_rng(), 0x10), padding: vec![0x1e], feature_set => { autoupdate2: true, } }); let init_client_packet = connection.send_packet_prefix(&[0, 4], &request.write_to_bytes().unwrap()) .unwrap(); let init_server_packet = connection.recv_packet().unwrap(); let response: protocol::keyexchange::APResponseMessage = protobuf::parse_from_bytes(&init_server_packet[4..]).unwrap(); let remote_key = response.get_challenge() .get_login_crypto_challenge() .get_diffie_hellman() .get_gs(); let shared_secret = local_keys.shared_secret(remote_key); let (challenge, send_key, recv_key) = { let mut data = Vec::with_capacity(0x64); let mut mac = Hmac::new(Sha1::new(), &shared_secret); for i in 1..6 { mac.input(&init_client_packet); mac.input(&init_server_packet); mac.input(&[i]); data.write(&mac.result().code()).unwrap(); mac.reset(); } mac = Hmac::new(Sha1::new(), &data[..0x14]); mac.input(&init_client_packet); mac.input(&init_server_packet); (mac.result().code().to_vec(), data[0x14..0x34].to_vec(), data[0x34..0x54].to_vec()) }; let packet = protobuf_init!(protocol::keyexchange::ClientResponsePlaintext::new(), { login_crypto_response.diffie_hellman => { hmac: challenge }, pow_response => {}, crypto_response => {}, }); connection.send_packet(&packet.write_to_bytes().unwrap()).unwrap(); CipherConnection::new(connection.into_stream(), &send_key, &recv_key) } pub fn login(&self, credentials: Credentials) -> Result<Credentials, ()> { let packet = protobuf_init!(protocol::authentication::ClientResponseEncrypted::new(), { login_credentials => { username: credentials.username, typ: credentials.auth_type, auth_data: credentials.auth_data, }, system_info => { cpu_family: protocol::authentication::CpuFamily::CPU_UNKNOWN, os: protocol::authentication::Os::OS_UNKNOWN, system_information_string: "librespot".to_owned(), device_id: self.device_id().to_owned(), }, version_string: version::version_string(), appkey => { version: self.config().application_key[0] as u32, devkey: self.config().application_key[0x1..0x81].to_vec(), signature: self.config().application_key[0x81..0x141].to_vec(), useragent: self.config().user_agent.clone(), callback_hash: vec![0; 20], } }); let mut connection = self.connect(); connection.send_packet(0xab, &packet.write_to_bytes().unwrap()).unwrap(); let (cmd, data) = connection.recv_packet().unwrap(); match cmd { 0xac => { let welcome_data: protocol::authentication::APWelcome = protobuf::parse_from_bytes(&data).unwrap(); let username = welcome_data.get_canonical_username().to_owned(); self.0.data.write().unwrap().canonical_username = username.clone(); *self.0.rx_connection.lock().unwrap() = Some(connection.clone()); *self.0.tx_connection.lock().unwrap() = Some(connection); info!("Authenticated!"); let reusable_credentials = Credentials { username: username, auth_type: welcome_data.get_reusable_auth_credentials_type(), auth_data: welcome_data.get_reusable_auth_credentials().to_owned(), }; self.0.cache.put_credentials(&reusable_credentials); Ok(reusable_credentials) } 0xad => { let msg: protocol::keyexchange::APLoginFailed = protobuf::parse_from_bytes(&data).unwrap(); error!("Authentication failed, {:?}", msg); Err(()) } _ => { error!("Unexpected message {:x}", cmd); Err(()) } } } pub fn poll(&self) { let (cmd, data) = self.recv(); match cmd { 0x4 => self.send_packet(0x49, &data).unwrap(), 0x4a => (), 0x9 | 0xa => self.0.stream.lock().unwrap().handle(cmd, data, self), 0xd | 0xe => self.0.audio_key.lock().unwrap().handle(cmd, data, self), 0x1b => { self.0.data.write().unwrap().country = String::from_utf8(data).unwrap(); } 0xb2...0xb6 => self.0.mercury.lock().unwrap().handle(cmd, data, self), _ => (), } } pub fn recv(&self) -> (u8, Vec<u8>) { self.0.rx_connection.lock().unwrap().as_mut().unwrap().recv_packet().unwrap() } pub fn send_packet(&self, cmd: u8, data: &[u8]) -> connection::Result<()> { self.0.tx_connection.lock().unwrap().as_mut().unwrap().send_packet(cmd, data) } pub fn audio_key(&self, track: SpotifyId, file_id: FileId) -> Future<AudioKey, AudioKeyError> { self.0.cache .get_audio_key(track, file_id) .map(Future::of) .unwrap_or_else(|| { let self_ = self.clone(); self.0.audio_key.lock().unwrap() .request(self, track, file_id) .map(move |key| { self_.0.cache.put_audio_key(track, file_id, key); key }) }) } pub fn audio_file(&self, file_id: FileId) -> Box<ReadSeek> { self.0.cache .get_file(file_id) .unwrap_or_else(|| { let (audio_file, complete_rx) = AudioFile::new(self, file_id); let self_ = self.clone(); complete_rx.map(move |mut complete_file| { self_.0.cache.put_file(file_id, &mut complete_file) }).fire(); Box::new(audio_file.await().unwrap()) }) } pub fn album_cover(&self, file_id: FileId) -> eventual::Future<Vec<u8>, ()> { self.0.cache .get_file(file_id) .map(|mut f| { let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); Future::of(data) }) .unwrap_or_else(|| { let self_ = self.clone(); AlbumCover::get(file_id, self) .map(move |data| { self_.0.cache.put_file(file_id, &mut Cursor::new(&data)); data }) }) } pub fn stream(&self, handler: Box<stream::Handler>) { self.0.stream.lock().unwrap().create(handler, self) } pub fn metadata<T: MetadataTrait>(&self, id: SpotifyId) -> MetadataRef<T> { self.0.metadata.lock().unwrap().get(self, id) } pub fn mercury(&self, req: MercuryRequest) -> Future<MercuryResponse, ()> { self.0.mercury.lock().unwrap().request(self, req) } pub fn mercury_sub(&self, uri: String) -> mpsc::Receiver<MercuryResponse> { self.0.mercury.lock().unwrap().subscribe(self, uri) } pub fn cache(&self) -> &Cache { self.0.cache.as_ref() } pub fn config(&self) -> &Config { &self.0.config } pub fn username(&self) -> String { self.0.data.read().unwrap().canonical_username.clone() } pub fn country(&self) -> String { self.0.data.read().unwrap().country.clone() } pub fn device_id(&self) -> &str { &self.0.device_id } } pub trait PacketHandler { fn handle(&mut self, cmd: u8, data: Vec<u8>, session: &Session); }
SessionInternal
identifier_name
session.rs
use crypto::digest::Digest; use crypto::sha1::Sha1; use crypto::hmac::Hmac; use crypto::mac::Mac; use eventual; use eventual::Future; use eventual::Async; use protobuf::{self, Message}; use rand::thread_rng; use rand::Rng; use std::io::{Read, Write, Cursor}; use std::result::Result; use std::sync::{Mutex, RwLock, Arc, mpsc}; use album_cover::AlbumCover; use apresolve::apresolve; use audio_key::{AudioKeyManager, AudioKey, AudioKeyError}; use audio_file::AudioFile; use authentication::Credentials; use cache::Cache; use connection::{self, PlainConnection, CipherConnection}; use diffie_hellman::DHLocalKeys; use mercury::{MercuryManager, MercuryRequest, MercuryResponse}; use metadata::{MetadataManager, MetadataRef, MetadataTrait}; use protocol; use stream::StreamManager; use util::{self, SpotifyId, FileId, ReadSeek}; use version; use stream; pub enum Bitrate { Bitrate96, Bitrate160, Bitrate320, } pub struct Config { pub application_key: Vec<u8>, pub user_agent: String, pub device_name: String, pub bitrate: Bitrate, } pub struct SessionData { country: String, canonical_username: String, } pub struct SessionInternal { config: Config, device_id: String, data: RwLock<SessionData>, cache: Box<Cache + Send + Sync>, mercury: Mutex<MercuryManager>, metadata: Mutex<MetadataManager>, stream: Mutex<StreamManager>, audio_key: Mutex<AudioKeyManager>, rx_connection: Mutex<Option<CipherConnection>>, tx_connection: Mutex<Option<CipherConnection>>, } #[derive(Clone)] pub struct Session(pub Arc<SessionInternal>); impl Session { pub fn new(config: Config, cache: Box<Cache + Send + Sync>) -> Session { let device_id = { let mut h = Sha1::new(); h.input_str(&config.device_name); h.result_str() }; Session(Arc::new(SessionInternal { config: config, device_id: device_id, data: RwLock::new(SessionData { country: String::new(), canonical_username: String::new(), }), rx_connection: Mutex::new(None), tx_connection: Mutex::new(None), cache: cache, mercury: Mutex::new(MercuryManager::new()), metadata: Mutex::new(MetadataManager::new()), stream: Mutex::new(StreamManager::new()), audio_key: Mutex::new(AudioKeyManager::new()), })) } fn connect(&self) -> CipherConnection { let local_keys = DHLocalKeys::random(&mut thread_rng()); let aps = apresolve().unwrap(); let ap = thread_rng().choose(&aps).expect("No APs found"); info!("Connecting to AP {}", ap); let mut connection = PlainConnection::connect(ap).unwrap(); let request = protobuf_init!(protocol::keyexchange::ClientHello::new(), { build_info => { product: protocol::keyexchange::Product::PRODUCT_LIBSPOTIFY_EMBEDDED, platform: protocol::keyexchange::Platform::PLATFORM_LINUX_X86, version: 0x10800000000, }, /* fingerprints_supported => [ protocol::keyexchange::Fingerprint::FINGERPRINT_GRAIN ], */ cryptosuites_supported => [ protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_SHANNON, //protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_RC4_SHA1_HMAC ], /* powschemes_supported => [ protocol::keyexchange::Powscheme::POW_HASH_CASH ], */ login_crypto_hello.diffie_hellman => { gc: local_keys.public_key(), server_keys_known: 1, }, client_nonce: util::rand_vec(&mut thread_rng(), 0x10), padding: vec![0x1e], feature_set => { autoupdate2: true, } }); let init_client_packet = connection.send_packet_prefix(&[0, 4], &request.write_to_bytes().unwrap()) .unwrap(); let init_server_packet = connection.recv_packet().unwrap(); let response: protocol::keyexchange::APResponseMessage = protobuf::parse_from_bytes(&init_server_packet[4..]).unwrap(); let remote_key = response.get_challenge() .get_login_crypto_challenge() .get_diffie_hellman() .get_gs(); let shared_secret = local_keys.shared_secret(remote_key); let (challenge, send_key, recv_key) = { let mut data = Vec::with_capacity(0x64); let mut mac = Hmac::new(Sha1::new(), &shared_secret); for i in 1..6 { mac.input(&init_client_packet); mac.input(&init_server_packet); mac.input(&[i]); data.write(&mac.result().code()).unwrap(); mac.reset(); } mac = Hmac::new(Sha1::new(), &data[..0x14]); mac.input(&init_client_packet); mac.input(&init_server_packet); (mac.result().code().to_vec(), data[0x14..0x34].to_vec(), data[0x34..0x54].to_vec()) }; let packet = protobuf_init!(protocol::keyexchange::ClientResponsePlaintext::new(), { login_crypto_response.diffie_hellman => { hmac: challenge }, pow_response => {}, crypto_response => {}, }); connection.send_packet(&packet.write_to_bytes().unwrap()).unwrap(); CipherConnection::new(connection.into_stream(), &send_key, &recv_key) } pub fn login(&self, credentials: Credentials) -> Result<Credentials, ()> { let packet = protobuf_init!(protocol::authentication::ClientResponseEncrypted::new(), { login_credentials => { username: credentials.username, typ: credentials.auth_type, auth_data: credentials.auth_data, }, system_info => { cpu_family: protocol::authentication::CpuFamily::CPU_UNKNOWN, os: protocol::authentication::Os::OS_UNKNOWN, system_information_string: "librespot".to_owned(), device_id: self.device_id().to_owned(), }, version_string: version::version_string(), appkey => { version: self.config().application_key[0] as u32, devkey: self.config().application_key[0x1..0x81].to_vec(), signature: self.config().application_key[0x81..0x141].to_vec(), useragent: self.config().user_agent.clone(), callback_hash: vec![0; 20], } }); let mut connection = self.connect(); connection.send_packet(0xab, &packet.write_to_bytes().unwrap()).unwrap(); let (cmd, data) = connection.recv_packet().unwrap(); match cmd { 0xac => { let welcome_data: protocol::authentication::APWelcome = protobuf::parse_from_bytes(&data).unwrap(); let username = welcome_data.get_canonical_username().to_owned(); self.0.data.write().unwrap().canonical_username = username.clone(); *self.0.rx_connection.lock().unwrap() = Some(connection.clone()); *self.0.tx_connection.lock().unwrap() = Some(connection); info!("Authenticated!"); let reusable_credentials = Credentials { username: username, auth_type: welcome_data.get_reusable_auth_credentials_type(), auth_data: welcome_data.get_reusable_auth_credentials().to_owned(), }; self.0.cache.put_credentials(&reusable_credentials); Ok(reusable_credentials) } 0xad => { let msg: protocol::keyexchange::APLoginFailed = protobuf::parse_from_bytes(&data).unwrap(); error!("Authentication failed, {:?}", msg); Err(()) } _ => { error!("Unexpected message {:x}", cmd); Err(()) } } } pub fn poll(&self) { let (cmd, data) = self.recv(); match cmd { 0x4 => self.send_packet(0x49, &data).unwrap(), 0x4a => (), 0x9 | 0xa => self.0.stream.lock().unwrap().handle(cmd, data, self), 0xd | 0xe => self.0.audio_key.lock().unwrap().handle(cmd, data, self), 0x1b => { self.0.data.write().unwrap().country = String::from_utf8(data).unwrap(); } 0xb2...0xb6 => self.0.mercury.lock().unwrap().handle(cmd, data, self), _ => (), } } pub fn recv(&self) -> (u8, Vec<u8>) { self.0.rx_connection.lock().unwrap().as_mut().unwrap().recv_packet().unwrap() } pub fn send_packet(&self, cmd: u8, data: &[u8]) -> connection::Result<()> { self.0.tx_connection.lock().unwrap().as_mut().unwrap().send_packet(cmd, data) } pub fn audio_key(&self, track: SpotifyId, file_id: FileId) -> Future<AudioKey, AudioKeyError> { self.0.cache .get_audio_key(track, file_id) .map(Future::of) .unwrap_or_else(|| { let self_ = self.clone(); self.0.audio_key.lock().unwrap() .request(self, track, file_id) .map(move |key| { self_.0.cache.put_audio_key(track, file_id, key); key }) }) } pub fn audio_file(&self, file_id: FileId) -> Box<ReadSeek> { self.0.cache .get_file(file_id) .unwrap_or_else(|| { let (audio_file, complete_rx) = AudioFile::new(self, file_id); let self_ = self.clone(); complete_rx.map(move |mut complete_file| { self_.0.cache.put_file(file_id, &mut complete_file) }).fire(); Box::new(audio_file.await().unwrap()) }) } pub fn album_cover(&self, file_id: FileId) -> eventual::Future<Vec<u8>, ()> { self.0.cache .get_file(file_id) .map(|mut f| { let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); Future::of(data) }) .unwrap_or_else(|| { let self_ = self.clone(); AlbumCover::get(file_id, self) .map(move |data| { self_.0.cache.put_file(file_id, &mut Cursor::new(&data)); data }) }) } pub fn stream(&self, handler: Box<stream::Handler>) { self.0.stream.lock().unwrap().create(handler, self) } pub fn metadata<T: MetadataTrait>(&self, id: SpotifyId) -> MetadataRef<T> { self.0.metadata.lock().unwrap().get(self, id) } pub fn mercury(&self, req: MercuryRequest) -> Future<MercuryResponse, ()> { self.0.mercury.lock().unwrap().request(self, req) } pub fn mercury_sub(&self, uri: String) -> mpsc::Receiver<MercuryResponse>
pub fn cache(&self) -> &Cache { self.0.cache.as_ref() } pub fn config(&self) -> &Config { &self.0.config } pub fn username(&self) -> String { self.0.data.read().unwrap().canonical_username.clone() } pub fn country(&self) -> String { self.0.data.read().unwrap().country.clone() } pub fn device_id(&self) -> &str { &self.0.device_id } } pub trait PacketHandler { fn handle(&mut self, cmd: u8, data: Vec<u8>, session: &Session); }
{ self.0.mercury.lock().unwrap().subscribe(self, uri) }
identifier_body
option.rs
//! Enumeration of RS2 sensor options. //! //! Not all options apply to every sensor. In order to retrieve the correct options, //! one must iterate over the `sensor` object for option compatibility. //! //! Notice that this option refers to the `sensor`, not the device. However, the device //! used also matters; sensors that are alike across devices are not guaranteed to share //! the same sensor options. Again, it is up to the user to query whether an option //! is supported by the sensor before attempting to set it. Failure to do so may cause //! an error in operation. use super::Rs2Exception; use num_derive::{FromPrimitive, ToPrimitive}; use realsense_sys as sys; use std::ffi::CStr; use thiserror::Error; /// Occur when an option cannot be set. #[derive(Error, Debug)] pub enum OptionSetError { /// The requested option is not supported by this sensor. #[error("Option not supported on this sensor.")] OptionNotSupported, /// The requested option is read-only and cannot be set. #[error("Option is read only.")] OptionIsReadOnly, /// The requested option could not be set. Reason is reported by the sensor. #[error("Could not set option. Type: {0}; Reason: {1}")] CouldNotSetOption(Rs2Exception, String), } /// The enumeration of options available in the RealSense SDK. /// /// The majority of the options presented have a specific range of valid values. Run /// `sensor.get_option_range(Rs2Option::_)` to retrieve possible values of an Option type for your sensor. /// Setting a bad value will lead to a no-op at best, and a malfunction at worst. /// /// # Deprecated Options /// /// `AmbientLight` /// /// - Equivalent to `RS2_OPTION_AMBIENT_LIGHT` /// - Replacement: [Rs2Option::DigitalGain]. /// - Old Description: "Change the depth ambient light see rs2_ambient_light for values". /// /// `ZeroOrderEnabled` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_ENABLED` /// - Replacement: N/A. /// - Old Description: "Toggle Zero-Order mode." /// /// `ZeroOrderPointX` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_POINT_X` /// - Replacement: N/A. /// - Old Description: "Get the Zero order point x." /// /// `ZeroOrderPointY` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_POINT_Y` /// - Replacement: N/A. /// - Old Description: "Get the Zero order point y." /// /// `Trigger camera accuracy health` /// /// - Deprecated as of 2.46 (not officially released, so technically 2.47) /// - Old Description: "Enable Depth & color frame sync with periodic calibration for proper /// alignment" /// /// `Reset camera accuracy health` /// /// - Deprecated as of 2.46 (not officially released, so technically 2.47) /// - Old Description: "Reset Camera Accuracy metric (if affected by TriggerCameraAccuracyHealth /// option)." #[repr(i32)] #[derive(FromPrimitive, ToPrimitive, Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Rs2Option { /// Enable/disable color backlight compensation. BacklightCompensation = sys::rs2_option_RS2_OPTION_BACKLIGHT_COMPENSATION as i32, /// Set color image brightness. Brightness = sys::rs2_option_RS2_OPTION_BRIGHTNESS as i32, /// Set color image contrast. Contrast = sys::rs2_option_RS2_OPTION_CONTRAST as i32, /// Set exposure time of color camera. Setting any value will disable auto exposure. Exposure = sys::rs2_option_RS2_OPTION_EXPOSURE as i32, /// Set color image gain. Gain = sys::rs2_option_RS2_OPTION_GAIN as i32, /// Set color image gamma setting. Gamma = sys::rs2_option_RS2_OPTION_GAMMA as i32, /// Set color image hue. Hue = sys::rs2_option_RS2_OPTION_HUE as i32, /// Set color image saturation. Saturation = sys::rs2_option_RS2_OPTION_SATURATION as i32, /// Set color image sharpness. Sharpness = sys::rs2_option_RS2_OPTION_SHARPNESS as i32, /// Set white balance of color image. Setting any value will disable auto white balance. WhiteBalance = sys::rs2_option_RS2_OPTION_WHITE_BALANCE as i32, /// Enable/disable color image auto-exposure. EnableAutoExposure = sys::rs2_option_RS2_OPTION_ENABLE_AUTO_EXPOSURE as i32, /// Enable/disable color image auto-white-balance EnableAutoWhiteBalance = sys::rs2_option_RS2_OPTION_ENABLE_AUTO_WHITE_BALANCE as i32, /// Set the visual preset on the sensor. `sensor.get_option_range()` provides /// access to several recommend sets of option presets for a depth camera. The preset /// selection varies between devices and sensors. VisualPreset = sys::rs2_option_RS2_OPTION_VISUAL_PRESET as i32, /// Set the power of the laser emitter, with 0 meaning projector off. LaserPower = sys::rs2_option_RS2_OPTION_LASER_POWER as i32, /// Set the number of patterns projected per frame. The higher the accuracy value, /// the more patterns projected. Increasing the number of patterns helps to achieve /// better accuracy. Note that this control affects Depth FPS. Accuracy = sys::rs2_option_RS2_OPTION_ACCURACY as i32, /// Set the motion vs. range trade-off. Lower values allow for better motion sensitivity. /// Higher values allow for better depth range. MotionRange = sys::rs2_option_RS2_OPTION_MOTION_RANGE as i32, /// Set the filter to apply to each depth frame. Each one of the filter is optimized per the /// application requirements. FilterOption = sys::rs2_option_RS2_OPTION_FILTER_OPTION as i32, /// Set the confidence level threshold used by the Depth algorithm pipe. /// This determines whether a pixel will get a valid range or will be marked as invalid. ConfidenceThreshold = sys::rs2_option_RS2_OPTION_CONFIDENCE_THRESHOLD as i32, /// Enable/disable emitters. Emitter selection: /// /// - `0`: disable all emitters /// - `1`: enable laser /// - `2`: enable auto laser /// - `3`: enable LED EmitterEnabled = sys::rs2_option_RS2_OPTION_EMITTER_ENABLED as i32, /// Set the number of frames the user is allowed to keep per stream. /// Trying to hold on to more frames will cause frame drops. FramesQueueSize = sys::rs2_option_RS2_OPTION_FRAMES_QUEUE_SIZE as i32, /// Get the total number of detected frame drops from all streams. TotalFrameDrops = sys::rs2_option_RS2_OPTION_TOTAL_FRAME_DROPS as i32, /// Set the auto-exposure mode: /// /// - Static /// - Anti-Flicker /// - Hybrid AutoExposureMode = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_MODE as i32, /// Set the power line frequency control for anti-flickering: /// /// - Off /// - 50Hz /// - 60Hz /// - Auto PowerLineFrequency = sys::rs2_option_RS2_OPTION_POWER_LINE_FREQUENCY as i32, /// Get the current Temperature of the ASIC. AsicTemperature = sys::rs2_option_RS2_OPTION_ASIC_TEMPERATURE as i32, /// Enable/disable error handling. ErrorPollingEnabled = sys::rs2_option_RS2_OPTION_ERROR_POLLING_ENABLED as i32, /// Get the Current Temperature of the projector. ProjectorTemperature = sys::rs2_option_RS2_OPTION_PROJECTOR_TEMPERATURE as i32, /// Enable/disable trigger to be outputed from the camera to any external device on /// every depth frame. OutputTriggerEnabled = sys::rs2_option_RS2_OPTION_OUTPUT_TRIGGER_ENABLED as i32, /// Get the current Motion-Module Temperature. MotionModuleTemperature = sys::rs2_option_RS2_OPTION_MOTION_MODULE_TEMPERATURE as i32, /// Set the number of meters represented by a single depth unit. DepthUnits = sys::rs2_option_RS2_OPTION_DEPTH_UNITS as i32, /// Enable/Disable automatic correction of the motion data. EnableMotionCorrection = sys::rs2_option_RS2_OPTION_ENABLE_MOTION_CORRECTION as i32, /// Allows sensor to dynamically ajust the frame rate depending on lighting conditions. AutoExposurePriority = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_PRIORITY as i32, /// Set the color scheme for data visualization. ColorScheme = sys::rs2_option_RS2_OPTION_COLOR_SCHEME as i32, /// Enable/disable histogram equalization post-processing on the depth data. HistogramEqualizationEnabled = sys::rs2_option_RS2_OPTION_HISTOGRAM_EQUALIZATION_ENABLED as i32, /// Set the Minimal distance to the target. MinDistance = sys::rs2_option_RS2_OPTION_MIN_DISTANCE as i32, /// Set the Maximum distance to the target. MaxDistance = sys::rs2_option_RS2_OPTION_MAX_DISTANCE as i32, /// Get the texture mapping stream unique ID. TextureSource = sys::rs2_option_RS2_OPTION_TEXTURE_SOURCE as i32, /// Set the 2D-filter effect. The specific interpretation is given within the context of the filter. FilterMagnitude = sys::rs2_option_RS2_OPTION_FILTER_MAGNITUDE as i32, /// Set the 2D-filter parameter that controls the weight/radius for smoothing. FilterSmoothAlpha = sys::rs2_option_RS2_OPTION_FILTER_SMOOTH_ALPHA as i32, /// Set the 2D-filter range/validity threshold. FilterSmoothDelta = sys::rs2_option_RS2_OPTION_FILTER_SMOOTH_DELTA as i32, /// Enhance depth data post-processing with holes filling where appropriate. HolesFill = sys::rs2_option_RS2_OPTION_HOLES_FILL as i32, /// Get the distance in mm between the first and the second imagers in stereo-based depth cameras. StereoBaseline = sys::rs2_option_RS2_OPTION_STEREO_BASELINE as i32, /// Allows dynamically ajust the converge step value of the target exposure in /// the Auto-Exposure algorithm. AutoExposureConvergeStep = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_CONVERGE_STEP as i32, /// Impose Inter-camera HW synchronization mode. Applicable for D400/L500/Rolling Shutter SKUs. InterCamSyncMode = sys::rs2_option_RS2_OPTION_INTER_CAM_SYNC_MODE as i32, /// Select a stream to process. StreamFilter = sys::rs2_option_RS2_OPTION_STREAM_FILTER as i32, /// Select a stream format to process. StreamFormatFilter = sys::rs2_option_RS2_OPTION_STREAM_FORMAT_FILTER as i32, /// Select a stream index to process. StreamIndexFilter = sys::rs2_option_RS2_OPTION_STREAM_INDEX_FILTER as i32, /// When supported, this option make the camera to switch the emitter state every frame. /// 0 for disabled, 1 for enabled. EmitterOnOff = sys::rs2_option_RS2_OPTION_EMITTER_ON_OFF as i32, /// Get the LDD temperature. LldTemperature = sys::rs2_option_RS2_OPTION_LLD_TEMPERATURE as i32, /// Get the MC temperature. McTemperature = sys::rs2_option_RS2_OPTION_MC_TEMPERATURE as i32, /// Get the MA temperature. MaTemperature = sys::rs2_option_RS2_OPTION_MA_TEMPERATURE as i32, /// Hardware stream configuration. HardwarePreset = sys::rs2_option_RS2_OPTION_HARDWARE_PRESET as i32, /// Enable/disable global time. GlobalTimeEnabled = sys::rs2_option_RS2_OPTION_GLOBAL_TIME_ENABLED as i32, /// Get the APD temperature. ApdTemperature = sys::rs2_option_RS2_OPTION_APD_TEMPERATURE as i32, /// Enable/disable an internal map. EnableMapping = sys::rs2_option_RS2_OPTION_ENABLE_MAPPING as i32, /// Enable/disable appearance-based relocalization. EnableRelocalization = sys::rs2_option_RS2_OPTION_ENABLE_RELOCALIZATION as i32, /// Enable/disable position jumping. EnablePoseJumping = sys::rs2_option_RS2_OPTION_ENABLE_POSE_JUMPING as i32, /// Enable/disable dynamic calibration. EnableDynamicCalibration = sys::rs2_option_RS2_OPTION_ENABLE_DYNAMIC_CALIBRATION as i32, /// Get the offset from sensor to depth origin in millimeters. DepthOffset = sys::rs2_option_RS2_OPTION_DEPTH_OFFSET as i32, /// Set the power of the LED (light emitting diode), with 0 meaning off LedPower = sys::rs2_option_RS2_OPTION_LED_POWER as i32, /// Preserve the previous map when starting. EnableMapPreservation = sys::rs2_option_RS2_OPTION_ENABLE_MAP_PRESERVATION as i32, /// Enable/disable sensor shutdown when a free-fall is detected (on by default). FreefallDetectionEnabled = sys::rs2_option_RS2_OPTION_FREEFALL_DETECTION_ENABLED as i32, /// Changes the exposure time of Avalanche Photo Diode in the receiver. AvalanchePhotoDiode = sys::rs2_option_RS2_OPTION_AVALANCHE_PHOTO_DIODE as i32, /// Changes the amount of sharpening in the post-processed image. PostProcessingSharpening = sys::rs2_option_RS2_OPTION_POST_PROCESSING_SHARPENING as i32, /// Changes the amount of sharpening in the pre-processed image. PreProcessingSharpening = sys::rs2_option_RS2_OPTION_PRE_PROCESSING_SHARPENING as i32, /// Control edges and background noise. NoiseFiltering = sys::rs2_option_RS2_OPTION_NOISE_FILTERING as i32, /// Enable/disable pixel invalidation. InvalidationBypass = sys::rs2_option_RS2_OPTION_INVALIDATION_BYPASS as i32, /// Change the depth digital gain see rs2_digital_gain for values. DigitalGain = sys::rs2_option_RS2_OPTION_DIGITAL_GAIN as i32, /// The resolution mode: see rs2_sensor_mode for values. SensoeMode = sys::rs2_option_RS2_OPTION_SENSOR_MODE as i32, /// Enable/disable Laser On constantly (GS SKU Only). EmitterAlwaysOn = sys::rs2_option_RS2_OPTION_EMITTER_ALWAYS_ON as i32, /// Depth Thermal Compensation for selected D400 SKUs. ThermalCompensation = sys::rs2_option_RS2_OPTION_THERMAL_COMPENSATION as i32, /// Set host performance mode to optimize device settings so host can keep up with workload. /// Take USB transaction granularity as an example. Setting option to low performance host leads /// to larger USB transaction sizes and a reduced number of transactions. This improves performance /// and stability if the host machine is relatively weak compared to the workload. HostPerformance = sys::rs2_option_RS2_OPTION_HOST_PERFORMANCE as i32, /// Enable/disable HDR. HdrEnabled = sys::rs2_option_RS2_OPTION_HDR_ENABLED as i32, /// Get HDR Sequence name. SequenceName = sys::rs2_option_RS2_OPTION_SEQUENCE_NAME as i32, /// Get HDR Sequence size. SequenceSize = sys::rs2_option_RS2_OPTION_SEQUENCE_SIZE as i32, /// Get HDR Sequence ID - 0 is not HDR; sequence ID for HDR configuration starts from 1. SequenceId = sys::rs2_option_RS2_OPTION_SEQUENCE_ID as i32, /// Get Humidity temperature [in Celsius]. HumidityTemperature = sys::rs2_option_RS2_OPTION_HUMIDITY_TEMPERATURE as i32, /// Enable/disable the maximum usable depth sensor range given the amount of ambient light in the scene. EnableMaxUsableRange = sys::rs2_option_RS2_OPTION_ENABLE_MAX_USABLE_RANGE as i32, /// Enable/disable the alternate IR, When enabling alternate IR, the IR image is holding the amplitude of the depth correlation. AlternateIr = sys::rs2_option_RS2_OPTION_ALTERNATE_IR as i32, /// Get an estimation of the noise on the IR image. NoiseEstimation = sys::rs2_option_RS2_OPTION_NOISE_ESTIMATION as i32, /// Enable/disable data collection for calculating IR pixel reflectivity. EnableIrReflectivity = sys::rs2_option_RS2_OPTION_ENABLE_IR_REFLECTIVITY as i32, /// Auto exposure limit in microseconds. /// /// Default is 0 which means full exposure range. If the requested exposure limit is greater /// than frame time, it will be set to frame time at runtime. Setting will not take effect /// until next streaming session. AutoExposureLimit = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_LIMIT as i32, /// Auto gain limits ranging from 16 to 248. /// /// Default is 0 which means full gain. If the requested gain limit is less than 16, it will be /// set to 16. If the requested gain limit is greater than 248, it will be set to 248. Setting /// will not take effect until next streaming session. AutoGainLimit = sys::rs2_option_RS2_OPTION_AUTO_GAIN_LIMIT as i32, /// Enable receiver sensitivity according to ambient light, bounded by the Receiver GAin /// control. AutoReceiverSensitivity = sys::rs2_option_RS2_OPTION_AUTO_RX_SENSITIVITY as i32, /// Changes the transmistter frequency frequencies increasing effective range over sharpness. TransmitterFrequency = sys::rs2_option_RS2_OPTION_TRANSMITTER_FREQUENCY as i32, /* Not included since this just tells us the total number of options. * * Count = sys::rs2_option_RS2_OPTION_COUNT, */ } impl Rs2Option { /// Get the option as a CStr. pub fn to_cstr(self) -> &'static CStr { unsafe { let ptr = sys::rs2_option_to_string(self as sys::rs2_option); CStr::from_ptr(ptr) } } /// Get the option as a str. pub fn to_str(self) -> &'static str { self.to_cstr().to_str().unwrap() } } impl ToString for Rs2Option { fn to_string(&self) -> String { self.to_str().to_owned() } } /// The range of available values of a supported option. pub struct Rs2OptionRange { /// The minimum value which will be accepted for this option pub min: f32, /// The maximum value which will be accepted for this option pub max: f32, /// The granularity of options which accept discrete values, or zero if the option accepts /// continuous values pub step: f32, /// The default value of the option pub default: f32, } #[cfg(test)] mod tests { use super::*; use num_traits::FromPrimitive; #[test] fn all_variants_exist() { let deprecated_options = vec![ sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_X as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_Y as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_ENABLED as i32, sys::rs2_option_RS2_OPTION_AMBIENT_LIGHT as i32, sys::rs2_option_RS2_OPTION_TRIGGER_CAMERA_ACCURACY_HEALTH as i32, sys::rs2_option_RS2_OPTION_RESET_CAMERA_ACCURACY_HEALTH as i32, ]; for i in 0..sys::rs2_option_RS2_OPTION_COUNT as i32 { if deprecated_options.iter().any(|x| x == &i)
assert!( Rs2Option::from_i32(i).is_some(), "Rs2Option variant for ordinal {} does not exist.", i, ); } } }
{ continue; }
conditional_block
option.rs
//! Enumeration of RS2 sensor options. //! //! Not all options apply to every sensor. In order to retrieve the correct options, //! one must iterate over the `sensor` object for option compatibility. //! //! Notice that this option refers to the `sensor`, not the device. However, the device //! used also matters; sensors that are alike across devices are not guaranteed to share //! the same sensor options. Again, it is up to the user to query whether an option //! is supported by the sensor before attempting to set it. Failure to do so may cause //! an error in operation. use super::Rs2Exception; use num_derive::{FromPrimitive, ToPrimitive}; use realsense_sys as sys; use std::ffi::CStr; use thiserror::Error; /// Occur when an option cannot be set. #[derive(Error, Debug)] pub enum
{ /// The requested option is not supported by this sensor. #[error("Option not supported on this sensor.")] OptionNotSupported, /// The requested option is read-only and cannot be set. #[error("Option is read only.")] OptionIsReadOnly, /// The requested option could not be set. Reason is reported by the sensor. #[error("Could not set option. Type: {0}; Reason: {1}")] CouldNotSetOption(Rs2Exception, String), } /// The enumeration of options available in the RealSense SDK. /// /// The majority of the options presented have a specific range of valid values. Run /// `sensor.get_option_range(Rs2Option::_)` to retrieve possible values of an Option type for your sensor. /// Setting a bad value will lead to a no-op at best, and a malfunction at worst. /// /// # Deprecated Options /// /// `AmbientLight` /// /// - Equivalent to `RS2_OPTION_AMBIENT_LIGHT` /// - Replacement: [Rs2Option::DigitalGain]. /// - Old Description: "Change the depth ambient light see rs2_ambient_light for values". /// /// `ZeroOrderEnabled` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_ENABLED` /// - Replacement: N/A. /// - Old Description: "Toggle Zero-Order mode." /// /// `ZeroOrderPointX` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_POINT_X` /// - Replacement: N/A. /// - Old Description: "Get the Zero order point x." /// /// `ZeroOrderPointY` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_POINT_Y` /// - Replacement: N/A. /// - Old Description: "Get the Zero order point y." /// /// `Trigger camera accuracy health` /// /// - Deprecated as of 2.46 (not officially released, so technically 2.47) /// - Old Description: "Enable Depth & color frame sync with periodic calibration for proper /// alignment" /// /// `Reset camera accuracy health` /// /// - Deprecated as of 2.46 (not officially released, so technically 2.47) /// - Old Description: "Reset Camera Accuracy metric (if affected by TriggerCameraAccuracyHealth /// option)." #[repr(i32)] #[derive(FromPrimitive, ToPrimitive, Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Rs2Option { /// Enable/disable color backlight compensation. BacklightCompensation = sys::rs2_option_RS2_OPTION_BACKLIGHT_COMPENSATION as i32, /// Set color image brightness. Brightness = sys::rs2_option_RS2_OPTION_BRIGHTNESS as i32, /// Set color image contrast. Contrast = sys::rs2_option_RS2_OPTION_CONTRAST as i32, /// Set exposure time of color camera. Setting any value will disable auto exposure. Exposure = sys::rs2_option_RS2_OPTION_EXPOSURE as i32, /// Set color image gain. Gain = sys::rs2_option_RS2_OPTION_GAIN as i32, /// Set color image gamma setting. Gamma = sys::rs2_option_RS2_OPTION_GAMMA as i32, /// Set color image hue. Hue = sys::rs2_option_RS2_OPTION_HUE as i32, /// Set color image saturation. Saturation = sys::rs2_option_RS2_OPTION_SATURATION as i32, /// Set color image sharpness. Sharpness = sys::rs2_option_RS2_OPTION_SHARPNESS as i32, /// Set white balance of color image. Setting any value will disable auto white balance. WhiteBalance = sys::rs2_option_RS2_OPTION_WHITE_BALANCE as i32, /// Enable/disable color image auto-exposure. EnableAutoExposure = sys::rs2_option_RS2_OPTION_ENABLE_AUTO_EXPOSURE as i32, /// Enable/disable color image auto-white-balance EnableAutoWhiteBalance = sys::rs2_option_RS2_OPTION_ENABLE_AUTO_WHITE_BALANCE as i32, /// Set the visual preset on the sensor. `sensor.get_option_range()` provides /// access to several recommend sets of option presets for a depth camera. The preset /// selection varies between devices and sensors. VisualPreset = sys::rs2_option_RS2_OPTION_VISUAL_PRESET as i32, /// Set the power of the laser emitter, with 0 meaning projector off. LaserPower = sys::rs2_option_RS2_OPTION_LASER_POWER as i32, /// Set the number of patterns projected per frame. The higher the accuracy value, /// the more patterns projected. Increasing the number of patterns helps to achieve /// better accuracy. Note that this control affects Depth FPS. Accuracy = sys::rs2_option_RS2_OPTION_ACCURACY as i32, /// Set the motion vs. range trade-off. Lower values allow for better motion sensitivity. /// Higher values allow for better depth range. MotionRange = sys::rs2_option_RS2_OPTION_MOTION_RANGE as i32, /// Set the filter to apply to each depth frame. Each one of the filter is optimized per the /// application requirements. FilterOption = sys::rs2_option_RS2_OPTION_FILTER_OPTION as i32, /// Set the confidence level threshold used by the Depth algorithm pipe. /// This determines whether a pixel will get a valid range or will be marked as invalid. ConfidenceThreshold = sys::rs2_option_RS2_OPTION_CONFIDENCE_THRESHOLD as i32, /// Enable/disable emitters. Emitter selection: /// /// - `0`: disable all emitters /// - `1`: enable laser /// - `2`: enable auto laser /// - `3`: enable LED EmitterEnabled = sys::rs2_option_RS2_OPTION_EMITTER_ENABLED as i32, /// Set the number of frames the user is allowed to keep per stream. /// Trying to hold on to more frames will cause frame drops. FramesQueueSize = sys::rs2_option_RS2_OPTION_FRAMES_QUEUE_SIZE as i32, /// Get the total number of detected frame drops from all streams. TotalFrameDrops = sys::rs2_option_RS2_OPTION_TOTAL_FRAME_DROPS as i32, /// Set the auto-exposure mode: /// /// - Static /// - Anti-Flicker /// - Hybrid AutoExposureMode = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_MODE as i32, /// Set the power line frequency control for anti-flickering: /// /// - Off /// - 50Hz /// - 60Hz /// - Auto PowerLineFrequency = sys::rs2_option_RS2_OPTION_POWER_LINE_FREQUENCY as i32, /// Get the current Temperature of the ASIC. AsicTemperature = sys::rs2_option_RS2_OPTION_ASIC_TEMPERATURE as i32, /// Enable/disable error handling. ErrorPollingEnabled = sys::rs2_option_RS2_OPTION_ERROR_POLLING_ENABLED as i32, /// Get the Current Temperature of the projector. ProjectorTemperature = sys::rs2_option_RS2_OPTION_PROJECTOR_TEMPERATURE as i32, /// Enable/disable trigger to be outputed from the camera to any external device on /// every depth frame. OutputTriggerEnabled = sys::rs2_option_RS2_OPTION_OUTPUT_TRIGGER_ENABLED as i32, /// Get the current Motion-Module Temperature. MotionModuleTemperature = sys::rs2_option_RS2_OPTION_MOTION_MODULE_TEMPERATURE as i32, /// Set the number of meters represented by a single depth unit. DepthUnits = sys::rs2_option_RS2_OPTION_DEPTH_UNITS as i32, /// Enable/Disable automatic correction of the motion data. EnableMotionCorrection = sys::rs2_option_RS2_OPTION_ENABLE_MOTION_CORRECTION as i32, /// Allows sensor to dynamically ajust the frame rate depending on lighting conditions. AutoExposurePriority = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_PRIORITY as i32, /// Set the color scheme for data visualization. ColorScheme = sys::rs2_option_RS2_OPTION_COLOR_SCHEME as i32, /// Enable/disable histogram equalization post-processing on the depth data. HistogramEqualizationEnabled = sys::rs2_option_RS2_OPTION_HISTOGRAM_EQUALIZATION_ENABLED as i32, /// Set the Minimal distance to the target. MinDistance = sys::rs2_option_RS2_OPTION_MIN_DISTANCE as i32, /// Set the Maximum distance to the target. MaxDistance = sys::rs2_option_RS2_OPTION_MAX_DISTANCE as i32, /// Get the texture mapping stream unique ID. TextureSource = sys::rs2_option_RS2_OPTION_TEXTURE_SOURCE as i32, /// Set the 2D-filter effect. The specific interpretation is given within the context of the filter. FilterMagnitude = sys::rs2_option_RS2_OPTION_FILTER_MAGNITUDE as i32, /// Set the 2D-filter parameter that controls the weight/radius for smoothing. FilterSmoothAlpha = sys::rs2_option_RS2_OPTION_FILTER_SMOOTH_ALPHA as i32, /// Set the 2D-filter range/validity threshold. FilterSmoothDelta = sys::rs2_option_RS2_OPTION_FILTER_SMOOTH_DELTA as i32, /// Enhance depth data post-processing with holes filling where appropriate. HolesFill = sys::rs2_option_RS2_OPTION_HOLES_FILL as i32, /// Get the distance in mm between the first and the second imagers in stereo-based depth cameras. StereoBaseline = sys::rs2_option_RS2_OPTION_STEREO_BASELINE as i32, /// Allows dynamically ajust the converge step value of the target exposure in /// the Auto-Exposure algorithm. AutoExposureConvergeStep = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_CONVERGE_STEP as i32, /// Impose Inter-camera HW synchronization mode. Applicable for D400/L500/Rolling Shutter SKUs. InterCamSyncMode = sys::rs2_option_RS2_OPTION_INTER_CAM_SYNC_MODE as i32, /// Select a stream to process. StreamFilter = sys::rs2_option_RS2_OPTION_STREAM_FILTER as i32, /// Select a stream format to process. StreamFormatFilter = sys::rs2_option_RS2_OPTION_STREAM_FORMAT_FILTER as i32, /// Select a stream index to process. StreamIndexFilter = sys::rs2_option_RS2_OPTION_STREAM_INDEX_FILTER as i32, /// When supported, this option make the camera to switch the emitter state every frame. /// 0 for disabled, 1 for enabled. EmitterOnOff = sys::rs2_option_RS2_OPTION_EMITTER_ON_OFF as i32, /// Get the LDD temperature. LldTemperature = sys::rs2_option_RS2_OPTION_LLD_TEMPERATURE as i32, /// Get the MC temperature. McTemperature = sys::rs2_option_RS2_OPTION_MC_TEMPERATURE as i32, /// Get the MA temperature. MaTemperature = sys::rs2_option_RS2_OPTION_MA_TEMPERATURE as i32, /// Hardware stream configuration. HardwarePreset = sys::rs2_option_RS2_OPTION_HARDWARE_PRESET as i32, /// Enable/disable global time. GlobalTimeEnabled = sys::rs2_option_RS2_OPTION_GLOBAL_TIME_ENABLED as i32, /// Get the APD temperature. ApdTemperature = sys::rs2_option_RS2_OPTION_APD_TEMPERATURE as i32, /// Enable/disable an internal map. EnableMapping = sys::rs2_option_RS2_OPTION_ENABLE_MAPPING as i32, /// Enable/disable appearance-based relocalization. EnableRelocalization = sys::rs2_option_RS2_OPTION_ENABLE_RELOCALIZATION as i32, /// Enable/disable position jumping. EnablePoseJumping = sys::rs2_option_RS2_OPTION_ENABLE_POSE_JUMPING as i32, /// Enable/disable dynamic calibration. EnableDynamicCalibration = sys::rs2_option_RS2_OPTION_ENABLE_DYNAMIC_CALIBRATION as i32, /// Get the offset from sensor to depth origin in millimeters. DepthOffset = sys::rs2_option_RS2_OPTION_DEPTH_OFFSET as i32, /// Set the power of the LED (light emitting diode), with 0 meaning off LedPower = sys::rs2_option_RS2_OPTION_LED_POWER as i32, /// Preserve the previous map when starting. EnableMapPreservation = sys::rs2_option_RS2_OPTION_ENABLE_MAP_PRESERVATION as i32, /// Enable/disable sensor shutdown when a free-fall is detected (on by default). FreefallDetectionEnabled = sys::rs2_option_RS2_OPTION_FREEFALL_DETECTION_ENABLED as i32, /// Changes the exposure time of Avalanche Photo Diode in the receiver. AvalanchePhotoDiode = sys::rs2_option_RS2_OPTION_AVALANCHE_PHOTO_DIODE as i32, /// Changes the amount of sharpening in the post-processed image. PostProcessingSharpening = sys::rs2_option_RS2_OPTION_POST_PROCESSING_SHARPENING as i32, /// Changes the amount of sharpening in the pre-processed image. PreProcessingSharpening = sys::rs2_option_RS2_OPTION_PRE_PROCESSING_SHARPENING as i32, /// Control edges and background noise. NoiseFiltering = sys::rs2_option_RS2_OPTION_NOISE_FILTERING as i32, /// Enable/disable pixel invalidation. InvalidationBypass = sys::rs2_option_RS2_OPTION_INVALIDATION_BYPASS as i32, /// Change the depth digital gain see rs2_digital_gain for values. DigitalGain = sys::rs2_option_RS2_OPTION_DIGITAL_GAIN as i32, /// The resolution mode: see rs2_sensor_mode for values. SensoeMode = sys::rs2_option_RS2_OPTION_SENSOR_MODE as i32, /// Enable/disable Laser On constantly (GS SKU Only). EmitterAlwaysOn = sys::rs2_option_RS2_OPTION_EMITTER_ALWAYS_ON as i32, /// Depth Thermal Compensation for selected D400 SKUs. ThermalCompensation = sys::rs2_option_RS2_OPTION_THERMAL_COMPENSATION as i32, /// Set host performance mode to optimize device settings so host can keep up with workload. /// Take USB transaction granularity as an example. Setting option to low performance host leads /// to larger USB transaction sizes and a reduced number of transactions. This improves performance /// and stability if the host machine is relatively weak compared to the workload. HostPerformance = sys::rs2_option_RS2_OPTION_HOST_PERFORMANCE as i32, /// Enable/disable HDR. HdrEnabled = sys::rs2_option_RS2_OPTION_HDR_ENABLED as i32, /// Get HDR Sequence name. SequenceName = sys::rs2_option_RS2_OPTION_SEQUENCE_NAME as i32, /// Get HDR Sequence size. SequenceSize = sys::rs2_option_RS2_OPTION_SEQUENCE_SIZE as i32, /// Get HDR Sequence ID - 0 is not HDR; sequence ID for HDR configuration starts from 1. SequenceId = sys::rs2_option_RS2_OPTION_SEQUENCE_ID as i32, /// Get Humidity temperature [in Celsius]. HumidityTemperature = sys::rs2_option_RS2_OPTION_HUMIDITY_TEMPERATURE as i32, /// Enable/disable the maximum usable depth sensor range given the amount of ambient light in the scene. EnableMaxUsableRange = sys::rs2_option_RS2_OPTION_ENABLE_MAX_USABLE_RANGE as i32, /// Enable/disable the alternate IR, When enabling alternate IR, the IR image is holding the amplitude of the depth correlation. AlternateIr = sys::rs2_option_RS2_OPTION_ALTERNATE_IR as i32, /// Get an estimation of the noise on the IR image. NoiseEstimation = sys::rs2_option_RS2_OPTION_NOISE_ESTIMATION as i32, /// Enable/disable data collection for calculating IR pixel reflectivity. EnableIrReflectivity = sys::rs2_option_RS2_OPTION_ENABLE_IR_REFLECTIVITY as i32, /// Auto exposure limit in microseconds. /// /// Default is 0 which means full exposure range. If the requested exposure limit is greater /// than frame time, it will be set to frame time at runtime. Setting will not take effect /// until next streaming session. AutoExposureLimit = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_LIMIT as i32, /// Auto gain limits ranging from 16 to 248. /// /// Default is 0 which means full gain. If the requested gain limit is less than 16, it will be /// set to 16. If the requested gain limit is greater than 248, it will be set to 248. Setting /// will not take effect until next streaming session. AutoGainLimit = sys::rs2_option_RS2_OPTION_AUTO_GAIN_LIMIT as i32, /// Enable receiver sensitivity according to ambient light, bounded by the Receiver GAin /// control. AutoReceiverSensitivity = sys::rs2_option_RS2_OPTION_AUTO_RX_SENSITIVITY as i32, /// Changes the transmistter frequency frequencies increasing effective range over sharpness. TransmitterFrequency = sys::rs2_option_RS2_OPTION_TRANSMITTER_FREQUENCY as i32, /* Not included since this just tells us the total number of options. * * Count = sys::rs2_option_RS2_OPTION_COUNT, */ } impl Rs2Option { /// Get the option as a CStr. pub fn to_cstr(self) -> &'static CStr { unsafe { let ptr = sys::rs2_option_to_string(self as sys::rs2_option); CStr::from_ptr(ptr) } } /// Get the option as a str. pub fn to_str(self) -> &'static str { self.to_cstr().to_str().unwrap() } } impl ToString for Rs2Option { fn to_string(&self) -> String { self.to_str().to_owned() } } /// The range of available values of a supported option. pub struct Rs2OptionRange { /// The minimum value which will be accepted for this option pub min: f32, /// The maximum value which will be accepted for this option pub max: f32, /// The granularity of options which accept discrete values, or zero if the option accepts /// continuous values pub step: f32, /// The default value of the option pub default: f32, } #[cfg(test)] mod tests { use super::*; use num_traits::FromPrimitive; #[test] fn all_variants_exist() { let deprecated_options = vec![ sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_X as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_Y as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_ENABLED as i32, sys::rs2_option_RS2_OPTION_AMBIENT_LIGHT as i32, sys::rs2_option_RS2_OPTION_TRIGGER_CAMERA_ACCURACY_HEALTH as i32, sys::rs2_option_RS2_OPTION_RESET_CAMERA_ACCURACY_HEALTH as i32, ]; for i in 0..sys::rs2_option_RS2_OPTION_COUNT as i32 { if deprecated_options.iter().any(|x| x == &i) { continue; } assert!( Rs2Option::from_i32(i).is_some(), "Rs2Option variant for ordinal {} does not exist.", i, ); } } }
OptionSetError
identifier_name
option.rs
//! Enumeration of RS2 sensor options. //! //! Not all options apply to every sensor. In order to retrieve the correct options, //! one must iterate over the `sensor` object for option compatibility. //! //! Notice that this option refers to the `sensor`, not the device. However, the device //! used also matters; sensors that are alike across devices are not guaranteed to share //! the same sensor options. Again, it is up to the user to query whether an option //! is supported by the sensor before attempting to set it. Failure to do so may cause //! an error in operation. use super::Rs2Exception; use num_derive::{FromPrimitive, ToPrimitive}; use realsense_sys as sys; use std::ffi::CStr; use thiserror::Error; /// Occur when an option cannot be set. #[derive(Error, Debug)] pub enum OptionSetError { /// The requested option is not supported by this sensor. #[error("Option not supported on this sensor.")] OptionNotSupported, /// The requested option is read-only and cannot be set. #[error("Option is read only.")] OptionIsReadOnly, /// The requested option could not be set. Reason is reported by the sensor. #[error("Could not set option. Type: {0}; Reason: {1}")] CouldNotSetOption(Rs2Exception, String), } /// The enumeration of options available in the RealSense SDK. /// /// The majority of the options presented have a specific range of valid values. Run /// `sensor.get_option_range(Rs2Option::_)` to retrieve possible values of an Option type for your sensor. /// Setting a bad value will lead to a no-op at best, and a malfunction at worst. /// /// # Deprecated Options /// /// `AmbientLight` /// /// - Equivalent to `RS2_OPTION_AMBIENT_LIGHT` /// - Replacement: [Rs2Option::DigitalGain]. /// - Old Description: "Change the depth ambient light see rs2_ambient_light for values". /// /// `ZeroOrderEnabled` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_ENABLED` /// - Replacement: N/A. /// - Old Description: "Toggle Zero-Order mode." /// /// `ZeroOrderPointX` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_POINT_X` /// - Replacement: N/A. /// - Old Description: "Get the Zero order point x." /// /// `ZeroOrderPointY` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_POINT_Y` /// - Replacement: N/A. /// - Old Description: "Get the Zero order point y." /// /// `Trigger camera accuracy health` /// /// - Deprecated as of 2.46 (not officially released, so technically 2.47) /// - Old Description: "Enable Depth & color frame sync with periodic calibration for proper /// alignment" /// /// `Reset camera accuracy health` /// /// - Deprecated as of 2.46 (not officially released, so technically 2.47) /// - Old Description: "Reset Camera Accuracy metric (if affected by TriggerCameraAccuracyHealth /// option)." #[repr(i32)] #[derive(FromPrimitive, ToPrimitive, Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Rs2Option { /// Enable/disable color backlight compensation. BacklightCompensation = sys::rs2_option_RS2_OPTION_BACKLIGHT_COMPENSATION as i32, /// Set color image brightness. Brightness = sys::rs2_option_RS2_OPTION_BRIGHTNESS as i32, /// Set color image contrast. Contrast = sys::rs2_option_RS2_OPTION_CONTRAST as i32, /// Set exposure time of color camera. Setting any value will disable auto exposure. Exposure = sys::rs2_option_RS2_OPTION_EXPOSURE as i32, /// Set color image gain. Gain = sys::rs2_option_RS2_OPTION_GAIN as i32, /// Set color image gamma setting. Gamma = sys::rs2_option_RS2_OPTION_GAMMA as i32, /// Set color image hue. Hue = sys::rs2_option_RS2_OPTION_HUE as i32, /// Set color image saturation. Saturation = sys::rs2_option_RS2_OPTION_SATURATION as i32, /// Set color image sharpness. Sharpness = sys::rs2_option_RS2_OPTION_SHARPNESS as i32, /// Set white balance of color image. Setting any value will disable auto white balance. WhiteBalance = sys::rs2_option_RS2_OPTION_WHITE_BALANCE as i32, /// Enable/disable color image auto-exposure. EnableAutoExposure = sys::rs2_option_RS2_OPTION_ENABLE_AUTO_EXPOSURE as i32, /// Enable/disable color image auto-white-balance EnableAutoWhiteBalance = sys::rs2_option_RS2_OPTION_ENABLE_AUTO_WHITE_BALANCE as i32, /// Set the visual preset on the sensor. `sensor.get_option_range()` provides /// access to several recommend sets of option presets for a depth camera. The preset /// selection varies between devices and sensors. VisualPreset = sys::rs2_option_RS2_OPTION_VISUAL_PRESET as i32, /// Set the power of the laser emitter, with 0 meaning projector off. LaserPower = sys::rs2_option_RS2_OPTION_LASER_POWER as i32, /// Set the number of patterns projected per frame. The higher the accuracy value, /// the more patterns projected. Increasing the number of patterns helps to achieve /// better accuracy. Note that this control affects Depth FPS. Accuracy = sys::rs2_option_RS2_OPTION_ACCURACY as i32, /// Set the motion vs. range trade-off. Lower values allow for better motion sensitivity. /// Higher values allow for better depth range. MotionRange = sys::rs2_option_RS2_OPTION_MOTION_RANGE as i32, /// Set the filter to apply to each depth frame. Each one of the filter is optimized per the /// application requirements. FilterOption = sys::rs2_option_RS2_OPTION_FILTER_OPTION as i32, /// Set the confidence level threshold used by the Depth algorithm pipe. /// This determines whether a pixel will get a valid range or will be marked as invalid. ConfidenceThreshold = sys::rs2_option_RS2_OPTION_CONFIDENCE_THRESHOLD as i32, /// Enable/disable emitters. Emitter selection: /// /// - `0`: disable all emitters /// - `1`: enable laser /// - `2`: enable auto laser /// - `3`: enable LED EmitterEnabled = sys::rs2_option_RS2_OPTION_EMITTER_ENABLED as i32, /// Set the number of frames the user is allowed to keep per stream. /// Trying to hold on to more frames will cause frame drops. FramesQueueSize = sys::rs2_option_RS2_OPTION_FRAMES_QUEUE_SIZE as i32, /// Get the total number of detected frame drops from all streams. TotalFrameDrops = sys::rs2_option_RS2_OPTION_TOTAL_FRAME_DROPS as i32, /// Set the auto-exposure mode: /// /// - Static /// - Anti-Flicker /// - Hybrid AutoExposureMode = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_MODE as i32, /// Set the power line frequency control for anti-flickering: /// /// - Off /// - 50Hz /// - 60Hz /// - Auto PowerLineFrequency = sys::rs2_option_RS2_OPTION_POWER_LINE_FREQUENCY as i32, /// Get the current Temperature of the ASIC. AsicTemperature = sys::rs2_option_RS2_OPTION_ASIC_TEMPERATURE as i32, /// Enable/disable error handling. ErrorPollingEnabled = sys::rs2_option_RS2_OPTION_ERROR_POLLING_ENABLED as i32, /// Get the Current Temperature of the projector. ProjectorTemperature = sys::rs2_option_RS2_OPTION_PROJECTOR_TEMPERATURE as i32, /// Enable/disable trigger to be outputed from the camera to any external device on /// every depth frame. OutputTriggerEnabled = sys::rs2_option_RS2_OPTION_OUTPUT_TRIGGER_ENABLED as i32, /// Get the current Motion-Module Temperature. MotionModuleTemperature = sys::rs2_option_RS2_OPTION_MOTION_MODULE_TEMPERATURE as i32, /// Set the number of meters represented by a single depth unit. DepthUnits = sys::rs2_option_RS2_OPTION_DEPTH_UNITS as i32, /// Enable/Disable automatic correction of the motion data. EnableMotionCorrection = sys::rs2_option_RS2_OPTION_ENABLE_MOTION_CORRECTION as i32, /// Allows sensor to dynamically ajust the frame rate depending on lighting conditions. AutoExposurePriority = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_PRIORITY as i32, /// Set the color scheme for data visualization. ColorScheme = sys::rs2_option_RS2_OPTION_COLOR_SCHEME as i32, /// Enable/disable histogram equalization post-processing on the depth data. HistogramEqualizationEnabled = sys::rs2_option_RS2_OPTION_HISTOGRAM_EQUALIZATION_ENABLED as i32, /// Set the Minimal distance to the target. MinDistance = sys::rs2_option_RS2_OPTION_MIN_DISTANCE as i32, /// Set the Maximum distance to the target. MaxDistance = sys::rs2_option_RS2_OPTION_MAX_DISTANCE as i32, /// Get the texture mapping stream unique ID. TextureSource = sys::rs2_option_RS2_OPTION_TEXTURE_SOURCE as i32, /// Set the 2D-filter effect. The specific interpretation is given within the context of the filter. FilterMagnitude = sys::rs2_option_RS2_OPTION_FILTER_MAGNITUDE as i32, /// Set the 2D-filter parameter that controls the weight/radius for smoothing. FilterSmoothAlpha = sys::rs2_option_RS2_OPTION_FILTER_SMOOTH_ALPHA as i32, /// Set the 2D-filter range/validity threshold. FilterSmoothDelta = sys::rs2_option_RS2_OPTION_FILTER_SMOOTH_DELTA as i32, /// Enhance depth data post-processing with holes filling where appropriate. HolesFill = sys::rs2_option_RS2_OPTION_HOLES_FILL as i32, /// Get the distance in mm between the first and the second imagers in stereo-based depth cameras. StereoBaseline = sys::rs2_option_RS2_OPTION_STEREO_BASELINE as i32, /// Allows dynamically ajust the converge step value of the target exposure in /// the Auto-Exposure algorithm. AutoExposureConvergeStep = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_CONVERGE_STEP as i32, /// Impose Inter-camera HW synchronization mode. Applicable for D400/L500/Rolling Shutter SKUs. InterCamSyncMode = sys::rs2_option_RS2_OPTION_INTER_CAM_SYNC_MODE as i32, /// Select a stream to process. StreamFilter = sys::rs2_option_RS2_OPTION_STREAM_FILTER as i32, /// Select a stream format to process. StreamFormatFilter = sys::rs2_option_RS2_OPTION_STREAM_FORMAT_FILTER as i32, /// Select a stream index to process. StreamIndexFilter = sys::rs2_option_RS2_OPTION_STREAM_INDEX_FILTER as i32, /// When supported, this option make the camera to switch the emitter state every frame. /// 0 for disabled, 1 for enabled. EmitterOnOff = sys::rs2_option_RS2_OPTION_EMITTER_ON_OFF as i32, /// Get the LDD temperature. LldTemperature = sys::rs2_option_RS2_OPTION_LLD_TEMPERATURE as i32, /// Get the MC temperature. McTemperature = sys::rs2_option_RS2_OPTION_MC_TEMPERATURE as i32, /// Get the MA temperature. MaTemperature = sys::rs2_option_RS2_OPTION_MA_TEMPERATURE as i32, /// Hardware stream configuration. HardwarePreset = sys::rs2_option_RS2_OPTION_HARDWARE_PRESET as i32, /// Enable/disable global time. GlobalTimeEnabled = sys::rs2_option_RS2_OPTION_GLOBAL_TIME_ENABLED as i32, /// Get the APD temperature. ApdTemperature = sys::rs2_option_RS2_OPTION_APD_TEMPERATURE as i32, /// Enable/disable an internal map. EnableMapping = sys::rs2_option_RS2_OPTION_ENABLE_MAPPING as i32, /// Enable/disable appearance-based relocalization. EnableRelocalization = sys::rs2_option_RS2_OPTION_ENABLE_RELOCALIZATION as i32, /// Enable/disable position jumping. EnablePoseJumping = sys::rs2_option_RS2_OPTION_ENABLE_POSE_JUMPING as i32, /// Enable/disable dynamic calibration. EnableDynamicCalibration = sys::rs2_option_RS2_OPTION_ENABLE_DYNAMIC_CALIBRATION as i32, /// Get the offset from sensor to depth origin in millimeters. DepthOffset = sys::rs2_option_RS2_OPTION_DEPTH_OFFSET as i32, /// Set the power of the LED (light emitting diode), with 0 meaning off LedPower = sys::rs2_option_RS2_OPTION_LED_POWER as i32, /// Preserve the previous map when starting. EnableMapPreservation = sys::rs2_option_RS2_OPTION_ENABLE_MAP_PRESERVATION as i32, /// Enable/disable sensor shutdown when a free-fall is detected (on by default). FreefallDetectionEnabled = sys::rs2_option_RS2_OPTION_FREEFALL_DETECTION_ENABLED as i32, /// Changes the exposure time of Avalanche Photo Diode in the receiver. AvalanchePhotoDiode = sys::rs2_option_RS2_OPTION_AVALANCHE_PHOTO_DIODE as i32, /// Changes the amount of sharpening in the post-processed image. PostProcessingSharpening = sys::rs2_option_RS2_OPTION_POST_PROCESSING_SHARPENING as i32, /// Changes the amount of sharpening in the pre-processed image. PreProcessingSharpening = sys::rs2_option_RS2_OPTION_PRE_PROCESSING_SHARPENING as i32, /// Control edges and background noise. NoiseFiltering = sys::rs2_option_RS2_OPTION_NOISE_FILTERING as i32, /// Enable/disable pixel invalidation. InvalidationBypass = sys::rs2_option_RS2_OPTION_INVALIDATION_BYPASS as i32, /// Change the depth digital gain see rs2_digital_gain for values. DigitalGain = sys::rs2_option_RS2_OPTION_DIGITAL_GAIN as i32, /// The resolution mode: see rs2_sensor_mode for values. SensoeMode = sys::rs2_option_RS2_OPTION_SENSOR_MODE as i32, /// Enable/disable Laser On constantly (GS SKU Only). EmitterAlwaysOn = sys::rs2_option_RS2_OPTION_EMITTER_ALWAYS_ON as i32, /// Depth Thermal Compensation for selected D400 SKUs. ThermalCompensation = sys::rs2_option_RS2_OPTION_THERMAL_COMPENSATION as i32, /// Set host performance mode to optimize device settings so host can keep up with workload. /// Take USB transaction granularity as an example. Setting option to low performance host leads /// to larger USB transaction sizes and a reduced number of transactions. This improves performance /// and stability if the host machine is relatively weak compared to the workload. HostPerformance = sys::rs2_option_RS2_OPTION_HOST_PERFORMANCE as i32, /// Enable/disable HDR. HdrEnabled = sys::rs2_option_RS2_OPTION_HDR_ENABLED as i32, /// Get HDR Sequence name. SequenceName = sys::rs2_option_RS2_OPTION_SEQUENCE_NAME as i32, /// Get HDR Sequence size. SequenceSize = sys::rs2_option_RS2_OPTION_SEQUENCE_SIZE as i32, /// Get HDR Sequence ID - 0 is not HDR; sequence ID for HDR configuration starts from 1. SequenceId = sys::rs2_option_RS2_OPTION_SEQUENCE_ID as i32, /// Get Humidity temperature [in Celsius]. HumidityTemperature = sys::rs2_option_RS2_OPTION_HUMIDITY_TEMPERATURE as i32,
NoiseEstimation = sys::rs2_option_RS2_OPTION_NOISE_ESTIMATION as i32, /// Enable/disable data collection for calculating IR pixel reflectivity. EnableIrReflectivity = sys::rs2_option_RS2_OPTION_ENABLE_IR_REFLECTIVITY as i32, /// Auto exposure limit in microseconds. /// /// Default is 0 which means full exposure range. If the requested exposure limit is greater /// than frame time, it will be set to frame time at runtime. Setting will not take effect /// until next streaming session. AutoExposureLimit = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_LIMIT as i32, /// Auto gain limits ranging from 16 to 248. /// /// Default is 0 which means full gain. If the requested gain limit is less than 16, it will be /// set to 16. If the requested gain limit is greater than 248, it will be set to 248. Setting /// will not take effect until next streaming session. AutoGainLimit = sys::rs2_option_RS2_OPTION_AUTO_GAIN_LIMIT as i32, /// Enable receiver sensitivity according to ambient light, bounded by the Receiver GAin /// control. AutoReceiverSensitivity = sys::rs2_option_RS2_OPTION_AUTO_RX_SENSITIVITY as i32, /// Changes the transmistter frequency frequencies increasing effective range over sharpness. TransmitterFrequency = sys::rs2_option_RS2_OPTION_TRANSMITTER_FREQUENCY as i32, /* Not included since this just tells us the total number of options. * * Count = sys::rs2_option_RS2_OPTION_COUNT, */ } impl Rs2Option { /// Get the option as a CStr. pub fn to_cstr(self) -> &'static CStr { unsafe { let ptr = sys::rs2_option_to_string(self as sys::rs2_option); CStr::from_ptr(ptr) } } /// Get the option as a str. pub fn to_str(self) -> &'static str { self.to_cstr().to_str().unwrap() } } impl ToString for Rs2Option { fn to_string(&self) -> String { self.to_str().to_owned() } } /// The range of available values of a supported option. pub struct Rs2OptionRange { /// The minimum value which will be accepted for this option pub min: f32, /// The maximum value which will be accepted for this option pub max: f32, /// The granularity of options which accept discrete values, or zero if the option accepts /// continuous values pub step: f32, /// The default value of the option pub default: f32, } #[cfg(test)] mod tests { use super::*; use num_traits::FromPrimitive; #[test] fn all_variants_exist() { let deprecated_options = vec![ sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_X as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_Y as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_ENABLED as i32, sys::rs2_option_RS2_OPTION_AMBIENT_LIGHT as i32, sys::rs2_option_RS2_OPTION_TRIGGER_CAMERA_ACCURACY_HEALTH as i32, sys::rs2_option_RS2_OPTION_RESET_CAMERA_ACCURACY_HEALTH as i32, ]; for i in 0..sys::rs2_option_RS2_OPTION_COUNT as i32 { if deprecated_options.iter().any(|x| x == &i) { continue; } assert!( Rs2Option::from_i32(i).is_some(), "Rs2Option variant for ordinal {} does not exist.", i, ); } } }
/// Enable/disable the maximum usable depth sensor range given the amount of ambient light in the scene. EnableMaxUsableRange = sys::rs2_option_RS2_OPTION_ENABLE_MAX_USABLE_RANGE as i32, /// Enable/disable the alternate IR, When enabling alternate IR, the IR image is holding the amplitude of the depth correlation. AlternateIr = sys::rs2_option_RS2_OPTION_ALTERNATE_IR as i32, /// Get an estimation of the noise on the IR image.
random_line_split
option.rs
//! Enumeration of RS2 sensor options. //! //! Not all options apply to every sensor. In order to retrieve the correct options, //! one must iterate over the `sensor` object for option compatibility. //! //! Notice that this option refers to the `sensor`, not the device. However, the device //! used also matters; sensors that are alike across devices are not guaranteed to share //! the same sensor options. Again, it is up to the user to query whether an option //! is supported by the sensor before attempting to set it. Failure to do so may cause //! an error in operation. use super::Rs2Exception; use num_derive::{FromPrimitive, ToPrimitive}; use realsense_sys as sys; use std::ffi::CStr; use thiserror::Error; /// Occur when an option cannot be set. #[derive(Error, Debug)] pub enum OptionSetError { /// The requested option is not supported by this sensor. #[error("Option not supported on this sensor.")] OptionNotSupported, /// The requested option is read-only and cannot be set. #[error("Option is read only.")] OptionIsReadOnly, /// The requested option could not be set. Reason is reported by the sensor. #[error("Could not set option. Type: {0}; Reason: {1}")] CouldNotSetOption(Rs2Exception, String), } /// The enumeration of options available in the RealSense SDK. /// /// The majority of the options presented have a specific range of valid values. Run /// `sensor.get_option_range(Rs2Option::_)` to retrieve possible values of an Option type for your sensor. /// Setting a bad value will lead to a no-op at best, and a malfunction at worst. /// /// # Deprecated Options /// /// `AmbientLight` /// /// - Equivalent to `RS2_OPTION_AMBIENT_LIGHT` /// - Replacement: [Rs2Option::DigitalGain]. /// - Old Description: "Change the depth ambient light see rs2_ambient_light for values". /// /// `ZeroOrderEnabled` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_ENABLED` /// - Replacement: N/A. /// - Old Description: "Toggle Zero-Order mode." /// /// `ZeroOrderPointX` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_POINT_X` /// - Replacement: N/A. /// - Old Description: "Get the Zero order point x." /// /// `ZeroOrderPointY` /// /// - Equivalent to `RS2_OPTION_ZERO_ORDER_POINT_Y` /// - Replacement: N/A. /// - Old Description: "Get the Zero order point y." /// /// `Trigger camera accuracy health` /// /// - Deprecated as of 2.46 (not officially released, so technically 2.47) /// - Old Description: "Enable Depth & color frame sync with periodic calibration for proper /// alignment" /// /// `Reset camera accuracy health` /// /// - Deprecated as of 2.46 (not officially released, so technically 2.47) /// - Old Description: "Reset Camera Accuracy metric (if affected by TriggerCameraAccuracyHealth /// option)." #[repr(i32)] #[derive(FromPrimitive, ToPrimitive, Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Rs2Option { /// Enable/disable color backlight compensation. BacklightCompensation = sys::rs2_option_RS2_OPTION_BACKLIGHT_COMPENSATION as i32, /// Set color image brightness. Brightness = sys::rs2_option_RS2_OPTION_BRIGHTNESS as i32, /// Set color image contrast. Contrast = sys::rs2_option_RS2_OPTION_CONTRAST as i32, /// Set exposure time of color camera. Setting any value will disable auto exposure. Exposure = sys::rs2_option_RS2_OPTION_EXPOSURE as i32, /// Set color image gain. Gain = sys::rs2_option_RS2_OPTION_GAIN as i32, /// Set color image gamma setting. Gamma = sys::rs2_option_RS2_OPTION_GAMMA as i32, /// Set color image hue. Hue = sys::rs2_option_RS2_OPTION_HUE as i32, /// Set color image saturation. Saturation = sys::rs2_option_RS2_OPTION_SATURATION as i32, /// Set color image sharpness. Sharpness = sys::rs2_option_RS2_OPTION_SHARPNESS as i32, /// Set white balance of color image. Setting any value will disable auto white balance. WhiteBalance = sys::rs2_option_RS2_OPTION_WHITE_BALANCE as i32, /// Enable/disable color image auto-exposure. EnableAutoExposure = sys::rs2_option_RS2_OPTION_ENABLE_AUTO_EXPOSURE as i32, /// Enable/disable color image auto-white-balance EnableAutoWhiteBalance = sys::rs2_option_RS2_OPTION_ENABLE_AUTO_WHITE_BALANCE as i32, /// Set the visual preset on the sensor. `sensor.get_option_range()` provides /// access to several recommend sets of option presets for a depth camera. The preset /// selection varies between devices and sensors. VisualPreset = sys::rs2_option_RS2_OPTION_VISUAL_PRESET as i32, /// Set the power of the laser emitter, with 0 meaning projector off. LaserPower = sys::rs2_option_RS2_OPTION_LASER_POWER as i32, /// Set the number of patterns projected per frame. The higher the accuracy value, /// the more patterns projected. Increasing the number of patterns helps to achieve /// better accuracy. Note that this control affects Depth FPS. Accuracy = sys::rs2_option_RS2_OPTION_ACCURACY as i32, /// Set the motion vs. range trade-off. Lower values allow for better motion sensitivity. /// Higher values allow for better depth range. MotionRange = sys::rs2_option_RS2_OPTION_MOTION_RANGE as i32, /// Set the filter to apply to each depth frame. Each one of the filter is optimized per the /// application requirements. FilterOption = sys::rs2_option_RS2_OPTION_FILTER_OPTION as i32, /// Set the confidence level threshold used by the Depth algorithm pipe. /// This determines whether a pixel will get a valid range or will be marked as invalid. ConfidenceThreshold = sys::rs2_option_RS2_OPTION_CONFIDENCE_THRESHOLD as i32, /// Enable/disable emitters. Emitter selection: /// /// - `0`: disable all emitters /// - `1`: enable laser /// - `2`: enable auto laser /// - `3`: enable LED EmitterEnabled = sys::rs2_option_RS2_OPTION_EMITTER_ENABLED as i32, /// Set the number of frames the user is allowed to keep per stream. /// Trying to hold on to more frames will cause frame drops. FramesQueueSize = sys::rs2_option_RS2_OPTION_FRAMES_QUEUE_SIZE as i32, /// Get the total number of detected frame drops from all streams. TotalFrameDrops = sys::rs2_option_RS2_OPTION_TOTAL_FRAME_DROPS as i32, /// Set the auto-exposure mode: /// /// - Static /// - Anti-Flicker /// - Hybrid AutoExposureMode = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_MODE as i32, /// Set the power line frequency control for anti-flickering: /// /// - Off /// - 50Hz /// - 60Hz /// - Auto PowerLineFrequency = sys::rs2_option_RS2_OPTION_POWER_LINE_FREQUENCY as i32, /// Get the current Temperature of the ASIC. AsicTemperature = sys::rs2_option_RS2_OPTION_ASIC_TEMPERATURE as i32, /// Enable/disable error handling. ErrorPollingEnabled = sys::rs2_option_RS2_OPTION_ERROR_POLLING_ENABLED as i32, /// Get the Current Temperature of the projector. ProjectorTemperature = sys::rs2_option_RS2_OPTION_PROJECTOR_TEMPERATURE as i32, /// Enable/disable trigger to be outputed from the camera to any external device on /// every depth frame. OutputTriggerEnabled = sys::rs2_option_RS2_OPTION_OUTPUT_TRIGGER_ENABLED as i32, /// Get the current Motion-Module Temperature. MotionModuleTemperature = sys::rs2_option_RS2_OPTION_MOTION_MODULE_TEMPERATURE as i32, /// Set the number of meters represented by a single depth unit. DepthUnits = sys::rs2_option_RS2_OPTION_DEPTH_UNITS as i32, /// Enable/Disable automatic correction of the motion data. EnableMotionCorrection = sys::rs2_option_RS2_OPTION_ENABLE_MOTION_CORRECTION as i32, /// Allows sensor to dynamically ajust the frame rate depending on lighting conditions. AutoExposurePriority = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_PRIORITY as i32, /// Set the color scheme for data visualization. ColorScheme = sys::rs2_option_RS2_OPTION_COLOR_SCHEME as i32, /// Enable/disable histogram equalization post-processing on the depth data. HistogramEqualizationEnabled = sys::rs2_option_RS2_OPTION_HISTOGRAM_EQUALIZATION_ENABLED as i32, /// Set the Minimal distance to the target. MinDistance = sys::rs2_option_RS2_OPTION_MIN_DISTANCE as i32, /// Set the Maximum distance to the target. MaxDistance = sys::rs2_option_RS2_OPTION_MAX_DISTANCE as i32, /// Get the texture mapping stream unique ID. TextureSource = sys::rs2_option_RS2_OPTION_TEXTURE_SOURCE as i32, /// Set the 2D-filter effect. The specific interpretation is given within the context of the filter. FilterMagnitude = sys::rs2_option_RS2_OPTION_FILTER_MAGNITUDE as i32, /// Set the 2D-filter parameter that controls the weight/radius for smoothing. FilterSmoothAlpha = sys::rs2_option_RS2_OPTION_FILTER_SMOOTH_ALPHA as i32, /// Set the 2D-filter range/validity threshold. FilterSmoothDelta = sys::rs2_option_RS2_OPTION_FILTER_SMOOTH_DELTA as i32, /// Enhance depth data post-processing with holes filling where appropriate. HolesFill = sys::rs2_option_RS2_OPTION_HOLES_FILL as i32, /// Get the distance in mm between the first and the second imagers in stereo-based depth cameras. StereoBaseline = sys::rs2_option_RS2_OPTION_STEREO_BASELINE as i32, /// Allows dynamically ajust the converge step value of the target exposure in /// the Auto-Exposure algorithm. AutoExposureConvergeStep = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_CONVERGE_STEP as i32, /// Impose Inter-camera HW synchronization mode. Applicable for D400/L500/Rolling Shutter SKUs. InterCamSyncMode = sys::rs2_option_RS2_OPTION_INTER_CAM_SYNC_MODE as i32, /// Select a stream to process. StreamFilter = sys::rs2_option_RS2_OPTION_STREAM_FILTER as i32, /// Select a stream format to process. StreamFormatFilter = sys::rs2_option_RS2_OPTION_STREAM_FORMAT_FILTER as i32, /// Select a stream index to process. StreamIndexFilter = sys::rs2_option_RS2_OPTION_STREAM_INDEX_FILTER as i32, /// When supported, this option make the camera to switch the emitter state every frame. /// 0 for disabled, 1 for enabled. EmitterOnOff = sys::rs2_option_RS2_OPTION_EMITTER_ON_OFF as i32, /// Get the LDD temperature. LldTemperature = sys::rs2_option_RS2_OPTION_LLD_TEMPERATURE as i32, /// Get the MC temperature. McTemperature = sys::rs2_option_RS2_OPTION_MC_TEMPERATURE as i32, /// Get the MA temperature. MaTemperature = sys::rs2_option_RS2_OPTION_MA_TEMPERATURE as i32, /// Hardware stream configuration. HardwarePreset = sys::rs2_option_RS2_OPTION_HARDWARE_PRESET as i32, /// Enable/disable global time. GlobalTimeEnabled = sys::rs2_option_RS2_OPTION_GLOBAL_TIME_ENABLED as i32, /// Get the APD temperature. ApdTemperature = sys::rs2_option_RS2_OPTION_APD_TEMPERATURE as i32, /// Enable/disable an internal map. EnableMapping = sys::rs2_option_RS2_OPTION_ENABLE_MAPPING as i32, /// Enable/disable appearance-based relocalization. EnableRelocalization = sys::rs2_option_RS2_OPTION_ENABLE_RELOCALIZATION as i32, /// Enable/disable position jumping. EnablePoseJumping = sys::rs2_option_RS2_OPTION_ENABLE_POSE_JUMPING as i32, /// Enable/disable dynamic calibration. EnableDynamicCalibration = sys::rs2_option_RS2_OPTION_ENABLE_DYNAMIC_CALIBRATION as i32, /// Get the offset from sensor to depth origin in millimeters. DepthOffset = sys::rs2_option_RS2_OPTION_DEPTH_OFFSET as i32, /// Set the power of the LED (light emitting diode), with 0 meaning off LedPower = sys::rs2_option_RS2_OPTION_LED_POWER as i32, /// Preserve the previous map when starting. EnableMapPreservation = sys::rs2_option_RS2_OPTION_ENABLE_MAP_PRESERVATION as i32, /// Enable/disable sensor shutdown when a free-fall is detected (on by default). FreefallDetectionEnabled = sys::rs2_option_RS2_OPTION_FREEFALL_DETECTION_ENABLED as i32, /// Changes the exposure time of Avalanche Photo Diode in the receiver. AvalanchePhotoDiode = sys::rs2_option_RS2_OPTION_AVALANCHE_PHOTO_DIODE as i32, /// Changes the amount of sharpening in the post-processed image. PostProcessingSharpening = sys::rs2_option_RS2_OPTION_POST_PROCESSING_SHARPENING as i32, /// Changes the amount of sharpening in the pre-processed image. PreProcessingSharpening = sys::rs2_option_RS2_OPTION_PRE_PROCESSING_SHARPENING as i32, /// Control edges and background noise. NoiseFiltering = sys::rs2_option_RS2_OPTION_NOISE_FILTERING as i32, /// Enable/disable pixel invalidation. InvalidationBypass = sys::rs2_option_RS2_OPTION_INVALIDATION_BYPASS as i32, /// Change the depth digital gain see rs2_digital_gain for values. DigitalGain = sys::rs2_option_RS2_OPTION_DIGITAL_GAIN as i32, /// The resolution mode: see rs2_sensor_mode for values. SensoeMode = sys::rs2_option_RS2_OPTION_SENSOR_MODE as i32, /// Enable/disable Laser On constantly (GS SKU Only). EmitterAlwaysOn = sys::rs2_option_RS2_OPTION_EMITTER_ALWAYS_ON as i32, /// Depth Thermal Compensation for selected D400 SKUs. ThermalCompensation = sys::rs2_option_RS2_OPTION_THERMAL_COMPENSATION as i32, /// Set host performance mode to optimize device settings so host can keep up with workload. /// Take USB transaction granularity as an example. Setting option to low performance host leads /// to larger USB transaction sizes and a reduced number of transactions. This improves performance /// and stability if the host machine is relatively weak compared to the workload. HostPerformance = sys::rs2_option_RS2_OPTION_HOST_PERFORMANCE as i32, /// Enable/disable HDR. HdrEnabled = sys::rs2_option_RS2_OPTION_HDR_ENABLED as i32, /// Get HDR Sequence name. SequenceName = sys::rs2_option_RS2_OPTION_SEQUENCE_NAME as i32, /// Get HDR Sequence size. SequenceSize = sys::rs2_option_RS2_OPTION_SEQUENCE_SIZE as i32, /// Get HDR Sequence ID - 0 is not HDR; sequence ID for HDR configuration starts from 1. SequenceId = sys::rs2_option_RS2_OPTION_SEQUENCE_ID as i32, /// Get Humidity temperature [in Celsius]. HumidityTemperature = sys::rs2_option_RS2_OPTION_HUMIDITY_TEMPERATURE as i32, /// Enable/disable the maximum usable depth sensor range given the amount of ambient light in the scene. EnableMaxUsableRange = sys::rs2_option_RS2_OPTION_ENABLE_MAX_USABLE_RANGE as i32, /// Enable/disable the alternate IR, When enabling alternate IR, the IR image is holding the amplitude of the depth correlation. AlternateIr = sys::rs2_option_RS2_OPTION_ALTERNATE_IR as i32, /// Get an estimation of the noise on the IR image. NoiseEstimation = sys::rs2_option_RS2_OPTION_NOISE_ESTIMATION as i32, /// Enable/disable data collection for calculating IR pixel reflectivity. EnableIrReflectivity = sys::rs2_option_RS2_OPTION_ENABLE_IR_REFLECTIVITY as i32, /// Auto exposure limit in microseconds. /// /// Default is 0 which means full exposure range. If the requested exposure limit is greater /// than frame time, it will be set to frame time at runtime. Setting will not take effect /// until next streaming session. AutoExposureLimit = sys::rs2_option_RS2_OPTION_AUTO_EXPOSURE_LIMIT as i32, /// Auto gain limits ranging from 16 to 248. /// /// Default is 0 which means full gain. If the requested gain limit is less than 16, it will be /// set to 16. If the requested gain limit is greater than 248, it will be set to 248. Setting /// will not take effect until next streaming session. AutoGainLimit = sys::rs2_option_RS2_OPTION_AUTO_GAIN_LIMIT as i32, /// Enable receiver sensitivity according to ambient light, bounded by the Receiver GAin /// control. AutoReceiverSensitivity = sys::rs2_option_RS2_OPTION_AUTO_RX_SENSITIVITY as i32, /// Changes the transmistter frequency frequencies increasing effective range over sharpness. TransmitterFrequency = sys::rs2_option_RS2_OPTION_TRANSMITTER_FREQUENCY as i32, /* Not included since this just tells us the total number of options. * * Count = sys::rs2_option_RS2_OPTION_COUNT, */ } impl Rs2Option { /// Get the option as a CStr. pub fn to_cstr(self) -> &'static CStr { unsafe { let ptr = sys::rs2_option_to_string(self as sys::rs2_option); CStr::from_ptr(ptr) } } /// Get the option as a str. pub fn to_str(self) -> &'static str { self.to_cstr().to_str().unwrap() } } impl ToString for Rs2Option { fn to_string(&self) -> String { self.to_str().to_owned() } } /// The range of available values of a supported option. pub struct Rs2OptionRange { /// The minimum value which will be accepted for this option pub min: f32, /// The maximum value which will be accepted for this option pub max: f32, /// The granularity of options which accept discrete values, or zero if the option accepts /// continuous values pub step: f32, /// The default value of the option pub default: f32, } #[cfg(test)] mod tests { use super::*; use num_traits::FromPrimitive; #[test] fn all_variants_exist()
} } }
{ let deprecated_options = vec![ sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_X as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_Y as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_ENABLED as i32, sys::rs2_option_RS2_OPTION_AMBIENT_LIGHT as i32, sys::rs2_option_RS2_OPTION_TRIGGER_CAMERA_ACCURACY_HEALTH as i32, sys::rs2_option_RS2_OPTION_RESET_CAMERA_ACCURACY_HEALTH as i32, ]; for i in 0..sys::rs2_option_RS2_OPTION_COUNT as i32 { if deprecated_options.iter().any(|x| x == &i) { continue; } assert!( Rs2Option::from_i32(i).is_some(), "Rs2Option variant for ordinal {} does not exist.", i, );
identifier_body
mixture.rs
use itertools::{ Either, EitherOrBoth::{Both, Left, Right}, Itertools, }; use std::{ cell::Cell, sync::atomic::{AtomicU64, Ordering::Relaxed}, }; use tinyvec::TinyVec; use crate::reaction::ReactionIdentifier; use super::{ constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasIDX, }; type SpecificFireInfo = (usize, f32, f32); struct VisHash(AtomicU64); impl Clone for VisHash { fn clone(&self) -> Self { VisHash(AtomicU64::new(self.0.load(Relaxed))) } } /// The data structure representing a Space Station 13 gas mixture. /// Unlike Monstermos, this doesn't have the archive built-in; instead, /// the archive is a feature of the turf grid, only existing during /// turf processing. /// Also missing is `last_share`; due to the usage of Rust, /// processing no longer requires sleeping turfs. Instead, we're using /// a proper, fully-simulated FDM system, much like LINDA but without /// sleeping turfs. #[derive(Clone)] pub struct Mixture { temperature: f32, pub volume: f32, min_heat_capacity: f32, immutable: bool, moles: TinyVec<[f32; 8]>, cached_heat_capacity: Cell<Option<f32>>, cached_vis_hash: VisHash, } /* Cell is not thread-safe. However, we use it only for caching heat capacity. The worst case race condition is thus thread A and B try to access heat capacity at the same time; both find that it's currently uncached, so both go to calculate it; both calculate it, and both calculate it to the same value, then one sets the cache to that value, then the other does. Technically, a worse one would be thread A mutates the gas mixture, changing a gas amount, while thread B tries to get its heat capacity; thread B finds a well-defined heat capacity, which is not correct, and uses it for a calculation, but this cannot happen: thread A would have a write lock, precluding thread B from accessing it. */ unsafe impl Sync for Mixture {} impl Default for Mixture { fn default() -> Self { Self::new() } } impl Mixture { /// Makes an empty gas mixture. pub fn new() -> Self { Self { moles: TinyVec::new(), temperature: 2.7, volume: 2500.0, min_heat_capacity: 0.0, immutable: false, cached_heat_capacity: Cell::new(None), cached_vis_hash: VisHash(AtomicU64::new(0)), } } /// Makes an empty gas mixture with the given volume. pub fn from_vol(vol: f32) -> Self { let mut ret = Self::new(); ret.volume = vol; ret } /// Returns if any data is corrupt. pub fn is_corrupt(&self) -> bool { !self.temperature.is_normal() || self.moles.len() > total_num_gases() } /// Fixes any corruption found. pub fn fix_corruption(&mut self) { self.garbage_collect(); if self.temperature < 2.7 ||!self.temperature.is_normal() { self.set_temperature(293.15); } } /// Returns the temperature of the mix. T pub fn get_temperature(&self) -> f32 { self.temperature } /// Sets the temperature, if the mix isn't immutable. T pub fn set_temperature(&mut self, temp: f32) { if!self.immutable && temp.is_normal() { self.temperature = temp; } } /// Sets the minimum heat capacity of this mix. pub fn set_min_heat_capacity(&mut self, amt: f32) { self.min_heat_capacity = amt; } /// Returns an iterator over the gas keys and mole amounts thereof. pub fn enumerate(&self) -> impl Iterator<Item = (GasIDX, f32)> + '_ { self.moles.iter().copied().enumerate() } /// Allows closures to iterate over each gas. pub fn for_each_gas( &self, mut f: impl FnMut(GasIDX, f32) -> Result<(), auxtools::Runtime>, ) -> Result<(), auxtools::Runtime> { for (i, g) in self.enumerate() { f(i, g)?; } Ok(()) } /// Returns (by value) the amount of moles of a given index the mix has. M pub fn get_moles(&self, idx: GasIDX) -> f32 { self.moles.get(idx).copied().unwrap_or(0.0) } /// Sets the mix to be internally immutable. Rust doesn't know about any of this, obviously. pub fn mark_immutable(&mut self) { self.immutable = true; } /// Returns whether this gas mixture is immutable. pub fn is_immutable(&self) -> bool { self.immutable } fn maybe_expand(&mut self, size: usize) { if self.moles.len() < size { self.moles.resize(size, 0.0); } } /// If mix is not immutable, sets the gas at the given `idx` to the given `amt`. pub fn set_moles(&mut self, idx: GasIDX, amt: f32) { if!self.immutable && idx < total_num_gases() && (idx <= self.moles.len() || (amt > GAS_MIN_MOLES && amt.is_normal())) { self.maybe_expand((idx + 1) as usize); unsafe { *self.moles.get_unchecked_mut(idx) = amt; }; self.cached_heat_capacity.set(None); } } pub fn adjust_moles(&mut self, idx: GasIDX, amt: f32) { if!self.immutable && amt.is_normal() && idx < total_num_gases() { self.maybe_expand((idx + 1) as usize); let r = unsafe { self.moles.get_unchecked_mut(idx) }; *r += amt; if amt < 0.0 { self.garbage_collect(); } self.cached_heat_capacity.set(None); } } #[inline(never)] // mostly this makes it so that heat_capacity itself is inlined fn slow_heat_capacity(&self) -> f32 { let heat_cap = with_specific_heats(|heats| { self.moles .iter() .copied() .zip(heats.iter()) .fold(0.0, |acc, (amt, cap)| cap.mul_add(amt, acc)) }) .max(self.min_heat_capacity); self.cached_heat_capacity.set(Some(heat_cap)); heat_cap } /// The heat capacity of the material. [joules?]/mole-kelvin. pub fn heat_capacity(&self) -> f32 { self.cached_heat_capacity .get() .filter(|cap| cap.is_finite() && cap.is_sign_positive()) .unwrap_or_else(|| self.slow_heat_capacity()) } /// Heat capacity of exactly one gas in this mix. pub fn partial_heat_capacity(&self, idx: GasIDX) -> f32 { self.moles .get(idx) .filter(|amt| amt.is_normal()) .map_or(0.0, |amt| amt * with_specific_heats(|heats| heats[idx])) } /// The total mole count of the mixture. Moles. pub fn total_moles(&self) -> f32 { self.moles.iter().sum() } /// Pressure. Kilopascals. pub fn return_pressure(&self) -> f32 { self.total_moles() * R_IDEAL_GAS_EQUATION * self.temperature / self.volume } /// Thermal energy. Joules? pub fn thermal_energy(&self) -> f32 { self.heat_capacity() * self.temperature } /// Merges one gas mixture into another. pub fn merge(&mut self, giver: &Self) { if self.immutable { return; } let our_heat_capacity = self.heat_capacity(); let other_heat_capacity = giver.heat_capacity(); self.maybe_expand(giver.moles.len()); for (a, b) in self.moles.iter_mut().zip(giver.moles.iter()) { *a += b; } let combined_heat_capacity = our_heat_capacity + other_heat_capacity; if combined_heat_capacity > MINIMUM_HEAT_CAPACITY { self.set_temperature( (our_heat_capacity * self.temperature + other_heat_capacity * giver.temperature) / (combined_heat_capacity), ); } self.cached_heat_capacity.set(Some(combined_heat_capacity)); } /// Transfers only the given gases from us to another mix. pub fn transfer_gases_to(&mut self, r: f32, gases: &[GasIDX], into: &mut Self) { let ratio = r.clamp(0.0, 1.0); let initial_energy = into.thermal_energy(); let mut heat_transfer = 0.0; with_specific_heats(|heats| { for i in gases.iter().copied() { if let Some(orig) = self.moles.get_mut(i) { let delta = *orig * ratio; heat_transfer += delta * self.temperature * heats[i]; *orig -= delta; into.adjust_moles(i, delta); } } }); self.cached_heat_capacity.set(None); into.cached_heat_capacity.set(None); into.set_temperature((initial_energy + heat_transfer) / into.heat_capacity()); } /// Takes a percentage of this gas mixture's moles and puts it into another mixture. if this mix is mutable, also removes those moles from the original. pub fn remove_ratio_into(&mut self, mut ratio: f32, into: &mut Self) { if ratio <= 0.0 { return; } if ratio >= 1.0 { ratio = 1.0; } let orig_temp = self.temperature; into.copy_from_mutable(self); into.multiply(ratio); self.multiply(1.0 - ratio); self.temperature = orig_temp; into.temperature = orig_temp; } /// As `remove_ratio_into`, but a raw number of moles instead of a ratio. pub fn remove_into(&mut self, amount: f32, into: &mut Self) { self.remove_ratio_into(amount / self.total_moles(), into); } /// A convenience function that makes the mixture for `remove_ratio_into` on the spot and returns it. pub fn remove_ratio(&mut self, ratio: f32) -> Self { let mut removed = Self::from_vol(self.volume); self.remove_ratio_into(ratio, &mut removed); removed } /// Like `remove_ratio`, but with moles. pub fn remove(&mut self, amount: f32) -> Self { self.remove_ratio(amount / self.total_moles()) } /// Copies from a given gas mixture, if we're mutable. pub fn copy_from_mutable(&mut self, sample: &Self) { if self.immutable { return; } self.moles = sample.moles.clone(); self.temperature = sample.temperature; self.cached_heat_capacity .set(sample.cached_heat_capacity.get()); } /// A very simple finite difference solution to the heat transfer equation. /// Works well enough for our purposes, though perhaps called less often /// than it ought to be while we're working in Rust. /// Differs from the original by not using archive, since we don't put the archive into the gas mix itself anymore. pub fn temperature_share(&mut self, sharer: &mut Self, conduction_coefficient: f32) -> f32 { let temperature_delta = self.temperature - sharer.temperature; if temperature_delta.abs() > MINIMUM_TEMPERATURE_DELTA_TO_CONSIDER { let self_heat_capacity = self.heat_capacity(); let sharer_heat_capacity = sharer.heat_capacity(); if sharer_heat_capacity > MINIMUM_HEAT_CAPACITY && self_heat_capacity > MINIMUM_HEAT_CAPACITY { let heat = conduction_coefficient * temperature_delta * (self_heat_capacity * sharer_heat_capacity / (self_heat_capacity + sharer_heat_capacity)); if!self.immutable { self.set_temperature((self.temperature - heat / self_heat_capacity).max(TCMB)); } if!sharer.immutable { sharer.set_temperature( (sharer.temperature + heat / sharer_heat_capacity).max(TCMB), ); } } } sharer.temperature } /// As above, but you may put in any arbitrary coefficient, temp, heat capacity. /// Only used for superconductivity as of right now. pub fn temperature_share_non_gas( &mut self, conduction_coefficient: f32, sharer_temperature: f32, sharer_heat_capacity: f32, ) -> f32 { let temperature_delta = self.temperature - sharer_temperature; if temperature_delta.abs() > MINIMUM_TEMPERATURE_DELTA_TO_CONSIDER { let self_heat_capacity = self.heat_capacity(); if sharer_heat_capacity > MINIMUM_HEAT_CAPACITY && self_heat_capacity > MINIMUM_HEAT_CAPACITY { let heat = conduction_coefficient * temperature_delta * (self_heat_capacity * sharer_heat_capacity / (self_heat_capacity + sharer_heat_capacity)); if!self.immutable { self.set_temperature((self.temperature - heat / self_heat_capacity).max(TCMB)); } return (sharer_temperature + heat / sharer_heat_capacity).max(TCMB); } } sharer_temperature } /// The second part of old compare(). Compares temperature, but only if this gas has sufficiently high moles. pub fn temperature_compare(&self, sample: &Self) -> bool { (self.get_temperature() - sample.get_temperature()).abs() > MINIMUM_TEMPERATURE_DELTA_TO_SUSPEND && (self.total_moles() > MINIMUM_MOLES_DELTA_TO_MOVE) } /// Returns the maximum mole delta for an individual gas. pub fn compare(&self, sample: &Self) -> f32 { self.moles .iter() .copied() .zip_longest(sample.moles.iter().copied()) .fold(0.0, |acc, pair| acc.max(pair.reduce(|a, b| (b - a).abs()))) } pub fn compare_with(&self, sample: &Self, amt: f32) -> bool { self.moles .as_slice() .iter() .zip_longest(sample.moles.as_slice().iter()) .rev() .any(|pair| match pair { Left(a) => a >= &amt, Right(b) => b >= &amt, Both(a, b) => a!= b && (a - b).abs() >= amt, }) } /// Clears the moles from the gas. pub fn clear(&mut self) { if!self.immutable { self.moles.clear(); self.cached_heat_capacity.set(None); } } /// Resets the gas mixture to an initialized-with-volume state. pub fn clear_with_vol(&mut self, vol: f32) { self.temperature = 2.7; self.volume = vol; self.min_heat_capacity = 0.0; self.immutable = false; self.clear(); } /// Multiplies every gas molage with this value. pub fn multiply(&mut self, multiplier: f32) { if!self.immutable { for amt in self.moles.iter_mut() { *amt *= multiplier; } self.cached_heat_capacity.set(None); self.garbage_collect(); } } /// Checks if the proc can react with any reactions. pub fn can_react(&self) -> bool { with_reactions(|reactions| reactions.iter().any(|r| r.check_conditions(self)))
reactions .iter() .filter_map(|r| r.check_conditions(self).then(|| r.get_id())) .collect() }) } /// Returns a tuple with oxidation power and fuel amount of this gas mixture. pub fn get_burnability(&self) -> (f32, f32) { use crate::types::FireInfo; super::with_gas_info(|gas_info| { self.moles .iter() .zip(gas_info) .fold((0.0, 0.0), |mut acc, (&amt, this_gas_info)| { if amt > GAS_MIN_MOLES { match this_gas_info.fire_info { FireInfo::Oxidation(oxidation) => { if self.temperature > oxidation.temperature() { let amount = amt * (1.0 - oxidation.temperature() / self.temperature) .max(0.0); acc.0 += amount * oxidation.power(); } } FireInfo::Fuel(fire) => { if self.temperature > fire.temperature() { let amount = amt * (1.0 - fire.temperature() / self.temperature).max(0.0); acc.1 += amount / fire.burn_rate(); } } FireInfo::None => (), } } acc }) }) } /// Returns only the oxidation power. Since this calculates burnability anyway, prefer `get_burnability`. pub fn get_oxidation_power(&self) -> f32 { self.get_burnability().0 } /// Returns only fuel amount. Since this calculates burnability anyway, prefer `get_burnability`. pub fn get_fuel_amount(&self) -> f32 { self.get_burnability().1 } /// Like `get_fire_info`, but takes a reference to a gas info vector, /// so one doesn't need to do a recursive lock on the global list. pub fn get_fire_info_with_lock( &self, gas_info: &[super::GasType], ) -> (Vec<SpecificFireInfo>, Vec<SpecificFireInfo>) { use crate::types::FireInfo; self.moles .iter() .zip(gas_info) .enumerate() .filter_map(|(i, (&amt, this_gas_info))| { (amt > GAS_MIN_MOLES) .then(|| match this_gas_info.fire_info { FireInfo::Oxidation(oxidation) => (self.get_temperature() > oxidation.temperature()) .then(|| { let amount = amt * (1.0 - oxidation.temperature() / self.get_temperature()).max(0.0); Either::Right((i, amount, amount * oxidation.power())) }), FireInfo::Fuel(fuel) => { (self.get_temperature() > fuel.temperature()).then(|| { let amount = amt * (1.0 - fuel.temperature() / self.get_temperature()).max(0.0); Either::Left((i, amount, amount / fuel.burn_rate())) }) } FireInfo::None => None, }) .flatten() }) .partition_map(|r| r) } /// Returns two vectors: /// The first contains all oxidizers in this list, as well as their actual mole amounts and how much fuel they can oxidize. /// The second contains all fuel sources in this list, as well as their actual mole amounts and how much oxidizer they can react with. pub fn get_fire_info(&self) -> (Vec<SpecificFireInfo>, Vec<SpecificFireInfo>) { super::with_gas_info(|gas_info| self.get_fire_info_with_lock(gas_info)) } /// Adds heat directly to the gas mixture, in joules (probably). pub fn adjust_heat(&mut self, heat: f32) { let cap = self.heat_capacity(); self.set_temperature(((cap * self.temperature) + heat) / cap); } /// Returns true if there's a visible gas in this mix. pub fn is_visible(&self) -> bool { self.enumerate() .any(|(i, gas)| gas_visibility(i as usize).map_or(false, |amt| gas >= amt)) } /// A hashed representation of the visibility of a gas, so that it only needs to update vis when actually changed. pub fn vis_hash_changed(&self, gas_visibility: &[Option<f32>]) -> bool { use std::hash::Hasher; let mut hasher: ahash::AHasher = ahash::AHasher::default(); for (i, gas) in self.enumerate() { if let Some(amt) = unsafe { gas_visibility.get_unchecked(i) }.filter(|&amt| gas >= amt) { hasher.write_usize(i); hasher.write_usize((FACTOR_GAS_VISIBLE_MAX).min((gas / amt).ceil()) as usize); } } let cur_hash = hasher.finish(); self.cached_vis_hash.0.swap(cur_hash, Relaxed)!= cur_hash } // Removes all redundant zeroes from the gas mixture. pub fn garbage_collect(&mut self) { let mut last_valid_found = 0; for (i, amt) in self.moles.iter_mut().enumerate() { if *amt > GAS_MIN_MOLES { last_valid_found = i; } else { *amt = 0.0; } } self.moles.truncate(last_valid_found + 1); } } use std::ops::{Add, Mul}; /// Takes a copy of the mix, merges the right hand side, then returns the copy. impl Add<&Mixture> for Mixture { type Output = Self; fn add(self, rhs: &Mixture) -> Self { let mut ret = self; ret.merge(rhs); ret } } /// Takes a copy of the mix, merges the right hand side, then returns the copy. impl<'a, 'b> Add<&'a Mixture> for &'b Mixture { type Output = Mixture; fn add(self, rhs: &Mixture) -> Mixture { let mut ret = self.clone(); ret.merge(rhs); ret } } /// Makes a copy of the given mix, multiplied by a scalar. impl Mul<f32> for Mixture { type Output = Self; fn mul(self, rhs: f32) -> Self { let mut ret = self; ret.multiply(rhs); ret } } /// Makes a copy of the given mix, multiplied by a scalar. impl<'a> Mul<f32> for &'a Mixture { type Output = Mixture; fn mul(self, rhs: f32) -> Mixture { let mut ret = self.clone(); ret.multiply(rhs); ret } } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let mut into = Mixture::new(); into.set_moles(0, 82.0); into.set_moles(1, 22.0); into.set_temperature(293.15); let mut source = Mixture::new(); source.set_moles(3, 100.0); source.set_temperature(313.15); into.merge(&source); // make sure that the merge successfuly moved the moles assert_eq!(into.get_moles(3), 100.0); assert_eq!(source.get_moles(3), 100.0); // source is not modified by merge /* make sure that the merge successfuly changed the temperature of the mix merged into: test gases have heat capacities of 2,080 and 20,000 respectively, so total thermal energies of 609,752 and 6,263,000 respectively once multiplied by temperatures. add those together, then divide by new total heat capacity: (609,752 + 6,263,000)/(2,080 + 20,000) = 6,872,752 / 2,2080 ~ 311.265942 so we compare to see if it's relatively close to 311.266, cause of floating point precision */ assert!( (into.get_temperature() - 311.266).abs() < 0.01, "{} should be near 311.266, is {}", into.get_temperature(), (into.get_temperature() - 311.266) ); } #[test] fn test_remove() { // also tests multiply, copy_from_mutable let mut removed = Mixture::new(); removed.set_moles(0, 22.0); removed.set_moles(1, 82.0); let new = removed.remove_ratio(0.5); assert_eq!(removed.compare(&new) >= MINIMUM_MOLES_DELTA_TO_MOVE, false); assert_eq!(removed.get_moles(0), 11.0); assert_eq!(removed.get_moles(1), 41.0); removed.mark_immutable(); let new_two = removed.remove_ratio(0.5); assert_eq!( removed.compare(&new_two) >= MINIMUM_MOLES_DELTA_TO_MOVE, true ); assert_eq!(removed.get_moles(0), 11.0); assert_eq!(removed.get_moles(1), 41.0); assert_eq!(new_two.get_moles(0), 5.5); } }
} /// Gets all of the reactions this mix should do. pub fn all_reactable(&self) -> Vec<ReactionIdentifier> { with_reactions(|reactions| {
random_line_split
mixture.rs
use itertools::{ Either, EitherOrBoth::{Both, Left, Right}, Itertools, }; use std::{ cell::Cell, sync::atomic::{AtomicU64, Ordering::Relaxed}, }; use tinyvec::TinyVec; use crate::reaction::ReactionIdentifier; use super::{ constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasIDX, }; type SpecificFireInfo = (usize, f32, f32); struct VisHash(AtomicU64); impl Clone for VisHash { fn clone(&self) -> Self { VisHash(AtomicU64::new(self.0.load(Relaxed))) } } /// The data structure representing a Space Station 13 gas mixture. /// Unlike Monstermos, this doesn't have the archive built-in; instead, /// the archive is a feature of the turf grid, only existing during /// turf processing. /// Also missing is `last_share`; due to the usage of Rust, /// processing no longer requires sleeping turfs. Instead, we're using /// a proper, fully-simulated FDM system, much like LINDA but without /// sleeping turfs. #[derive(Clone)] pub struct Mixture { temperature: f32, pub volume: f32, min_heat_capacity: f32, immutable: bool, moles: TinyVec<[f32; 8]>, cached_heat_capacity: Cell<Option<f32>>, cached_vis_hash: VisHash, } /* Cell is not thread-safe. However, we use it only for caching heat capacity. The worst case race condition is thus thread A and B try to access heat capacity at the same time; both find that it's currently uncached, so both go to calculate it; both calculate it, and both calculate it to the same value, then one sets the cache to that value, then the other does. Technically, a worse one would be thread A mutates the gas mixture, changing a gas amount, while thread B tries to get its heat capacity; thread B finds a well-defined heat capacity, which is not correct, and uses it for a calculation, but this cannot happen: thread A would have a write lock, precluding thread B from accessing it. */ unsafe impl Sync for Mixture {} impl Default for Mixture { fn default() -> Self { Self::new() } } impl Mixture { /// Makes an empty gas mixture. pub fn new() -> Self { Self { moles: TinyVec::new(), temperature: 2.7, volume: 2500.0, min_heat_capacity: 0.0, immutable: false, cached_heat_capacity: Cell::new(None), cached_vis_hash: VisHash(AtomicU64::new(0)), } } /// Makes an empty gas mixture with the given volume. pub fn from_vol(vol: f32) -> Self { let mut ret = Self::new(); ret.volume = vol; ret } /// Returns if any data is corrupt. pub fn is_corrupt(&self) -> bool { !self.temperature.is_normal() || self.moles.len() > total_num_gases() } /// Fixes any corruption found. pub fn fix_corruption(&mut self) { self.garbage_collect(); if self.temperature < 2.7 ||!self.temperature.is_normal() { self.set_temperature(293.15); } } /// Returns the temperature of the mix. T pub fn get_temperature(&self) -> f32 { self.temperature } /// Sets the temperature, if the mix isn't immutable. T pub fn set_temperature(&mut self, temp: f32) { if!self.immutable && temp.is_normal() { self.temperature = temp; } } /// Sets the minimum heat capacity of this mix. pub fn set_min_heat_capacity(&mut self, amt: f32) { self.min_heat_capacity = amt; } /// Returns an iterator over the gas keys and mole amounts thereof. pub fn enumerate(&self) -> impl Iterator<Item = (GasIDX, f32)> + '_ { self.moles.iter().copied().enumerate() } /// Allows closures to iterate over each gas. pub fn for_each_gas( &self, mut f: impl FnMut(GasIDX, f32) -> Result<(), auxtools::Runtime>, ) -> Result<(), auxtools::Runtime> { for (i, g) in self.enumerate() { f(i, g)?; } Ok(()) } /// Returns (by value) the amount of moles of a given index the mix has. M pub fn get_moles(&self, idx: GasIDX) -> f32 { self.moles.get(idx).copied().unwrap_or(0.0) } /// Sets the mix to be internally immutable. Rust doesn't know about any of this, obviously. pub fn mark_immutable(&mut self) { self.immutable = true; } /// Returns whether this gas mixture is immutable. pub fn is_immutable(&self) -> bool { self.immutable } fn maybe_expand(&mut self, size: usize) { if self.moles.len() < size { self.moles.resize(size, 0.0); } } /// If mix is not immutable, sets the gas at the given `idx` to the given `amt`. pub fn set_moles(&mut self, idx: GasIDX, amt: f32) { if!self.immutable && idx < total_num_gases() && (idx <= self.moles.len() || (amt > GAS_MIN_MOLES && amt.is_normal())) { self.maybe_expand((idx + 1) as usize); unsafe { *self.moles.get_unchecked_mut(idx) = amt; }; self.cached_heat_capacity.set(None); } } pub fn adjust_moles(&mut self, idx: GasIDX, amt: f32) { if!self.immutable && amt.is_normal() && idx < total_num_gases() { self.maybe_expand((idx + 1) as usize); let r = unsafe { self.moles.get_unchecked_mut(idx) }; *r += amt; if amt < 0.0 { self.garbage_collect(); } self.cached_heat_capacity.set(None); } } #[inline(never)] // mostly this makes it so that heat_capacity itself is inlined fn slow_heat_capacity(&self) -> f32 { let heat_cap = with_specific_heats(|heats| { self.moles .iter() .copied() .zip(heats.iter()) .fold(0.0, |acc, (amt, cap)| cap.mul_add(amt, acc)) }) .max(self.min_heat_capacity); self.cached_heat_capacity.set(Some(heat_cap)); heat_cap } /// The heat capacity of the material. [joules?]/mole-kelvin. pub fn heat_capacity(&self) -> f32 { self.cached_heat_capacity .get() .filter(|cap| cap.is_finite() && cap.is_sign_positive()) .unwrap_or_else(|| self.slow_heat_capacity()) } /// Heat capacity of exactly one gas in this mix. pub fn partial_heat_capacity(&self, idx: GasIDX) -> f32 { self.moles .get(idx) .filter(|amt| amt.is_normal()) .map_or(0.0, |amt| amt * with_specific_heats(|heats| heats[idx])) } /// The total mole count of the mixture. Moles. pub fn total_moles(&self) -> f32 { self.moles.iter().sum() } /// Pressure. Kilopascals. pub fn return_pressure(&self) -> f32 { self.total_moles() * R_IDEAL_GAS_EQUATION * self.temperature / self.volume } /// Thermal energy. Joules? pub fn thermal_energy(&self) -> f32 { self.heat_capacity() * self.temperature } /// Merges one gas mixture into another. pub fn merge(&mut self, giver: &Self) { if self.immutable { return; } let our_heat_capacity = self.heat_capacity(); let other_heat_capacity = giver.heat_capacity(); self.maybe_expand(giver.moles.len()); for (a, b) in self.moles.iter_mut().zip(giver.moles.iter()) { *a += b; } let combined_heat_capacity = our_heat_capacity + other_heat_capacity; if combined_heat_capacity > MINIMUM_HEAT_CAPACITY { self.set_temperature( (our_heat_capacity * self.temperature + other_heat_capacity * giver.temperature) / (combined_heat_capacity), ); } self.cached_heat_capacity.set(Some(combined_heat_capacity)); } /// Transfers only the given gases from us to another mix. pub fn transfer_gases_to(&mut self, r: f32, gases: &[GasIDX], into: &mut Self) { let ratio = r.clamp(0.0, 1.0); let initial_energy = into.thermal_energy(); let mut heat_transfer = 0.0; with_specific_heats(|heats| { for i in gases.iter().copied() { if let Some(orig) = self.moles.get_mut(i) { let delta = *orig * ratio; heat_transfer += delta * self.temperature * heats[i]; *orig -= delta; into.adjust_moles(i, delta); } } }); self.cached_heat_capacity.set(None); into.cached_heat_capacity.set(None); into.set_temperature((initial_energy + heat_transfer) / into.heat_capacity()); } /// Takes a percentage of this gas mixture's moles and puts it into another mixture. if this mix is mutable, also removes those moles from the original. pub fn remove_ratio_into(&mut self, mut ratio: f32, into: &mut Self) { if ratio <= 0.0 { return; } if ratio >= 1.0 { ratio = 1.0; } let orig_temp = self.temperature; into.copy_from_mutable(self); into.multiply(ratio); self.multiply(1.0 - ratio); self.temperature = orig_temp; into.temperature = orig_temp; } /// As `remove_ratio_into`, but a raw number of moles instead of a ratio. pub fn remove_into(&mut self, amount: f32, into: &mut Self) { self.remove_ratio_into(amount / self.total_moles(), into); } /// A convenience function that makes the mixture for `remove_ratio_into` on the spot and returns it. pub fn remove_ratio(&mut self, ratio: f32) -> Self { let mut removed = Self::from_vol(self.volume); self.remove_ratio_into(ratio, &mut removed); removed } /// Like `remove_ratio`, but with moles. pub fn remove(&mut self, amount: f32) -> Self { self.remove_ratio(amount / self.total_moles()) } /// Copies from a given gas mixture, if we're mutable. pub fn copy_from_mutable(&mut self, sample: &Self) { if self.immutable { return; } self.moles = sample.moles.clone(); self.temperature = sample.temperature; self.cached_heat_capacity .set(sample.cached_heat_capacity.get()); } /// A very simple finite difference solution to the heat transfer equation. /// Works well enough for our purposes, though perhaps called less often /// than it ought to be while we're working in Rust. /// Differs from the original by not using archive, since we don't put the archive into the gas mix itself anymore. pub fn temperature_share(&mut self, sharer: &mut Self, conduction_coefficient: f32) -> f32 { let temperature_delta = self.temperature - sharer.temperature; if temperature_delta.abs() > MINIMUM_TEMPERATURE_DELTA_TO_CONSIDER { let self_heat_capacity = self.heat_capacity(); let sharer_heat_capacity = sharer.heat_capacity(); if sharer_heat_capacity > MINIMUM_HEAT_CAPACITY && self_heat_capacity > MINIMUM_HEAT_CAPACITY { let heat = conduction_coefficient * temperature_delta * (self_heat_capacity * sharer_heat_capacity / (self_heat_capacity + sharer_heat_capacity)); if!self.immutable { self.set_temperature((self.temperature - heat / self_heat_capacity).max(TCMB)); } if!sharer.immutable { sharer.set_temperature( (sharer.temperature + heat / sharer_heat_capacity).max(TCMB), ); } } } sharer.temperature } /// As above, but you may put in any arbitrary coefficient, temp, heat capacity. /// Only used for superconductivity as of right now. pub fn temperature_share_non_gas( &mut self, conduction_coefficient: f32, sharer_temperature: f32, sharer_heat_capacity: f32, ) -> f32 { let temperature_delta = self.temperature - sharer_temperature; if temperature_delta.abs() > MINIMUM_TEMPERATURE_DELTA_TO_CONSIDER { let self_heat_capacity = self.heat_capacity(); if sharer_heat_capacity > MINIMUM_HEAT_CAPACITY && self_heat_capacity > MINIMUM_HEAT_CAPACITY { let heat = conduction_coefficient * temperature_delta * (self_heat_capacity * sharer_heat_capacity / (self_heat_capacity + sharer_heat_capacity)); if!self.immutable { self.set_temperature((self.temperature - heat / self_heat_capacity).max(TCMB)); } return (sharer_temperature + heat / sharer_heat_capacity).max(TCMB); } } sharer_temperature } /// The second part of old compare(). Compares temperature, but only if this gas has sufficiently high moles. pub fn temperature_compare(&self, sample: &Self) -> bool { (self.get_temperature() - sample.get_temperature()).abs() > MINIMUM_TEMPERATURE_DELTA_TO_SUSPEND && (self.total_moles() > MINIMUM_MOLES_DELTA_TO_MOVE) } /// Returns the maximum mole delta for an individual gas. pub fn compare(&self, sample: &Self) -> f32 { self.moles .iter() .copied() .zip_longest(sample.moles.iter().copied()) .fold(0.0, |acc, pair| acc.max(pair.reduce(|a, b| (b - a).abs()))) } pub fn compare_with(&self, sample: &Self, amt: f32) -> bool { self.moles .as_slice() .iter() .zip_longest(sample.moles.as_slice().iter()) .rev() .any(|pair| match pair { Left(a) => a >= &amt, Right(b) => b >= &amt, Both(a, b) => a!= b && (a - b).abs() >= amt, }) } /// Clears the moles from the gas. pub fn clear(&mut self) { if!self.immutable { self.moles.clear(); self.cached_heat_capacity.set(None); } } /// Resets the gas mixture to an initialized-with-volume state. pub fn clear_with_vol(&mut self, vol: f32) { self.temperature = 2.7; self.volume = vol; self.min_heat_capacity = 0.0; self.immutable = false; self.clear(); } /// Multiplies every gas molage with this value. pub fn multiply(&mut self, multiplier: f32) { if!self.immutable { for amt in self.moles.iter_mut() { *amt *= multiplier; } self.cached_heat_capacity.set(None); self.garbage_collect(); } } /// Checks if the proc can react with any reactions. pub fn can_react(&self) -> bool { with_reactions(|reactions| reactions.iter().any(|r| r.check_conditions(self))) } /// Gets all of the reactions this mix should do. pub fn all_reactable(&self) -> Vec<ReactionIdentifier> { with_reactions(|reactions| { reactions .iter() .filter_map(|r| r.check_conditions(self).then(|| r.get_id())) .collect() }) } /// Returns a tuple with oxidation power and fuel amount of this gas mixture. pub fn get_burnability(&self) -> (f32, f32) { use crate::types::FireInfo; super::with_gas_info(|gas_info| { self.moles .iter() .zip(gas_info) .fold((0.0, 0.0), |mut acc, (&amt, this_gas_info)| { if amt > GAS_MIN_MOLES { match this_gas_info.fire_info { FireInfo::Oxidation(oxidation) =>
FireInfo::Fuel(fire) => { if self.temperature > fire.temperature() { let amount = amt * (1.0 - fire.temperature() / self.temperature).max(0.0); acc.1 += amount / fire.burn_rate(); } } FireInfo::None => (), } } acc }) }) } /// Returns only the oxidation power. Since this calculates burnability anyway, prefer `get_burnability`. pub fn get_oxidation_power(&self) -> f32 { self.get_burnability().0 } /// Returns only fuel amount. Since this calculates burnability anyway, prefer `get_burnability`. pub fn get_fuel_amount(&self) -> f32 { self.get_burnability().1 } /// Like `get_fire_info`, but takes a reference to a gas info vector, /// so one doesn't need to do a recursive lock on the global list. pub fn get_fire_info_with_lock( &self, gas_info: &[super::GasType], ) -> (Vec<SpecificFireInfo>, Vec<SpecificFireInfo>) { use crate::types::FireInfo; self.moles .iter() .zip(gas_info) .enumerate() .filter_map(|(i, (&amt, this_gas_info))| { (amt > GAS_MIN_MOLES) .then(|| match this_gas_info.fire_info { FireInfo::Oxidation(oxidation) => (self.get_temperature() > oxidation.temperature()) .then(|| { let amount = amt * (1.0 - oxidation.temperature() / self.get_temperature()).max(0.0); Either::Right((i, amount, amount * oxidation.power())) }), FireInfo::Fuel(fuel) => { (self.get_temperature() > fuel.temperature()).then(|| { let amount = amt * (1.0 - fuel.temperature() / self.get_temperature()).max(0.0); Either::Left((i, amount, amount / fuel.burn_rate())) }) } FireInfo::None => None, }) .flatten() }) .partition_map(|r| r) } /// Returns two vectors: /// The first contains all oxidizers in this list, as well as their actual mole amounts and how much fuel they can oxidize. /// The second contains all fuel sources in this list, as well as their actual mole amounts and how much oxidizer they can react with. pub fn get_fire_info(&self) -> (Vec<SpecificFireInfo>, Vec<SpecificFireInfo>) { super::with_gas_info(|gas_info| self.get_fire_info_with_lock(gas_info)) } /// Adds heat directly to the gas mixture, in joules (probably). pub fn adjust_heat(&mut self, heat: f32) { let cap = self.heat_capacity(); self.set_temperature(((cap * self.temperature) + heat) / cap); } /// Returns true if there's a visible gas in this mix. pub fn is_visible(&self) -> bool { self.enumerate() .any(|(i, gas)| gas_visibility(i as usize).map_or(false, |amt| gas >= amt)) } /// A hashed representation of the visibility of a gas, so that it only needs to update vis when actually changed. pub fn vis_hash_changed(&self, gas_visibility: &[Option<f32>]) -> bool { use std::hash::Hasher; let mut hasher: ahash::AHasher = ahash::AHasher::default(); for (i, gas) in self.enumerate() { if let Some(amt) = unsafe { gas_visibility.get_unchecked(i) }.filter(|&amt| gas >= amt) { hasher.write_usize(i); hasher.write_usize((FACTOR_GAS_VISIBLE_MAX).min((gas / amt).ceil()) as usize); } } let cur_hash = hasher.finish(); self.cached_vis_hash.0.swap(cur_hash, Relaxed)!= cur_hash } // Removes all redundant zeroes from the gas mixture. pub fn garbage_collect(&mut self) { let mut last_valid_found = 0; for (i, amt) in self.moles.iter_mut().enumerate() { if *amt > GAS_MIN_MOLES { last_valid_found = i; } else { *amt = 0.0; } } self.moles.truncate(last_valid_found + 1); } } use std::ops::{Add, Mul}; /// Takes a copy of the mix, merges the right hand side, then returns the copy. impl Add<&Mixture> for Mixture { type Output = Self; fn add(self, rhs: &Mixture) -> Self { let mut ret = self; ret.merge(rhs); ret } } /// Takes a copy of the mix, merges the right hand side, then returns the copy. impl<'a, 'b> Add<&'a Mixture> for &'b Mixture { type Output = Mixture; fn add(self, rhs: &Mixture) -> Mixture { let mut ret = self.clone(); ret.merge(rhs); ret } } /// Makes a copy of the given mix, multiplied by a scalar. impl Mul<f32> for Mixture { type Output = Self; fn mul(self, rhs: f32) -> Self { let mut ret = self; ret.multiply(rhs); ret } } /// Makes a copy of the given mix, multiplied by a scalar. impl<'a> Mul<f32> for &'a Mixture { type Output = Mixture; fn mul(self, rhs: f32) -> Mixture { let mut ret = self.clone(); ret.multiply(rhs); ret } } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let mut into = Mixture::new(); into.set_moles(0, 82.0); into.set_moles(1, 22.0); into.set_temperature(293.15); let mut source = Mixture::new(); source.set_moles(3, 100.0); source.set_temperature(313.15); into.merge(&source); // make sure that the merge successfuly moved the moles assert_eq!(into.get_moles(3), 100.0); assert_eq!(source.get_moles(3), 100.0); // source is not modified by merge /* make sure that the merge successfuly changed the temperature of the mix merged into: test gases have heat capacities of 2,080 and 20,000 respectively, so total thermal energies of 609,752 and 6,263,000 respectively once multiplied by temperatures. add those together, then divide by new total heat capacity: (609,752 + 6,263,000)/(2,080 + 20,000) = 6,872,752 / 2,2080 ~ 311.265942 so we compare to see if it's relatively close to 311.266, cause of floating point precision */ assert!( (into.get_temperature() - 311.266).abs() < 0.01, "{} should be near 311.266, is {}", into.get_temperature(), (into.get_temperature() - 311.266) ); } #[test] fn test_remove() { // also tests multiply, copy_from_mutable let mut removed = Mixture::new(); removed.set_moles(0, 22.0); removed.set_moles(1, 82.0); let new = removed.remove_ratio(0.5); assert_eq!(removed.compare(&new) >= MINIMUM_MOLES_DELTA_TO_MOVE, false); assert_eq!(removed.get_moles(0), 11.0); assert_eq!(removed.get_moles(1), 41.0); removed.mark_immutable(); let new_two = removed.remove_ratio(0.5); assert_eq!( removed.compare(&new_two) >= MINIMUM_MOLES_DELTA_TO_MOVE, true ); assert_eq!(removed.get_moles(0), 11.0); assert_eq!(removed.get_moles(1), 41.0); assert_eq!(new_two.get_moles(0), 5.5); } }
{ if self.temperature > oxidation.temperature() { let amount = amt * (1.0 - oxidation.temperature() / self.temperature) .max(0.0); acc.0 += amount * oxidation.power(); } }
conditional_block
mixture.rs
use itertools::{ Either, EitherOrBoth::{Both, Left, Right}, Itertools, }; use std::{ cell::Cell, sync::atomic::{AtomicU64, Ordering::Relaxed}, }; use tinyvec::TinyVec; use crate::reaction::ReactionIdentifier; use super::{ constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasIDX, }; type SpecificFireInfo = (usize, f32, f32); struct VisHash(AtomicU64); impl Clone for VisHash { fn clone(&self) -> Self { VisHash(AtomicU64::new(self.0.load(Relaxed))) } } /// The data structure representing a Space Station 13 gas mixture. /// Unlike Monstermos, this doesn't have the archive built-in; instead, /// the archive is a feature of the turf grid, only existing during /// turf processing. /// Also missing is `last_share`; due to the usage of Rust, /// processing no longer requires sleeping turfs. Instead, we're using /// a proper, fully-simulated FDM system, much like LINDA but without /// sleeping turfs. #[derive(Clone)] pub struct Mixture { temperature: f32, pub volume: f32, min_heat_capacity: f32, immutable: bool, moles: TinyVec<[f32; 8]>, cached_heat_capacity: Cell<Option<f32>>, cached_vis_hash: VisHash, } /* Cell is not thread-safe. However, we use it only for caching heat capacity. The worst case race condition is thus thread A and B try to access heat capacity at the same time; both find that it's currently uncached, so both go to calculate it; both calculate it, and both calculate it to the same value, then one sets the cache to that value, then the other does. Technically, a worse one would be thread A mutates the gas mixture, changing a gas amount, while thread B tries to get its heat capacity; thread B finds a well-defined heat capacity, which is not correct, and uses it for a calculation, but this cannot happen: thread A would have a write lock, precluding thread B from accessing it. */ unsafe impl Sync for Mixture {} impl Default for Mixture { fn default() -> Self { Self::new() } } impl Mixture { /// Makes an empty gas mixture. pub fn new() -> Self { Self { moles: TinyVec::new(), temperature: 2.7, volume: 2500.0, min_heat_capacity: 0.0, immutable: false, cached_heat_capacity: Cell::new(None), cached_vis_hash: VisHash(AtomicU64::new(0)), } } /// Makes an empty gas mixture with the given volume. pub fn from_vol(vol: f32) -> Self { let mut ret = Self::new(); ret.volume = vol; ret } /// Returns if any data is corrupt. pub fn is_corrupt(&self) -> bool { !self.temperature.is_normal() || self.moles.len() > total_num_gases() } /// Fixes any corruption found. pub fn fix_corruption(&mut self) { self.garbage_collect(); if self.temperature < 2.7 ||!self.temperature.is_normal() { self.set_temperature(293.15); } } /// Returns the temperature of the mix. T pub fn get_temperature(&self) -> f32 { self.temperature } /// Sets the temperature, if the mix isn't immutable. T pub fn set_temperature(&mut self, temp: f32) { if!self.immutable && temp.is_normal() { self.temperature = temp; } } /// Sets the minimum heat capacity of this mix. pub fn set_min_heat_capacity(&mut self, amt: f32) { self.min_heat_capacity = amt; } /// Returns an iterator over the gas keys and mole amounts thereof. pub fn enumerate(&self) -> impl Iterator<Item = (GasIDX, f32)> + '_ { self.moles.iter().copied().enumerate() } /// Allows closures to iterate over each gas. pub fn for_each_gas( &self, mut f: impl FnMut(GasIDX, f32) -> Result<(), auxtools::Runtime>, ) -> Result<(), auxtools::Runtime> { for (i, g) in self.enumerate() { f(i, g)?; } Ok(()) } /// Returns (by value) the amount of moles of a given index the mix has. M pub fn get_moles(&self, idx: GasIDX) -> f32 { self.moles.get(idx).copied().unwrap_or(0.0) } /// Sets the mix to be internally immutable. Rust doesn't know about any of this, obviously. pub fn mark_immutable(&mut self) { self.immutable = true; } /// Returns whether this gas mixture is immutable. pub fn is_immutable(&self) -> bool { self.immutable } fn maybe_expand(&mut self, size: usize) { if self.moles.len() < size { self.moles.resize(size, 0.0); } } /// If mix is not immutable, sets the gas at the given `idx` to the given `amt`. pub fn set_moles(&mut self, idx: GasIDX, amt: f32) { if!self.immutable && idx < total_num_gases() && (idx <= self.moles.len() || (amt > GAS_MIN_MOLES && amt.is_normal())) { self.maybe_expand((idx + 1) as usize); unsafe { *self.moles.get_unchecked_mut(idx) = amt; }; self.cached_heat_capacity.set(None); } } pub fn adjust_moles(&mut self, idx: GasIDX, amt: f32) { if!self.immutable && amt.is_normal() && idx < total_num_gases() { self.maybe_expand((idx + 1) as usize); let r = unsafe { self.moles.get_unchecked_mut(idx) }; *r += amt; if amt < 0.0 { self.garbage_collect(); } self.cached_heat_capacity.set(None); } } #[inline(never)] // mostly this makes it so that heat_capacity itself is inlined fn slow_heat_capacity(&self) -> f32 { let heat_cap = with_specific_heats(|heats| { self.moles .iter() .copied() .zip(heats.iter()) .fold(0.0, |acc, (amt, cap)| cap.mul_add(amt, acc)) }) .max(self.min_heat_capacity); self.cached_heat_capacity.set(Some(heat_cap)); heat_cap } /// The heat capacity of the material. [joules?]/mole-kelvin. pub fn heat_capacity(&self) -> f32 { self.cached_heat_capacity .get() .filter(|cap| cap.is_finite() && cap.is_sign_positive()) .unwrap_or_else(|| self.slow_heat_capacity()) } /// Heat capacity of exactly one gas in this mix. pub fn partial_heat_capacity(&self, idx: GasIDX) -> f32 { self.moles .get(idx) .filter(|amt| amt.is_normal()) .map_or(0.0, |amt| amt * with_specific_heats(|heats| heats[idx])) } /// The total mole count of the mixture. Moles. pub fn total_moles(&self) -> f32 { self.moles.iter().sum() } /// Pressure. Kilopascals. pub fn return_pressure(&self) -> f32 { self.total_moles() * R_IDEAL_GAS_EQUATION * self.temperature / self.volume } /// Thermal energy. Joules? pub fn thermal_energy(&self) -> f32
/// Merges one gas mixture into another. pub fn merge(&mut self, giver: &Self) { if self.immutable { return; } let our_heat_capacity = self.heat_capacity(); let other_heat_capacity = giver.heat_capacity(); self.maybe_expand(giver.moles.len()); for (a, b) in self.moles.iter_mut().zip(giver.moles.iter()) { *a += b; } let combined_heat_capacity = our_heat_capacity + other_heat_capacity; if combined_heat_capacity > MINIMUM_HEAT_CAPACITY { self.set_temperature( (our_heat_capacity * self.temperature + other_heat_capacity * giver.temperature) / (combined_heat_capacity), ); } self.cached_heat_capacity.set(Some(combined_heat_capacity)); } /// Transfers only the given gases from us to another mix. pub fn transfer_gases_to(&mut self, r: f32, gases: &[GasIDX], into: &mut Self) { let ratio = r.clamp(0.0, 1.0); let initial_energy = into.thermal_energy(); let mut heat_transfer = 0.0; with_specific_heats(|heats| { for i in gases.iter().copied() { if let Some(orig) = self.moles.get_mut(i) { let delta = *orig * ratio; heat_transfer += delta * self.temperature * heats[i]; *orig -= delta; into.adjust_moles(i, delta); } } }); self.cached_heat_capacity.set(None); into.cached_heat_capacity.set(None); into.set_temperature((initial_energy + heat_transfer) / into.heat_capacity()); } /// Takes a percentage of this gas mixture's moles and puts it into another mixture. if this mix is mutable, also removes those moles from the original. pub fn remove_ratio_into(&mut self, mut ratio: f32, into: &mut Self) { if ratio <= 0.0 { return; } if ratio >= 1.0 { ratio = 1.0; } let orig_temp = self.temperature; into.copy_from_mutable(self); into.multiply(ratio); self.multiply(1.0 - ratio); self.temperature = orig_temp; into.temperature = orig_temp; } /// As `remove_ratio_into`, but a raw number of moles instead of a ratio. pub fn remove_into(&mut self, amount: f32, into: &mut Self) { self.remove_ratio_into(amount / self.total_moles(), into); } /// A convenience function that makes the mixture for `remove_ratio_into` on the spot and returns it. pub fn remove_ratio(&mut self, ratio: f32) -> Self { let mut removed = Self::from_vol(self.volume); self.remove_ratio_into(ratio, &mut removed); removed } /// Like `remove_ratio`, but with moles. pub fn remove(&mut self, amount: f32) -> Self { self.remove_ratio(amount / self.total_moles()) } /// Copies from a given gas mixture, if we're mutable. pub fn copy_from_mutable(&mut self, sample: &Self) { if self.immutable { return; } self.moles = sample.moles.clone(); self.temperature = sample.temperature; self.cached_heat_capacity .set(sample.cached_heat_capacity.get()); } /// A very simple finite difference solution to the heat transfer equation. /// Works well enough for our purposes, though perhaps called less often /// than it ought to be while we're working in Rust. /// Differs from the original by not using archive, since we don't put the archive into the gas mix itself anymore. pub fn temperature_share(&mut self, sharer: &mut Self, conduction_coefficient: f32) -> f32 { let temperature_delta = self.temperature - sharer.temperature; if temperature_delta.abs() > MINIMUM_TEMPERATURE_DELTA_TO_CONSIDER { let self_heat_capacity = self.heat_capacity(); let sharer_heat_capacity = sharer.heat_capacity(); if sharer_heat_capacity > MINIMUM_HEAT_CAPACITY && self_heat_capacity > MINIMUM_HEAT_CAPACITY { let heat = conduction_coefficient * temperature_delta * (self_heat_capacity * sharer_heat_capacity / (self_heat_capacity + sharer_heat_capacity)); if!self.immutable { self.set_temperature((self.temperature - heat / self_heat_capacity).max(TCMB)); } if!sharer.immutable { sharer.set_temperature( (sharer.temperature + heat / sharer_heat_capacity).max(TCMB), ); } } } sharer.temperature } /// As above, but you may put in any arbitrary coefficient, temp, heat capacity. /// Only used for superconductivity as of right now. pub fn temperature_share_non_gas( &mut self, conduction_coefficient: f32, sharer_temperature: f32, sharer_heat_capacity: f32, ) -> f32 { let temperature_delta = self.temperature - sharer_temperature; if temperature_delta.abs() > MINIMUM_TEMPERATURE_DELTA_TO_CONSIDER { let self_heat_capacity = self.heat_capacity(); if sharer_heat_capacity > MINIMUM_HEAT_CAPACITY && self_heat_capacity > MINIMUM_HEAT_CAPACITY { let heat = conduction_coefficient * temperature_delta * (self_heat_capacity * sharer_heat_capacity / (self_heat_capacity + sharer_heat_capacity)); if!self.immutable { self.set_temperature((self.temperature - heat / self_heat_capacity).max(TCMB)); } return (sharer_temperature + heat / sharer_heat_capacity).max(TCMB); } } sharer_temperature } /// The second part of old compare(). Compares temperature, but only if this gas has sufficiently high moles. pub fn temperature_compare(&self, sample: &Self) -> bool { (self.get_temperature() - sample.get_temperature()).abs() > MINIMUM_TEMPERATURE_DELTA_TO_SUSPEND && (self.total_moles() > MINIMUM_MOLES_DELTA_TO_MOVE) } /// Returns the maximum mole delta for an individual gas. pub fn compare(&self, sample: &Self) -> f32 { self.moles .iter() .copied() .zip_longest(sample.moles.iter().copied()) .fold(0.0, |acc, pair| acc.max(pair.reduce(|a, b| (b - a).abs()))) } pub fn compare_with(&self, sample: &Self, amt: f32) -> bool { self.moles .as_slice() .iter() .zip_longest(sample.moles.as_slice().iter()) .rev() .any(|pair| match pair { Left(a) => a >= &amt, Right(b) => b >= &amt, Both(a, b) => a!= b && (a - b).abs() >= amt, }) } /// Clears the moles from the gas. pub fn clear(&mut self) { if!self.immutable { self.moles.clear(); self.cached_heat_capacity.set(None); } } /// Resets the gas mixture to an initialized-with-volume state. pub fn clear_with_vol(&mut self, vol: f32) { self.temperature = 2.7; self.volume = vol; self.min_heat_capacity = 0.0; self.immutable = false; self.clear(); } /// Multiplies every gas molage with this value. pub fn multiply(&mut self, multiplier: f32) { if!self.immutable { for amt in self.moles.iter_mut() { *amt *= multiplier; } self.cached_heat_capacity.set(None); self.garbage_collect(); } } /// Checks if the proc can react with any reactions. pub fn can_react(&self) -> bool { with_reactions(|reactions| reactions.iter().any(|r| r.check_conditions(self))) } /// Gets all of the reactions this mix should do. pub fn all_reactable(&self) -> Vec<ReactionIdentifier> { with_reactions(|reactions| { reactions .iter() .filter_map(|r| r.check_conditions(self).then(|| r.get_id())) .collect() }) } /// Returns a tuple with oxidation power and fuel amount of this gas mixture. pub fn get_burnability(&self) -> (f32, f32) { use crate::types::FireInfo; super::with_gas_info(|gas_info| { self.moles .iter() .zip(gas_info) .fold((0.0, 0.0), |mut acc, (&amt, this_gas_info)| { if amt > GAS_MIN_MOLES { match this_gas_info.fire_info { FireInfo::Oxidation(oxidation) => { if self.temperature > oxidation.temperature() { let amount = amt * (1.0 - oxidation.temperature() / self.temperature) .max(0.0); acc.0 += amount * oxidation.power(); } } FireInfo::Fuel(fire) => { if self.temperature > fire.temperature() { let amount = amt * (1.0 - fire.temperature() / self.temperature).max(0.0); acc.1 += amount / fire.burn_rate(); } } FireInfo::None => (), } } acc }) }) } /// Returns only the oxidation power. Since this calculates burnability anyway, prefer `get_burnability`. pub fn get_oxidation_power(&self) -> f32 { self.get_burnability().0 } /// Returns only fuel amount. Since this calculates burnability anyway, prefer `get_burnability`. pub fn get_fuel_amount(&self) -> f32 { self.get_burnability().1 } /// Like `get_fire_info`, but takes a reference to a gas info vector, /// so one doesn't need to do a recursive lock on the global list. pub fn get_fire_info_with_lock( &self, gas_info: &[super::GasType], ) -> (Vec<SpecificFireInfo>, Vec<SpecificFireInfo>) { use crate::types::FireInfo; self.moles .iter() .zip(gas_info) .enumerate() .filter_map(|(i, (&amt, this_gas_info))| { (amt > GAS_MIN_MOLES) .then(|| match this_gas_info.fire_info { FireInfo::Oxidation(oxidation) => (self.get_temperature() > oxidation.temperature()) .then(|| { let amount = amt * (1.0 - oxidation.temperature() / self.get_temperature()).max(0.0); Either::Right((i, amount, amount * oxidation.power())) }), FireInfo::Fuel(fuel) => { (self.get_temperature() > fuel.temperature()).then(|| { let amount = amt * (1.0 - fuel.temperature() / self.get_temperature()).max(0.0); Either::Left((i, amount, amount / fuel.burn_rate())) }) } FireInfo::None => None, }) .flatten() }) .partition_map(|r| r) } /// Returns two vectors: /// The first contains all oxidizers in this list, as well as their actual mole amounts and how much fuel they can oxidize. /// The second contains all fuel sources in this list, as well as their actual mole amounts and how much oxidizer they can react with. pub fn get_fire_info(&self) -> (Vec<SpecificFireInfo>, Vec<SpecificFireInfo>) { super::with_gas_info(|gas_info| self.get_fire_info_with_lock(gas_info)) } /// Adds heat directly to the gas mixture, in joules (probably). pub fn adjust_heat(&mut self, heat: f32) { let cap = self.heat_capacity(); self.set_temperature(((cap * self.temperature) + heat) / cap); } /// Returns true if there's a visible gas in this mix. pub fn is_visible(&self) -> bool { self.enumerate() .any(|(i, gas)| gas_visibility(i as usize).map_or(false, |amt| gas >= amt)) } /// A hashed representation of the visibility of a gas, so that it only needs to update vis when actually changed. pub fn vis_hash_changed(&self, gas_visibility: &[Option<f32>]) -> bool { use std::hash::Hasher; let mut hasher: ahash::AHasher = ahash::AHasher::default(); for (i, gas) in self.enumerate() { if let Some(amt) = unsafe { gas_visibility.get_unchecked(i) }.filter(|&amt| gas >= amt) { hasher.write_usize(i); hasher.write_usize((FACTOR_GAS_VISIBLE_MAX).min((gas / amt).ceil()) as usize); } } let cur_hash = hasher.finish(); self.cached_vis_hash.0.swap(cur_hash, Relaxed)!= cur_hash } // Removes all redundant zeroes from the gas mixture. pub fn garbage_collect(&mut self) { let mut last_valid_found = 0; for (i, amt) in self.moles.iter_mut().enumerate() { if *amt > GAS_MIN_MOLES { last_valid_found = i; } else { *amt = 0.0; } } self.moles.truncate(last_valid_found + 1); } } use std::ops::{Add, Mul}; /// Takes a copy of the mix, merges the right hand side, then returns the copy. impl Add<&Mixture> for Mixture { type Output = Self; fn add(self, rhs: &Mixture) -> Self { let mut ret = self; ret.merge(rhs); ret } } /// Takes a copy of the mix, merges the right hand side, then returns the copy. impl<'a, 'b> Add<&'a Mixture> for &'b Mixture { type Output = Mixture; fn add(self, rhs: &Mixture) -> Mixture { let mut ret = self.clone(); ret.merge(rhs); ret } } /// Makes a copy of the given mix, multiplied by a scalar. impl Mul<f32> for Mixture { type Output = Self; fn mul(self, rhs: f32) -> Self { let mut ret = self; ret.multiply(rhs); ret } } /// Makes a copy of the given mix, multiplied by a scalar. impl<'a> Mul<f32> for &'a Mixture { type Output = Mixture; fn mul(self, rhs: f32) -> Mixture { let mut ret = self.clone(); ret.multiply(rhs); ret } } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let mut into = Mixture::new(); into.set_moles(0, 82.0); into.set_moles(1, 22.0); into.set_temperature(293.15); let mut source = Mixture::new(); source.set_moles(3, 100.0); source.set_temperature(313.15); into.merge(&source); // make sure that the merge successfuly moved the moles assert_eq!(into.get_moles(3), 100.0); assert_eq!(source.get_moles(3), 100.0); // source is not modified by merge /* make sure that the merge successfuly changed the temperature of the mix merged into: test gases have heat capacities of 2,080 and 20,000 respectively, so total thermal energies of 609,752 and 6,263,000 respectively once multiplied by temperatures. add those together, then divide by new total heat capacity: (609,752 + 6,263,000)/(2,080 + 20,000) = 6,872,752 / 2,2080 ~ 311.265942 so we compare to see if it's relatively close to 311.266, cause of floating point precision */ assert!( (into.get_temperature() - 311.266).abs() < 0.01, "{} should be near 311.266, is {}", into.get_temperature(), (into.get_temperature() - 311.266) ); } #[test] fn test_remove() { // also tests multiply, copy_from_mutable let mut removed = Mixture::new(); removed.set_moles(0, 22.0); removed.set_moles(1, 82.0); let new = removed.remove_ratio(0.5); assert_eq!(removed.compare(&new) >= MINIMUM_MOLES_DELTA_TO_MOVE, false); assert_eq!(removed.get_moles(0), 11.0); assert_eq!(removed.get_moles(1), 41.0); removed.mark_immutable(); let new_two = removed.remove_ratio(0.5); assert_eq!( removed.compare(&new_two) >= MINIMUM_MOLES_DELTA_TO_MOVE, true ); assert_eq!(removed.get_moles(0), 11.0); assert_eq!(removed.get_moles(1), 41.0); assert_eq!(new_two.get_moles(0), 5.5); } }
{ self.heat_capacity() * self.temperature }
identifier_body
mixture.rs
use itertools::{ Either, EitherOrBoth::{Both, Left, Right}, Itertools, }; use std::{ cell::Cell, sync::atomic::{AtomicU64, Ordering::Relaxed}, }; use tinyvec::TinyVec; use crate::reaction::ReactionIdentifier; use super::{ constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasIDX, }; type SpecificFireInfo = (usize, f32, f32); struct VisHash(AtomicU64); impl Clone for VisHash { fn clone(&self) -> Self { VisHash(AtomicU64::new(self.0.load(Relaxed))) } } /// The data structure representing a Space Station 13 gas mixture. /// Unlike Monstermos, this doesn't have the archive built-in; instead, /// the archive is a feature of the turf grid, only existing during /// turf processing. /// Also missing is `last_share`; due to the usage of Rust, /// processing no longer requires sleeping turfs. Instead, we're using /// a proper, fully-simulated FDM system, much like LINDA but without /// sleeping turfs. #[derive(Clone)] pub struct Mixture { temperature: f32, pub volume: f32, min_heat_capacity: f32, immutable: bool, moles: TinyVec<[f32; 8]>, cached_heat_capacity: Cell<Option<f32>>, cached_vis_hash: VisHash, } /* Cell is not thread-safe. However, we use it only for caching heat capacity. The worst case race condition is thus thread A and B try to access heat capacity at the same time; both find that it's currently uncached, so both go to calculate it; both calculate it, and both calculate it to the same value, then one sets the cache to that value, then the other does. Technically, a worse one would be thread A mutates the gas mixture, changing a gas amount, while thread B tries to get its heat capacity; thread B finds a well-defined heat capacity, which is not correct, and uses it for a calculation, but this cannot happen: thread A would have a write lock, precluding thread B from accessing it. */ unsafe impl Sync for Mixture {} impl Default for Mixture { fn default() -> Self { Self::new() } } impl Mixture { /// Makes an empty gas mixture. pub fn new() -> Self { Self { moles: TinyVec::new(), temperature: 2.7, volume: 2500.0, min_heat_capacity: 0.0, immutable: false, cached_heat_capacity: Cell::new(None), cached_vis_hash: VisHash(AtomicU64::new(0)), } } /// Makes an empty gas mixture with the given volume. pub fn from_vol(vol: f32) -> Self { let mut ret = Self::new(); ret.volume = vol; ret } /// Returns if any data is corrupt. pub fn is_corrupt(&self) -> bool { !self.temperature.is_normal() || self.moles.len() > total_num_gases() } /// Fixes any corruption found. pub fn fix_corruption(&mut self) { self.garbage_collect(); if self.temperature < 2.7 ||!self.temperature.is_normal() { self.set_temperature(293.15); } } /// Returns the temperature of the mix. T pub fn get_temperature(&self) -> f32 { self.temperature } /// Sets the temperature, if the mix isn't immutable. T pub fn set_temperature(&mut self, temp: f32) { if!self.immutable && temp.is_normal() { self.temperature = temp; } } /// Sets the minimum heat capacity of this mix. pub fn set_min_heat_capacity(&mut self, amt: f32) { self.min_heat_capacity = amt; } /// Returns an iterator over the gas keys and mole amounts thereof. pub fn enumerate(&self) -> impl Iterator<Item = (GasIDX, f32)> + '_ { self.moles.iter().copied().enumerate() } /// Allows closures to iterate over each gas. pub fn for_each_gas( &self, mut f: impl FnMut(GasIDX, f32) -> Result<(), auxtools::Runtime>, ) -> Result<(), auxtools::Runtime> { for (i, g) in self.enumerate() { f(i, g)?; } Ok(()) } /// Returns (by value) the amount of moles of a given index the mix has. M pub fn get_moles(&self, idx: GasIDX) -> f32 { self.moles.get(idx).copied().unwrap_or(0.0) } /// Sets the mix to be internally immutable. Rust doesn't know about any of this, obviously. pub fn mark_immutable(&mut self) { self.immutable = true; } /// Returns whether this gas mixture is immutable. pub fn is_immutable(&self) -> bool { self.immutable } fn maybe_expand(&mut self, size: usize) { if self.moles.len() < size { self.moles.resize(size, 0.0); } } /// If mix is not immutable, sets the gas at the given `idx` to the given `amt`. pub fn set_moles(&mut self, idx: GasIDX, amt: f32) { if!self.immutable && idx < total_num_gases() && (idx <= self.moles.len() || (amt > GAS_MIN_MOLES && amt.is_normal())) { self.maybe_expand((idx + 1) as usize); unsafe { *self.moles.get_unchecked_mut(idx) = amt; }; self.cached_heat_capacity.set(None); } } pub fn adjust_moles(&mut self, idx: GasIDX, amt: f32) { if!self.immutable && amt.is_normal() && idx < total_num_gases() { self.maybe_expand((idx + 1) as usize); let r = unsafe { self.moles.get_unchecked_mut(idx) }; *r += amt; if amt < 0.0 { self.garbage_collect(); } self.cached_heat_capacity.set(None); } } #[inline(never)] // mostly this makes it so that heat_capacity itself is inlined fn slow_heat_capacity(&self) -> f32 { let heat_cap = with_specific_heats(|heats| { self.moles .iter() .copied() .zip(heats.iter()) .fold(0.0, |acc, (amt, cap)| cap.mul_add(amt, acc)) }) .max(self.min_heat_capacity); self.cached_heat_capacity.set(Some(heat_cap)); heat_cap } /// The heat capacity of the material. [joules?]/mole-kelvin. pub fn heat_capacity(&self) -> f32 { self.cached_heat_capacity .get() .filter(|cap| cap.is_finite() && cap.is_sign_positive()) .unwrap_or_else(|| self.slow_heat_capacity()) } /// Heat capacity of exactly one gas in this mix. pub fn partial_heat_capacity(&self, idx: GasIDX) -> f32 { self.moles .get(idx) .filter(|amt| amt.is_normal()) .map_or(0.0, |amt| amt * with_specific_heats(|heats| heats[idx])) } /// The total mole count of the mixture. Moles. pub fn total_moles(&self) -> f32 { self.moles.iter().sum() } /// Pressure. Kilopascals. pub fn return_pressure(&self) -> f32 { self.total_moles() * R_IDEAL_GAS_EQUATION * self.temperature / self.volume } /// Thermal energy. Joules? pub fn thermal_energy(&self) -> f32 { self.heat_capacity() * self.temperature } /// Merges one gas mixture into another. pub fn merge(&mut self, giver: &Self) { if self.immutable { return; } let our_heat_capacity = self.heat_capacity(); let other_heat_capacity = giver.heat_capacity(); self.maybe_expand(giver.moles.len()); for (a, b) in self.moles.iter_mut().zip(giver.moles.iter()) { *a += b; } let combined_heat_capacity = our_heat_capacity + other_heat_capacity; if combined_heat_capacity > MINIMUM_HEAT_CAPACITY { self.set_temperature( (our_heat_capacity * self.temperature + other_heat_capacity * giver.temperature) / (combined_heat_capacity), ); } self.cached_heat_capacity.set(Some(combined_heat_capacity)); } /// Transfers only the given gases from us to another mix. pub fn transfer_gases_to(&mut self, r: f32, gases: &[GasIDX], into: &mut Self) { let ratio = r.clamp(0.0, 1.0); let initial_energy = into.thermal_energy(); let mut heat_transfer = 0.0; with_specific_heats(|heats| { for i in gases.iter().copied() { if let Some(orig) = self.moles.get_mut(i) { let delta = *orig * ratio; heat_transfer += delta * self.temperature * heats[i]; *orig -= delta; into.adjust_moles(i, delta); } } }); self.cached_heat_capacity.set(None); into.cached_heat_capacity.set(None); into.set_temperature((initial_energy + heat_transfer) / into.heat_capacity()); } /// Takes a percentage of this gas mixture's moles and puts it into another mixture. if this mix is mutable, also removes those moles from the original. pub fn remove_ratio_into(&mut self, mut ratio: f32, into: &mut Self) { if ratio <= 0.0 { return; } if ratio >= 1.0 { ratio = 1.0; } let orig_temp = self.temperature; into.copy_from_mutable(self); into.multiply(ratio); self.multiply(1.0 - ratio); self.temperature = orig_temp; into.temperature = orig_temp; } /// As `remove_ratio_into`, but a raw number of moles instead of a ratio. pub fn remove_into(&mut self, amount: f32, into: &mut Self) { self.remove_ratio_into(amount / self.total_moles(), into); } /// A convenience function that makes the mixture for `remove_ratio_into` on the spot and returns it. pub fn remove_ratio(&mut self, ratio: f32) -> Self { let mut removed = Self::from_vol(self.volume); self.remove_ratio_into(ratio, &mut removed); removed } /// Like `remove_ratio`, but with moles. pub fn remove(&mut self, amount: f32) -> Self { self.remove_ratio(amount / self.total_moles()) } /// Copies from a given gas mixture, if we're mutable. pub fn copy_from_mutable(&mut self, sample: &Self) { if self.immutable { return; } self.moles = sample.moles.clone(); self.temperature = sample.temperature; self.cached_heat_capacity .set(sample.cached_heat_capacity.get()); } /// A very simple finite difference solution to the heat transfer equation. /// Works well enough for our purposes, though perhaps called less often /// than it ought to be while we're working in Rust. /// Differs from the original by not using archive, since we don't put the archive into the gas mix itself anymore. pub fn temperature_share(&mut self, sharer: &mut Self, conduction_coefficient: f32) -> f32 { let temperature_delta = self.temperature - sharer.temperature; if temperature_delta.abs() > MINIMUM_TEMPERATURE_DELTA_TO_CONSIDER { let self_heat_capacity = self.heat_capacity(); let sharer_heat_capacity = sharer.heat_capacity(); if sharer_heat_capacity > MINIMUM_HEAT_CAPACITY && self_heat_capacity > MINIMUM_HEAT_CAPACITY { let heat = conduction_coefficient * temperature_delta * (self_heat_capacity * sharer_heat_capacity / (self_heat_capacity + sharer_heat_capacity)); if!self.immutable { self.set_temperature((self.temperature - heat / self_heat_capacity).max(TCMB)); } if!sharer.immutable { sharer.set_temperature( (sharer.temperature + heat / sharer_heat_capacity).max(TCMB), ); } } } sharer.temperature } /// As above, but you may put in any arbitrary coefficient, temp, heat capacity. /// Only used for superconductivity as of right now. pub fn temperature_share_non_gas( &mut self, conduction_coefficient: f32, sharer_temperature: f32, sharer_heat_capacity: f32, ) -> f32 { let temperature_delta = self.temperature - sharer_temperature; if temperature_delta.abs() > MINIMUM_TEMPERATURE_DELTA_TO_CONSIDER { let self_heat_capacity = self.heat_capacity(); if sharer_heat_capacity > MINIMUM_HEAT_CAPACITY && self_heat_capacity > MINIMUM_HEAT_CAPACITY { let heat = conduction_coefficient * temperature_delta * (self_heat_capacity * sharer_heat_capacity / (self_heat_capacity + sharer_heat_capacity)); if!self.immutable { self.set_temperature((self.temperature - heat / self_heat_capacity).max(TCMB)); } return (sharer_temperature + heat / sharer_heat_capacity).max(TCMB); } } sharer_temperature } /// The second part of old compare(). Compares temperature, but only if this gas has sufficiently high moles. pub fn temperature_compare(&self, sample: &Self) -> bool { (self.get_temperature() - sample.get_temperature()).abs() > MINIMUM_TEMPERATURE_DELTA_TO_SUSPEND && (self.total_moles() > MINIMUM_MOLES_DELTA_TO_MOVE) } /// Returns the maximum mole delta for an individual gas. pub fn compare(&self, sample: &Self) -> f32 { self.moles .iter() .copied() .zip_longest(sample.moles.iter().copied()) .fold(0.0, |acc, pair| acc.max(pair.reduce(|a, b| (b - a).abs()))) } pub fn compare_with(&self, sample: &Self, amt: f32) -> bool { self.moles .as_slice() .iter() .zip_longest(sample.moles.as_slice().iter()) .rev() .any(|pair| match pair { Left(a) => a >= &amt, Right(b) => b >= &amt, Both(a, b) => a!= b && (a - b).abs() >= amt, }) } /// Clears the moles from the gas. pub fn clear(&mut self) { if!self.immutable { self.moles.clear(); self.cached_heat_capacity.set(None); } } /// Resets the gas mixture to an initialized-with-volume state. pub fn clear_with_vol(&mut self, vol: f32) { self.temperature = 2.7; self.volume = vol; self.min_heat_capacity = 0.0; self.immutable = false; self.clear(); } /// Multiplies every gas molage with this value. pub fn multiply(&mut self, multiplier: f32) { if!self.immutable { for amt in self.moles.iter_mut() { *amt *= multiplier; } self.cached_heat_capacity.set(None); self.garbage_collect(); } } /// Checks if the proc can react with any reactions. pub fn can_react(&self) -> bool { with_reactions(|reactions| reactions.iter().any(|r| r.check_conditions(self))) } /// Gets all of the reactions this mix should do. pub fn all_reactable(&self) -> Vec<ReactionIdentifier> { with_reactions(|reactions| { reactions .iter() .filter_map(|r| r.check_conditions(self).then(|| r.get_id())) .collect() }) } /// Returns a tuple with oxidation power and fuel amount of this gas mixture. pub fn get_burnability(&self) -> (f32, f32) { use crate::types::FireInfo; super::with_gas_info(|gas_info| { self.moles .iter() .zip(gas_info) .fold((0.0, 0.0), |mut acc, (&amt, this_gas_info)| { if amt > GAS_MIN_MOLES { match this_gas_info.fire_info { FireInfo::Oxidation(oxidation) => { if self.temperature > oxidation.temperature() { let amount = amt * (1.0 - oxidation.temperature() / self.temperature) .max(0.0); acc.0 += amount * oxidation.power(); } } FireInfo::Fuel(fire) => { if self.temperature > fire.temperature() { let amount = amt * (1.0 - fire.temperature() / self.temperature).max(0.0); acc.1 += amount / fire.burn_rate(); } } FireInfo::None => (), } } acc }) }) } /// Returns only the oxidation power. Since this calculates burnability anyway, prefer `get_burnability`. pub fn get_oxidation_power(&self) -> f32 { self.get_burnability().0 } /// Returns only fuel amount. Since this calculates burnability anyway, prefer `get_burnability`. pub fn get_fuel_amount(&self) -> f32 { self.get_burnability().1 } /// Like `get_fire_info`, but takes a reference to a gas info vector, /// so one doesn't need to do a recursive lock on the global list. pub fn get_fire_info_with_lock( &self, gas_info: &[super::GasType], ) -> (Vec<SpecificFireInfo>, Vec<SpecificFireInfo>) { use crate::types::FireInfo; self.moles .iter() .zip(gas_info) .enumerate() .filter_map(|(i, (&amt, this_gas_info))| { (amt > GAS_MIN_MOLES) .then(|| match this_gas_info.fire_info { FireInfo::Oxidation(oxidation) => (self.get_temperature() > oxidation.temperature()) .then(|| { let amount = amt * (1.0 - oxidation.temperature() / self.get_temperature()).max(0.0); Either::Right((i, amount, amount * oxidation.power())) }), FireInfo::Fuel(fuel) => { (self.get_temperature() > fuel.temperature()).then(|| { let amount = amt * (1.0 - fuel.temperature() / self.get_temperature()).max(0.0); Either::Left((i, amount, amount / fuel.burn_rate())) }) } FireInfo::None => None, }) .flatten() }) .partition_map(|r| r) } /// Returns two vectors: /// The first contains all oxidizers in this list, as well as their actual mole amounts and how much fuel they can oxidize. /// The second contains all fuel sources in this list, as well as their actual mole amounts and how much oxidizer they can react with. pub fn get_fire_info(&self) -> (Vec<SpecificFireInfo>, Vec<SpecificFireInfo>) { super::with_gas_info(|gas_info| self.get_fire_info_with_lock(gas_info)) } /// Adds heat directly to the gas mixture, in joules (probably). pub fn
(&mut self, heat: f32) { let cap = self.heat_capacity(); self.set_temperature(((cap * self.temperature) + heat) / cap); } /// Returns true if there's a visible gas in this mix. pub fn is_visible(&self) -> bool { self.enumerate() .any(|(i, gas)| gas_visibility(i as usize).map_or(false, |amt| gas >= amt)) } /// A hashed representation of the visibility of a gas, so that it only needs to update vis when actually changed. pub fn vis_hash_changed(&self, gas_visibility: &[Option<f32>]) -> bool { use std::hash::Hasher; let mut hasher: ahash::AHasher = ahash::AHasher::default(); for (i, gas) in self.enumerate() { if let Some(amt) = unsafe { gas_visibility.get_unchecked(i) }.filter(|&amt| gas >= amt) { hasher.write_usize(i); hasher.write_usize((FACTOR_GAS_VISIBLE_MAX).min((gas / amt).ceil()) as usize); } } let cur_hash = hasher.finish(); self.cached_vis_hash.0.swap(cur_hash, Relaxed)!= cur_hash } // Removes all redundant zeroes from the gas mixture. pub fn garbage_collect(&mut self) { let mut last_valid_found = 0; for (i, amt) in self.moles.iter_mut().enumerate() { if *amt > GAS_MIN_MOLES { last_valid_found = i; } else { *amt = 0.0; } } self.moles.truncate(last_valid_found + 1); } } use std::ops::{Add, Mul}; /// Takes a copy of the mix, merges the right hand side, then returns the copy. impl Add<&Mixture> for Mixture { type Output = Self; fn add(self, rhs: &Mixture) -> Self { let mut ret = self; ret.merge(rhs); ret } } /// Takes a copy of the mix, merges the right hand side, then returns the copy. impl<'a, 'b> Add<&'a Mixture> for &'b Mixture { type Output = Mixture; fn add(self, rhs: &Mixture) -> Mixture { let mut ret = self.clone(); ret.merge(rhs); ret } } /// Makes a copy of the given mix, multiplied by a scalar. impl Mul<f32> for Mixture { type Output = Self; fn mul(self, rhs: f32) -> Self { let mut ret = self; ret.multiply(rhs); ret } } /// Makes a copy of the given mix, multiplied by a scalar. impl<'a> Mul<f32> for &'a Mixture { type Output = Mixture; fn mul(self, rhs: f32) -> Mixture { let mut ret = self.clone(); ret.multiply(rhs); ret } } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let mut into = Mixture::new(); into.set_moles(0, 82.0); into.set_moles(1, 22.0); into.set_temperature(293.15); let mut source = Mixture::new(); source.set_moles(3, 100.0); source.set_temperature(313.15); into.merge(&source); // make sure that the merge successfuly moved the moles assert_eq!(into.get_moles(3), 100.0); assert_eq!(source.get_moles(3), 100.0); // source is not modified by merge /* make sure that the merge successfuly changed the temperature of the mix merged into: test gases have heat capacities of 2,080 and 20,000 respectively, so total thermal energies of 609,752 and 6,263,000 respectively once multiplied by temperatures. add those together, then divide by new total heat capacity: (609,752 + 6,263,000)/(2,080 + 20,000) = 6,872,752 / 2,2080 ~ 311.265942 so we compare to see if it's relatively close to 311.266, cause of floating point precision */ assert!( (into.get_temperature() - 311.266).abs() < 0.01, "{} should be near 311.266, is {}", into.get_temperature(), (into.get_temperature() - 311.266) ); } #[test] fn test_remove() { // also tests multiply, copy_from_mutable let mut removed = Mixture::new(); removed.set_moles(0, 22.0); removed.set_moles(1, 82.0); let new = removed.remove_ratio(0.5); assert_eq!(removed.compare(&new) >= MINIMUM_MOLES_DELTA_TO_MOVE, false); assert_eq!(removed.get_moles(0), 11.0); assert_eq!(removed.get_moles(1), 41.0); removed.mark_immutable(); let new_two = removed.remove_ratio(0.5); assert_eq!( removed.compare(&new_two) >= MINIMUM_MOLES_DELTA_TO_MOVE, true ); assert_eq!(removed.get_moles(0), 11.0); assert_eq!(removed.get_moles(1), 41.0); assert_eq!(new_two.get_moles(0), 5.5); } }
adjust_heat
identifier_name
object.rs
//! Represents an object in PHP. Allows for overriding the internal object used //! by classes, allowing users to store Rust data inside a PHP object. use std::{convert::TryInto, fmt::Debug, ops::DerefMut}; use crate::{ boxed::{ZBox, ZBoxable}, class::RegisteredClass, convert::{FromZendObject, FromZval, FromZvalMut, IntoZval}, error::{Error, Result}, ffi::{ ext_php_rs_zend_object_release, zend_call_known_function, zend_object, zend_objects_new, HashTable, ZEND_ISEMPTY, ZEND_PROPERTY_EXISTS, ZEND_PROPERTY_ISSET, }, flags::DataType, rc::PhpRc, types::{ZendClassObject, ZendStr, Zval}, zend::{ce, ClassEntry, ExecutorGlobals, ZendObjectHandlers}, }; /// A PHP object. /// /// This type does not maintain any information about its type, for example, /// classes with have associated Rust structs cannot be accessed through this /// type. [`ZendClassObject`] is used for this purpose, and you can convert /// between the two. pub type ZendObject = zend_object; impl ZendObject { /// Creates a new [`ZendObject`], returned inside an [`ZBox<ZendObject>`] /// wrapper. /// /// # Parameters /// /// * `ce` - The type of class the new object should be an instance of. /// /// # Panics /// /// Panics when allocating memory for the new object fails. pub fn new(ce: &ClassEntry) -> ZBox<Self> { // SAFETY: Using emalloc to allocate memory inside Zend arena. Casting `ce` to // `*mut` is valid as the function will not mutate `ce`. unsafe { let ptr = zend_objects_new(ce as *const _ as *mut _); ZBox::from_raw( ptr.as_mut() .expect("Failed to allocate memory for Zend object"), ) } } /// Creates a new `stdClass` instance, returned inside an /// [`ZBox<ZendObject>`] wrapper. /// /// # Panics /// /// Panics if allocating memory for the object fails, or if the `stdClass` /// class entry has not been registered with PHP yet. /// /// # Example /// /// ```no_run /// use ext_php_rs::types::ZendObject; /// /// let mut obj = ZendObject::new_stdclass(); /// /// obj.set_property("hello", "world"); /// ``` pub fn new_stdclass() -> ZBox<Self> { // SAFETY: This will be `NULL` until it is initialized. `as_ref()` checks for // null, so we can panic if it's null. Self::new(ce::stdclass()) } /// Converts a class object into an owned [`ZendObject`]. This removes any /// possibility of accessing the underlying attached Rust struct. pub fn from_class_object<T: RegisteredClass>(obj: ZBox<ZendClassObject<T>>) -> ZBox<Self> { let this = obj.into_raw(); // SAFETY: Consumed box must produce a well-aligned non-null pointer. unsafe { ZBox::from_raw(this.get_mut_zend_obj()) } } /// Attempts to retrieve the class name of the object. pub fn get_class_name(&self) -> Result<String> { unsafe { self.handlers()? .get_class_name .and_then(|f| f(self).as_ref()) .ok_or(Error::InvalidScope) .and_then(|s| s.try_into()) } } /// Checks if the given object is an instance of a registered class with /// Rust type `T`. pub fn is_instance<T: RegisteredClass>(&self) -> bool { (self.ce as *const ClassEntry).eq(&(T::get_metadata().ce() as *const _)) } /// Attempts to read a property from the Object. Returns a result containing /// the value of the property if it exists and can be read, and an /// [`Error`] otherwise. /// /// # Parameters /// /// * `name` - The name of the property. /// * `query` - The type of query to use when attempting to get a property. pub fn get_property<'a, T>(&'a self, name: &str) -> Result<T> where T: FromZval<'a>, { if!self.has_property(name, PropertyQuery::Exists)? { return Err(Error::InvalidProperty); } let mut name = ZendStr::new(name, false)?; let mut rv = Zval::new(); let zv = unsafe { self.handlers()?.read_property.ok_or(Error::InvalidScope)?( self.mut_ptr(), name.deref_mut(), 1, std::ptr::null_mut(), &mut rv, ) .as_ref() } .ok_or(Error::InvalidScope)?; T::from_zval(zv).ok_or_else(|| Error::ZvalConversion(zv.get_type())) } /// Attempts to set a property on the object. /// /// # Parameters /// /// * `name` - The name of the property. /// * `value` - The value to set the property to. pub fn set_property(&mut self, name: &str, value: impl IntoZval) -> Result<()> { let mut name = ZendStr::new(name, false)?; let mut value = value.into_zval(false)?; unsafe { self.handlers()?.write_property.ok_or(Error::InvalidScope)?( self, name.deref_mut(), &mut value, std::ptr::null_mut(), ) .as_ref() } .ok_or(Error::InvalidScope)?; Ok(()) } /// Checks if a property exists on an object. Takes a property name and /// query parameter, which defines what classifies if a property exists /// or not. See [`PropertyQuery`] for more information. /// /// # Parameters /// /// * `name` - The name of the property. /// * `query` - The 'query' to classify if a property exists. pub fn has_property(&self, name: &str, query: PropertyQuery) -> Result<bool> { let mut name = ZendStr::new(name, false)?; Ok(unsafe { self.handlers()?.has_property.ok_or(Error::InvalidScope)?( self.mut_ptr(), name.deref_mut(), query as _, std::ptr::null_mut(), ) } > 0) } /// Attempts to retrieve the properties of the object. Returned inside a /// Zend Hashtable. pub fn get_properties(&self) -> Result<&HashTable> { unsafe { self.handlers()? .get_properties .and_then(|props| props(self.mut_ptr()).as_ref()) .ok_or(Error::InvalidScope) } } /// Extracts some type from a Zend object. /// /// This is a wrapper function around `FromZendObject::extract()`. pub fn extract<'a, T>(&'a self) -> Result<T> where T: FromZendObject<'a>, { T::from_zend_object(self) } /// Attempts to retrieve a reference to the object handlers. #[inline] unsafe fn handlers(&self) -> Result<&ZendObjectHandlers> { self.handlers.as_ref().ok_or(Error::InvalidScope) } /// Returns a mutable pointer to `self`, regardless of the type of /// reference. Only to be used in situations where a C function requires /// a mutable pointer but does not modify the underlying data. #[inline] fn mut_ptr(&self) -> *mut Self { (self as *const Self) as *mut Self } } unsafe impl ZBoxable for ZendObject { fn free(&mut self) { unsafe { ext_php_rs_zend_object_release(self) } } } impl Debug for ZendObject { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut dbg = f.debug_struct( self.get_class_name() .unwrap_or_else(|_| "ZendObject".to_string()) .as_str(), ); if let Ok(props) = self.get_properties() { for (id, key, val) in props.iter() { dbg.field(key.unwrap_or_else(|| id.to_string()).as_str(), val); } } dbg.finish() } } impl<'a> FromZval<'a> for &'a ZendObject { const TYPE: DataType = DataType::Object(None); fn
(zval: &'a Zval) -> Option<Self> { zval.object() } } impl<'a> FromZvalMut<'a> for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); fn from_zval_mut(zval: &'a mut Zval) -> Option<Self> { zval.object_mut() } } impl IntoZval for ZBox<ZendObject> { const TYPE: DataType = DataType::Object(None); #[inline] fn set_zval(mut self, zv: &mut Zval, _: bool) -> Result<()> { // We must decrement the refcounter on the object before inserting into the // zval, as the reference counter will be incremented on add. // NOTE(david): again is this needed, we increment in `set_object`. self.dec_count(); zv.set_object(self.into_raw()); Ok(()) } } impl<'a> IntoZval for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); #[inline] fn set_zval(self, zv: &mut Zval, _: bool) -> Result<()> { zv.set_object(self); Ok(()) } } impl FromZendObject<'_> for String { fn from_zend_object(obj: &ZendObject) -> Result<Self> { let mut ret = Zval::new(); unsafe { zend_call_known_function( (*obj.ce).__tostring, obj as *const _ as *mut _, obj.ce, &mut ret, 0, std::ptr::null_mut(), std::ptr::null_mut(), ); } if let Some(err) = ExecutorGlobals::take_exception() { // TODO: become an error let class_name = obj.get_class_name(); panic!( "Uncaught exception during call to {}::__toString(): {:?}", class_name.expect("unable to determine class name"), err ); } else if let Some(output) = ret.extract() { Ok(output) } else { // TODO: become an error let class_name = obj.get_class_name(); panic!( "{}::__toString() must return a string", class_name.expect("unable to determine class name"), ); } } } impl<T: RegisteredClass> From<ZBox<ZendClassObject<T>>> for ZBox<ZendObject> { #[inline] fn from(obj: ZBox<ZendClassObject<T>>) -> Self { ZendObject::from_class_object(obj) } } /// Different ways to query if a property exists. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[repr(u32)] pub enum PropertyQuery { /// Property exists and is not NULL. Isset = ZEND_PROPERTY_ISSET, /// Property is not empty. NotEmpty = ZEND_ISEMPTY, /// Property exists. Exists = ZEND_PROPERTY_EXISTS, }
from_zval
identifier_name
object.rs
//! Represents an object in PHP. Allows for overriding the internal object used //! by classes, allowing users to store Rust data inside a PHP object. use std::{convert::TryInto, fmt::Debug, ops::DerefMut}; use crate::{ boxed::{ZBox, ZBoxable}, class::RegisteredClass, convert::{FromZendObject, FromZval, FromZvalMut, IntoZval}, error::{Error, Result}, ffi::{ ext_php_rs_zend_object_release, zend_call_known_function, zend_object, zend_objects_new, HashTable, ZEND_ISEMPTY, ZEND_PROPERTY_EXISTS, ZEND_PROPERTY_ISSET, }, flags::DataType, rc::PhpRc, types::{ZendClassObject, ZendStr, Zval}, zend::{ce, ClassEntry, ExecutorGlobals, ZendObjectHandlers}, }; /// A PHP object. /// /// This type does not maintain any information about its type, for example, /// classes with have associated Rust structs cannot be accessed through this /// type. [`ZendClassObject`] is used for this purpose, and you can convert /// between the two. pub type ZendObject = zend_object; impl ZendObject { /// Creates a new [`ZendObject`], returned inside an [`ZBox<ZendObject>`] /// wrapper. /// /// # Parameters /// /// * `ce` - The type of class the new object should be an instance of. /// /// # Panics /// /// Panics when allocating memory for the new object fails. pub fn new(ce: &ClassEntry) -> ZBox<Self> { // SAFETY: Using emalloc to allocate memory inside Zend arena. Casting `ce` to // `*mut` is valid as the function will not mutate `ce`. unsafe { let ptr = zend_objects_new(ce as *const _ as *mut _); ZBox::from_raw( ptr.as_mut() .expect("Failed to allocate memory for Zend object"), ) } } /// Creates a new `stdClass` instance, returned inside an /// [`ZBox<ZendObject>`] wrapper. /// /// # Panics /// /// Panics if allocating memory for the object fails, or if the `stdClass` /// class entry has not been registered with PHP yet. /// /// # Example /// /// ```no_run /// use ext_php_rs::types::ZendObject; /// /// let mut obj = ZendObject::new_stdclass(); /// /// obj.set_property("hello", "world"); /// ``` pub fn new_stdclass() -> ZBox<Self> { // SAFETY: This will be `NULL` until it is initialized. `as_ref()` checks for // null, so we can panic if it's null. Self::new(ce::stdclass()) } /// Converts a class object into an owned [`ZendObject`]. This removes any /// possibility of accessing the underlying attached Rust struct. pub fn from_class_object<T: RegisteredClass>(obj: ZBox<ZendClassObject<T>>) -> ZBox<Self> { let this = obj.into_raw(); // SAFETY: Consumed box must produce a well-aligned non-null pointer. unsafe { ZBox::from_raw(this.get_mut_zend_obj()) } } /// Attempts to retrieve the class name of the object. pub fn get_class_name(&self) -> Result<String> { unsafe { self.handlers()? .get_class_name .and_then(|f| f(self).as_ref()) .ok_or(Error::InvalidScope) .and_then(|s| s.try_into()) } } /// Checks if the given object is an instance of a registered class with /// Rust type `T`. pub fn is_instance<T: RegisteredClass>(&self) -> bool { (self.ce as *const ClassEntry).eq(&(T::get_metadata().ce() as *const _)) } /// Attempts to read a property from the Object. Returns a result containing /// the value of the property if it exists and can be read, and an /// [`Error`] otherwise. /// /// # Parameters /// /// * `name` - The name of the property. /// * `query` - The type of query to use when attempting to get a property. pub fn get_property<'a, T>(&'a self, name: &str) -> Result<T> where T: FromZval<'a>, { if!self.has_property(name, PropertyQuery::Exists)? { return Err(Error::InvalidProperty); } let mut name = ZendStr::new(name, false)?; let mut rv = Zval::new(); let zv = unsafe { self.handlers()?.read_property.ok_or(Error::InvalidScope)?( self.mut_ptr(), name.deref_mut(), 1, std::ptr::null_mut(),
.as_ref() } .ok_or(Error::InvalidScope)?; T::from_zval(zv).ok_or_else(|| Error::ZvalConversion(zv.get_type())) } /// Attempts to set a property on the object. /// /// # Parameters /// /// * `name` - The name of the property. /// * `value` - The value to set the property to. pub fn set_property(&mut self, name: &str, value: impl IntoZval) -> Result<()> { let mut name = ZendStr::new(name, false)?; let mut value = value.into_zval(false)?; unsafe { self.handlers()?.write_property.ok_or(Error::InvalidScope)?( self, name.deref_mut(), &mut value, std::ptr::null_mut(), ) .as_ref() } .ok_or(Error::InvalidScope)?; Ok(()) } /// Checks if a property exists on an object. Takes a property name and /// query parameter, which defines what classifies if a property exists /// or not. See [`PropertyQuery`] for more information. /// /// # Parameters /// /// * `name` - The name of the property. /// * `query` - The 'query' to classify if a property exists. pub fn has_property(&self, name: &str, query: PropertyQuery) -> Result<bool> { let mut name = ZendStr::new(name, false)?; Ok(unsafe { self.handlers()?.has_property.ok_or(Error::InvalidScope)?( self.mut_ptr(), name.deref_mut(), query as _, std::ptr::null_mut(), ) } > 0) } /// Attempts to retrieve the properties of the object. Returned inside a /// Zend Hashtable. pub fn get_properties(&self) -> Result<&HashTable> { unsafe { self.handlers()? .get_properties .and_then(|props| props(self.mut_ptr()).as_ref()) .ok_or(Error::InvalidScope) } } /// Extracts some type from a Zend object. /// /// This is a wrapper function around `FromZendObject::extract()`. pub fn extract<'a, T>(&'a self) -> Result<T> where T: FromZendObject<'a>, { T::from_zend_object(self) } /// Attempts to retrieve a reference to the object handlers. #[inline] unsafe fn handlers(&self) -> Result<&ZendObjectHandlers> { self.handlers.as_ref().ok_or(Error::InvalidScope) } /// Returns a mutable pointer to `self`, regardless of the type of /// reference. Only to be used in situations where a C function requires /// a mutable pointer but does not modify the underlying data. #[inline] fn mut_ptr(&self) -> *mut Self { (self as *const Self) as *mut Self } } unsafe impl ZBoxable for ZendObject { fn free(&mut self) { unsafe { ext_php_rs_zend_object_release(self) } } } impl Debug for ZendObject { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut dbg = f.debug_struct( self.get_class_name() .unwrap_or_else(|_| "ZendObject".to_string()) .as_str(), ); if let Ok(props) = self.get_properties() { for (id, key, val) in props.iter() { dbg.field(key.unwrap_or_else(|| id.to_string()).as_str(), val); } } dbg.finish() } } impl<'a> FromZval<'a> for &'a ZendObject { const TYPE: DataType = DataType::Object(None); fn from_zval(zval: &'a Zval) -> Option<Self> { zval.object() } } impl<'a> FromZvalMut<'a> for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); fn from_zval_mut(zval: &'a mut Zval) -> Option<Self> { zval.object_mut() } } impl IntoZval for ZBox<ZendObject> { const TYPE: DataType = DataType::Object(None); #[inline] fn set_zval(mut self, zv: &mut Zval, _: bool) -> Result<()> { // We must decrement the refcounter on the object before inserting into the // zval, as the reference counter will be incremented on add. // NOTE(david): again is this needed, we increment in `set_object`. self.dec_count(); zv.set_object(self.into_raw()); Ok(()) } } impl<'a> IntoZval for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); #[inline] fn set_zval(self, zv: &mut Zval, _: bool) -> Result<()> { zv.set_object(self); Ok(()) } } impl FromZendObject<'_> for String { fn from_zend_object(obj: &ZendObject) -> Result<Self> { let mut ret = Zval::new(); unsafe { zend_call_known_function( (*obj.ce).__tostring, obj as *const _ as *mut _, obj.ce, &mut ret, 0, std::ptr::null_mut(), std::ptr::null_mut(), ); } if let Some(err) = ExecutorGlobals::take_exception() { // TODO: become an error let class_name = obj.get_class_name(); panic!( "Uncaught exception during call to {}::__toString(): {:?}", class_name.expect("unable to determine class name"), err ); } else if let Some(output) = ret.extract() { Ok(output) } else { // TODO: become an error let class_name = obj.get_class_name(); panic!( "{}::__toString() must return a string", class_name.expect("unable to determine class name"), ); } } } impl<T: RegisteredClass> From<ZBox<ZendClassObject<T>>> for ZBox<ZendObject> { #[inline] fn from(obj: ZBox<ZendClassObject<T>>) -> Self { ZendObject::from_class_object(obj) } } /// Different ways to query if a property exists. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[repr(u32)] pub enum PropertyQuery { /// Property exists and is not NULL. Isset = ZEND_PROPERTY_ISSET, /// Property is not empty. NotEmpty = ZEND_ISEMPTY, /// Property exists. Exists = ZEND_PROPERTY_EXISTS, }
&mut rv, )
random_line_split
object.rs
//! Represents an object in PHP. Allows for overriding the internal object used //! by classes, allowing users to store Rust data inside a PHP object. use std::{convert::TryInto, fmt::Debug, ops::DerefMut}; use crate::{ boxed::{ZBox, ZBoxable}, class::RegisteredClass, convert::{FromZendObject, FromZval, FromZvalMut, IntoZval}, error::{Error, Result}, ffi::{ ext_php_rs_zend_object_release, zend_call_known_function, zend_object, zend_objects_new, HashTable, ZEND_ISEMPTY, ZEND_PROPERTY_EXISTS, ZEND_PROPERTY_ISSET, }, flags::DataType, rc::PhpRc, types::{ZendClassObject, ZendStr, Zval}, zend::{ce, ClassEntry, ExecutorGlobals, ZendObjectHandlers}, }; /// A PHP object. /// /// This type does not maintain any information about its type, for example, /// classes with have associated Rust structs cannot be accessed through this /// type. [`ZendClassObject`] is used for this purpose, and you can convert /// between the two. pub type ZendObject = zend_object; impl ZendObject { /// Creates a new [`ZendObject`], returned inside an [`ZBox<ZendObject>`] /// wrapper. /// /// # Parameters /// /// * `ce` - The type of class the new object should be an instance of. /// /// # Panics /// /// Panics when allocating memory for the new object fails. pub fn new(ce: &ClassEntry) -> ZBox<Self> { // SAFETY: Using emalloc to allocate memory inside Zend arena. Casting `ce` to // `*mut` is valid as the function will not mutate `ce`. unsafe { let ptr = zend_objects_new(ce as *const _ as *mut _); ZBox::from_raw( ptr.as_mut() .expect("Failed to allocate memory for Zend object"), ) } } /// Creates a new `stdClass` instance, returned inside an /// [`ZBox<ZendObject>`] wrapper. /// /// # Panics /// /// Panics if allocating memory for the object fails, or if the `stdClass` /// class entry has not been registered with PHP yet. /// /// # Example /// /// ```no_run /// use ext_php_rs::types::ZendObject; /// /// let mut obj = ZendObject::new_stdclass(); /// /// obj.set_property("hello", "world"); /// ``` pub fn new_stdclass() -> ZBox<Self> { // SAFETY: This will be `NULL` until it is initialized. `as_ref()` checks for // null, so we can panic if it's null. Self::new(ce::stdclass()) } /// Converts a class object into an owned [`ZendObject`]. This removes any /// possibility of accessing the underlying attached Rust struct. pub fn from_class_object<T: RegisteredClass>(obj: ZBox<ZendClassObject<T>>) -> ZBox<Self> { let this = obj.into_raw(); // SAFETY: Consumed box must produce a well-aligned non-null pointer. unsafe { ZBox::from_raw(this.get_mut_zend_obj()) } } /// Attempts to retrieve the class name of the object. pub fn get_class_name(&self) -> Result<String> { unsafe { self.handlers()? .get_class_name .and_then(|f| f(self).as_ref()) .ok_or(Error::InvalidScope) .and_then(|s| s.try_into()) } } /// Checks if the given object is an instance of a registered class with /// Rust type `T`. pub fn is_instance<T: RegisteredClass>(&self) -> bool { (self.ce as *const ClassEntry).eq(&(T::get_metadata().ce() as *const _)) } /// Attempts to read a property from the Object. Returns a result containing /// the value of the property if it exists and can be read, and an /// [`Error`] otherwise. /// /// # Parameters /// /// * `name` - The name of the property. /// * `query` - The type of query to use when attempting to get a property. pub fn get_property<'a, T>(&'a self, name: &str) -> Result<T> where T: FromZval<'a>, { if!self.has_property(name, PropertyQuery::Exists)? { return Err(Error::InvalidProperty); } let mut name = ZendStr::new(name, false)?; let mut rv = Zval::new(); let zv = unsafe { self.handlers()?.read_property.ok_or(Error::InvalidScope)?( self.mut_ptr(), name.deref_mut(), 1, std::ptr::null_mut(), &mut rv, ) .as_ref() } .ok_or(Error::InvalidScope)?; T::from_zval(zv).ok_or_else(|| Error::ZvalConversion(zv.get_type())) } /// Attempts to set a property on the object. /// /// # Parameters /// /// * `name` - The name of the property. /// * `value` - The value to set the property to. pub fn set_property(&mut self, name: &str, value: impl IntoZval) -> Result<()> { let mut name = ZendStr::new(name, false)?; let mut value = value.into_zval(false)?; unsafe { self.handlers()?.write_property.ok_or(Error::InvalidScope)?( self, name.deref_mut(), &mut value, std::ptr::null_mut(), ) .as_ref() } .ok_or(Error::InvalidScope)?; Ok(()) } /// Checks if a property exists on an object. Takes a property name and /// query parameter, which defines what classifies if a property exists /// or not. See [`PropertyQuery`] for more information. /// /// # Parameters /// /// * `name` - The name of the property. /// * `query` - The 'query' to classify if a property exists. pub fn has_property(&self, name: &str, query: PropertyQuery) -> Result<bool> { let mut name = ZendStr::new(name, false)?; Ok(unsafe { self.handlers()?.has_property.ok_or(Error::InvalidScope)?( self.mut_ptr(), name.deref_mut(), query as _, std::ptr::null_mut(), ) } > 0) } /// Attempts to retrieve the properties of the object. Returned inside a /// Zend Hashtable. pub fn get_properties(&self) -> Result<&HashTable> { unsafe { self.handlers()? .get_properties .and_then(|props| props(self.mut_ptr()).as_ref()) .ok_or(Error::InvalidScope) } } /// Extracts some type from a Zend object. /// /// This is a wrapper function around `FromZendObject::extract()`. pub fn extract<'a, T>(&'a self) -> Result<T> where T: FromZendObject<'a>, { T::from_zend_object(self) } /// Attempts to retrieve a reference to the object handlers. #[inline] unsafe fn handlers(&self) -> Result<&ZendObjectHandlers> { self.handlers.as_ref().ok_or(Error::InvalidScope) } /// Returns a mutable pointer to `self`, regardless of the type of /// reference. Only to be used in situations where a C function requires /// a mutable pointer but does not modify the underlying data. #[inline] fn mut_ptr(&self) -> *mut Self { (self as *const Self) as *mut Self } } unsafe impl ZBoxable for ZendObject { fn free(&mut self) { unsafe { ext_php_rs_zend_object_release(self) } } } impl Debug for ZendObject { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut dbg = f.debug_struct( self.get_class_name() .unwrap_or_else(|_| "ZendObject".to_string()) .as_str(), ); if let Ok(props) = self.get_properties() { for (id, key, val) in props.iter() { dbg.field(key.unwrap_or_else(|| id.to_string()).as_str(), val); } } dbg.finish() } } impl<'a> FromZval<'a> for &'a ZendObject { const TYPE: DataType = DataType::Object(None); fn from_zval(zval: &'a Zval) -> Option<Self> { zval.object() } } impl<'a> FromZvalMut<'a> for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); fn from_zval_mut(zval: &'a mut Zval) -> Option<Self> { zval.object_mut() } } impl IntoZval for ZBox<ZendObject> { const TYPE: DataType = DataType::Object(None); #[inline] fn set_zval(mut self, zv: &mut Zval, _: bool) -> Result<()> { // We must decrement the refcounter on the object before inserting into the // zval, as the reference counter will be incremented on add. // NOTE(david): again is this needed, we increment in `set_object`. self.dec_count(); zv.set_object(self.into_raw()); Ok(()) } } impl<'a> IntoZval for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); #[inline] fn set_zval(self, zv: &mut Zval, _: bool) -> Result<()> { zv.set_object(self); Ok(()) } } impl FromZendObject<'_> for String { fn from_zend_object(obj: &ZendObject) -> Result<Self> { let mut ret = Zval::new(); unsafe { zend_call_known_function( (*obj.ce).__tostring, obj as *const _ as *mut _, obj.ce, &mut ret, 0, std::ptr::null_mut(), std::ptr::null_mut(), ); } if let Some(err) = ExecutorGlobals::take_exception() { // TODO: become an error let class_name = obj.get_class_name(); panic!( "Uncaught exception during call to {}::__toString(): {:?}", class_name.expect("unable to determine class name"), err ); } else if let Some(output) = ret.extract() { Ok(output) } else
} } impl<T: RegisteredClass> From<ZBox<ZendClassObject<T>>> for ZBox<ZendObject> { #[inline] fn from(obj: ZBox<ZendClassObject<T>>) -> Self { ZendObject::from_class_object(obj) } } /// Different ways to query if a property exists. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[repr(u32)] pub enum PropertyQuery { /// Property exists and is not NULL. Isset = ZEND_PROPERTY_ISSET, /// Property is not empty. NotEmpty = ZEND_ISEMPTY, /// Property exists. Exists = ZEND_PROPERTY_EXISTS, }
{ // TODO: become an error let class_name = obj.get_class_name(); panic!( "{}::__toString() must return a string", class_name.expect("unable to determine class name"), ); }
conditional_block
object.rs
//! Represents an object in PHP. Allows for overriding the internal object used //! by classes, allowing users to store Rust data inside a PHP object. use std::{convert::TryInto, fmt::Debug, ops::DerefMut}; use crate::{ boxed::{ZBox, ZBoxable}, class::RegisteredClass, convert::{FromZendObject, FromZval, FromZvalMut, IntoZval}, error::{Error, Result}, ffi::{ ext_php_rs_zend_object_release, zend_call_known_function, zend_object, zend_objects_new, HashTable, ZEND_ISEMPTY, ZEND_PROPERTY_EXISTS, ZEND_PROPERTY_ISSET, }, flags::DataType, rc::PhpRc, types::{ZendClassObject, ZendStr, Zval}, zend::{ce, ClassEntry, ExecutorGlobals, ZendObjectHandlers}, }; /// A PHP object. /// /// This type does not maintain any information about its type, for example, /// classes with have associated Rust structs cannot be accessed through this /// type. [`ZendClassObject`] is used for this purpose, and you can convert /// between the two. pub type ZendObject = zend_object; impl ZendObject { /// Creates a new [`ZendObject`], returned inside an [`ZBox<ZendObject>`] /// wrapper. /// /// # Parameters /// /// * `ce` - The type of class the new object should be an instance of. /// /// # Panics /// /// Panics when allocating memory for the new object fails. pub fn new(ce: &ClassEntry) -> ZBox<Self> { // SAFETY: Using emalloc to allocate memory inside Zend arena. Casting `ce` to // `*mut` is valid as the function will not mutate `ce`. unsafe { let ptr = zend_objects_new(ce as *const _ as *mut _); ZBox::from_raw( ptr.as_mut() .expect("Failed to allocate memory for Zend object"), ) } } /// Creates a new `stdClass` instance, returned inside an /// [`ZBox<ZendObject>`] wrapper. /// /// # Panics /// /// Panics if allocating memory for the object fails, or if the `stdClass` /// class entry has not been registered with PHP yet. /// /// # Example /// /// ```no_run /// use ext_php_rs::types::ZendObject; /// /// let mut obj = ZendObject::new_stdclass(); /// /// obj.set_property("hello", "world"); /// ``` pub fn new_stdclass() -> ZBox<Self> { // SAFETY: This will be `NULL` until it is initialized. `as_ref()` checks for // null, so we can panic if it's null. Self::new(ce::stdclass()) } /// Converts a class object into an owned [`ZendObject`]. This removes any /// possibility of accessing the underlying attached Rust struct. pub fn from_class_object<T: RegisteredClass>(obj: ZBox<ZendClassObject<T>>) -> ZBox<Self> { let this = obj.into_raw(); // SAFETY: Consumed box must produce a well-aligned non-null pointer. unsafe { ZBox::from_raw(this.get_mut_zend_obj()) } } /// Attempts to retrieve the class name of the object. pub fn get_class_name(&self) -> Result<String> { unsafe { self.handlers()? .get_class_name .and_then(|f| f(self).as_ref()) .ok_or(Error::InvalidScope) .and_then(|s| s.try_into()) } } /// Checks if the given object is an instance of a registered class with /// Rust type `T`. pub fn is_instance<T: RegisteredClass>(&self) -> bool { (self.ce as *const ClassEntry).eq(&(T::get_metadata().ce() as *const _)) } /// Attempts to read a property from the Object. Returns a result containing /// the value of the property if it exists and can be read, and an /// [`Error`] otherwise. /// /// # Parameters /// /// * `name` - The name of the property. /// * `query` - The type of query to use when attempting to get a property. pub fn get_property<'a, T>(&'a self, name: &str) -> Result<T> where T: FromZval<'a>, { if!self.has_property(name, PropertyQuery::Exists)? { return Err(Error::InvalidProperty); } let mut name = ZendStr::new(name, false)?; let mut rv = Zval::new(); let zv = unsafe { self.handlers()?.read_property.ok_or(Error::InvalidScope)?( self.mut_ptr(), name.deref_mut(), 1, std::ptr::null_mut(), &mut rv, ) .as_ref() } .ok_or(Error::InvalidScope)?; T::from_zval(zv).ok_or_else(|| Error::ZvalConversion(zv.get_type())) } /// Attempts to set a property on the object. /// /// # Parameters /// /// * `name` - The name of the property. /// * `value` - The value to set the property to. pub fn set_property(&mut self, name: &str, value: impl IntoZval) -> Result<()> { let mut name = ZendStr::new(name, false)?; let mut value = value.into_zval(false)?; unsafe { self.handlers()?.write_property.ok_or(Error::InvalidScope)?( self, name.deref_mut(), &mut value, std::ptr::null_mut(), ) .as_ref() } .ok_or(Error::InvalidScope)?; Ok(()) } /// Checks if a property exists on an object. Takes a property name and /// query parameter, which defines what classifies if a property exists /// or not. See [`PropertyQuery`] for more information. /// /// # Parameters /// /// * `name` - The name of the property. /// * `query` - The 'query' to classify if a property exists. pub fn has_property(&self, name: &str, query: PropertyQuery) -> Result<bool> { let mut name = ZendStr::new(name, false)?; Ok(unsafe { self.handlers()?.has_property.ok_or(Error::InvalidScope)?( self.mut_ptr(), name.deref_mut(), query as _, std::ptr::null_mut(), ) } > 0) } /// Attempts to retrieve the properties of the object. Returned inside a /// Zend Hashtable. pub fn get_properties(&self) -> Result<&HashTable> { unsafe { self.handlers()? .get_properties .and_then(|props| props(self.mut_ptr()).as_ref()) .ok_or(Error::InvalidScope) } } /// Extracts some type from a Zend object. /// /// This is a wrapper function around `FromZendObject::extract()`. pub fn extract<'a, T>(&'a self) -> Result<T> where T: FromZendObject<'a>, { T::from_zend_object(self) } /// Attempts to retrieve a reference to the object handlers. #[inline] unsafe fn handlers(&self) -> Result<&ZendObjectHandlers> { self.handlers.as_ref().ok_or(Error::InvalidScope) } /// Returns a mutable pointer to `self`, regardless of the type of /// reference. Only to be used in situations where a C function requires /// a mutable pointer but does not modify the underlying data. #[inline] fn mut_ptr(&self) -> *mut Self { (self as *const Self) as *mut Self } } unsafe impl ZBoxable for ZendObject { fn free(&mut self) { unsafe { ext_php_rs_zend_object_release(self) } } } impl Debug for ZendObject { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut dbg = f.debug_struct( self.get_class_name() .unwrap_or_else(|_| "ZendObject".to_string()) .as_str(), ); if let Ok(props) = self.get_properties() { for (id, key, val) in props.iter() { dbg.field(key.unwrap_or_else(|| id.to_string()).as_str(), val); } } dbg.finish() } } impl<'a> FromZval<'a> for &'a ZendObject { const TYPE: DataType = DataType::Object(None); fn from_zval(zval: &'a Zval) -> Option<Self> { zval.object() } } impl<'a> FromZvalMut<'a> for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); fn from_zval_mut(zval: &'a mut Zval) -> Option<Self> { zval.object_mut() } } impl IntoZval for ZBox<ZendObject> { const TYPE: DataType = DataType::Object(None); #[inline] fn set_zval(mut self, zv: &mut Zval, _: bool) -> Result<()> { // We must decrement the refcounter on the object before inserting into the // zval, as the reference counter will be incremented on add. // NOTE(david): again is this needed, we increment in `set_object`. self.dec_count(); zv.set_object(self.into_raw()); Ok(()) } } impl<'a> IntoZval for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); #[inline] fn set_zval(self, zv: &mut Zval, _: bool) -> Result<()>
} impl FromZendObject<'_> for String { fn from_zend_object(obj: &ZendObject) -> Result<Self> { let mut ret = Zval::new(); unsafe { zend_call_known_function( (*obj.ce).__tostring, obj as *const _ as *mut _, obj.ce, &mut ret, 0, std::ptr::null_mut(), std::ptr::null_mut(), ); } if let Some(err) = ExecutorGlobals::take_exception() { // TODO: become an error let class_name = obj.get_class_name(); panic!( "Uncaught exception during call to {}::__toString(): {:?}", class_name.expect("unable to determine class name"), err ); } else if let Some(output) = ret.extract() { Ok(output) } else { // TODO: become an error let class_name = obj.get_class_name(); panic!( "{}::__toString() must return a string", class_name.expect("unable to determine class name"), ); } } } impl<T: RegisteredClass> From<ZBox<ZendClassObject<T>>> for ZBox<ZendObject> { #[inline] fn from(obj: ZBox<ZendClassObject<T>>) -> Self { ZendObject::from_class_object(obj) } } /// Different ways to query if a property exists. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[repr(u32)] pub enum PropertyQuery { /// Property exists and is not NULL. Isset = ZEND_PROPERTY_ISSET, /// Property is not empty. NotEmpty = ZEND_ISEMPTY, /// Property exists. Exists = ZEND_PROPERTY_EXISTS, }
{ zv.set_object(self); Ok(()) }
identifier_body
public_key.rs
use crate::key::{KeyError, PublicKey}; use crate::ssh::decode::SshComplexTypeDecode; use crate::ssh::encode::SshComplexTypeEncode; use std::str::FromStr; use std::{io, string}; use thiserror::Error; #[derive(Debug, Error)] pub enum SshPublicKeyError { #[error(transparent)] IoError(#[from] io::Error), #[error(transparent)] FromUtf8Error(#[from] string::FromUtf8Error), #[error(transparent)] RsaError(#[from] rsa::errors::Error), #[error(transparent)] Base64DecodeError(#[from] base64::DecodeError), #[error("Unknown key type. We only support RSA")] UnknownKeyType, #[error(transparent)] KeyError(#[from] KeyError), } #[derive(Debug, Clone, PartialEq, Eq)] pub enum SshBasePublicKey { Rsa(PublicKey), Ec(PublicKey), Ed(PublicKey), } #[derive(Debug, Clone, PartialEq, Eq)]
pub struct SshPublicKey { pub inner_key: SshBasePublicKey, pub comment: String, } impl SshPublicKey { pub fn to_string(&self) -> Result<String, SshPublicKeyError> { let mut buffer = Vec::with_capacity(1024); self.encode(&mut buffer)?; Ok(String::from_utf8(buffer)?) } } impl FromStr for SshPublicKey { type Err = SshPublicKeyError; fn from_str(s: &str) -> Result<Self, Self::Err> { SshComplexTypeDecode::decode(s.as_bytes()) } } #[cfg(test)] mod tests { use super::*; use crate::test_files; use num_bigint_dig::BigUint; use rstest::rstest; #[test] fn decode_ssh_rsa_4096_public_key() { // ssh-keygen -t rsa -b 4096 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDbUCK4dH1n4dOFBv/sjfMma4q5qe7SZ49j2GODGKr8DueZMWYLTck61uUMMlVBT3XyX6me6X4WsBoijzQWvgwpLCGTqlhQTntm5FphXHHkKxFvjMhPzCnHNS+L0ebzewcecsY5rtgw+6BhFwdZGhFBfif1/6s9q7y7+8Ge3hUIEqLdiMDDzxc66zIaW26jZxO4BMHuKp7Xln2JeDjsRHvz0vBNAddOfkvtp+gM72OH4tm9wS/V8bVOZ68oU0os8DuiEGnwA5RnjOjaFdHWt1mD8B+nRINxI8zYyQcqp3t4p552P0Frhvjgixi67Ryax0DUNuzN2MpQ0ORUgRkfy/xWvImUseP/BfqvNiWkFAWHNDDSsc50Wmr+g0JicG2gowHLYPxKRjLIbOq+JgxHrE4TdaA2NJoeUppJgWU4yuGl5fx1G+Bcdr0C+lsMj14Hp+aGajEOLQ7Mq3HzWEox9G1KgN4r266Mofd8T4vrjF6Ja9E+pp0pXgEv2cvtYJLP0qdrHWafb3lWsP4hJWnv/NaXP6ZAxiEeHsigrY98kmgZbHm/6AmiBJ7bKQ/S/PelYj3mTL0aYkGF79qVtAzSl7yI9yVyHsl7dt5jdmp6+IofuEtNfnAcfoaSLu0Ojotp9VBMvil6ojScbJNLBL8tGN4+urIcsNUvVjAOnwc3nothKw== [email protected]\r\n"; let public_key = SshPublicKey::from_str(ssh_public_key).unwrap(); assert_eq!("[email protected]".to_owned(), public_key.comment); assert_eq!( SshBasePublicKey::Rsa(PublicKey::from_rsa_components( &BigUint::from_bytes_be(&[ 219, 80, 34, 184, 116, 125, 103, 225, 211, 133, 6, 255, 236, 141, 243, 38, 107, 138, 185, 169, 238, 210, 103, 143, 99, 216, 99, 131, 24, 170, 252, 14, 231, 153, 49, 102, 11, 77, 201, 58, 214, 229, 12, 50, 85, 65, 79, 117, 242, 95, 169, 158, 233, 126, 22, 176, 26, 34, 143, 52, 22, 190, 12, 41, 44, 33, 147, 170, 88, 80, 78, 123, 102, 228, 90, 97, 92, 113, 228, 43, 17, 111, 140, 200, 79, 204, 41, 199, 53, 47, 139, 209, 230, 243, 123, 7, 30, 114, 198, 57, 174, 216, 48, 251, 160, 97, 23, 7, 89, 26, 17, 65, 126, 39, 245, 255, 171, 61, 171, 188, 187, 251, 193, 158, 222, 21, 8, 18, 162, 221, 136, 192, 195, 207, 23, 58, 235, 50, 26, 91, 110, 163, 103, 19, 184, 4, 193, 238, 42, 158, 215, 150, 125, 137, 120, 56, 236, 68, 123, 243, 210, 240, 77, 1, 215, 78, 126, 75, 237, 167, 232, 12, 239, 99, 135, 226, 217, 189, 193, 47, 213, 241, 181, 78, 103, 175, 40, 83, 74, 44, 240, 59, 162, 16, 105, 240, 3, 148, 103, 140, 232, 218, 21, 209, 214, 183, 89, 131, 240, 31, 167, 68, 131, 113, 35, 204, 216, 201, 7, 42, 167, 123, 120, 167, 158, 118, 63, 65, 107, 134, 248, 224, 139, 24, 186, 237, 28, 154, 199, 64, 212, 54, 236, 205, 216, 202, 80, 208, 228, 84, 129, 25, 31, 203, 252, 86, 188, 137, 148, 177, 227, 255, 5, 250, 175, 54, 37, 164, 20, 5, 135, 52, 48, 210, 177, 206, 116, 90, 106, 254, 131, 66, 98, 112, 109, 160, 163, 1, 203, 96, 252, 74, 70, 50, 200, 108, 234, 190, 38, 12, 71, 172, 78, 19, 117, 160, 54, 52, 154, 30, 82, 154, 73, 129, 101, 56, 202, 225, 165, 229, 252, 117, 27, 224, 92, 118, 189, 2, 250, 91, 12, 143, 94, 7, 167, 230, 134, 106, 49, 14, 45, 14, 204, 171, 113, 243, 88, 74, 49, 244, 109, 74, 128, 222, 43, 219, 174, 140, 161, 247, 124, 79, 139, 235, 140, 94, 137, 107, 209, 62, 166, 157, 41, 94, 1, 47, 217, 203, 237, 96, 146, 207, 210, 167, 107, 29, 102, 159, 111, 121, 86, 176, 254, 33, 37, 105, 239, 252, 214, 151, 63, 166, 64, 198, 33, 30, 30, 200, 160, 173, 143, 124, 146, 104, 25, 108, 121, 191, 232, 9, 162, 4, 158, 219, 41, 15, 210, 252, 247, 165, 98, 61, 230, 76, 189, 26, 98, 65, 133, 239, 218, 149, 180, 12, 210, 151, 188, 136, 247, 37, 114, 30, 201, 123, 118, 222, 99, 118, 106, 122, 248, 138, 31, 184, 75, 77, 126, 112, 28, 126, 134, 146, 46, 237, 14, 142, 139, 105, 245, 80, 76, 190, 41, 122, 162, 52, 156, 108, 147, 75, 4, 191, 45, 24, 222, 62, 186, 178, 28, 176, 213, 47, 86, 48, 14, 159, 7, 55, 158, 139, 97, 43 ]), &BigUint::from_bytes_be(&[1, 0, 1]) )), public_key.inner_key ); } #[test] fn decode_ssh_rsa_2048_public_key() { // ssh-keygen -t rsa -b 2048 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI9ht2g2qOPgSG5huVYjFUouyaw59/6QuQqUVGwgnITlhRbM+bkvJQfcuiqcv+vD9/86Dfugk79sSfg/aVK+V/plqAAZoujz/wALDjEphSxAUcAR+t4i2F39Pa71MSc37I9L30z31tcba1X7od7hzrVMl9iurkOyBC4xcIWa1H8h0mDyoXyWPTqoTONDUe9dB1eu6GbixCfUcxvdVt0pAVJTdOmbNXKwRo5WXfMrsqKsFT2Acg4Vm4TfLShSSUW4rqM6GOBCfF6jnxFvTSDentH5hykjWL3lMCghD+1hJyOdnMHJC/5qTUGOB86MxsR4RCXqS+LZrGpMScVyDQge7r [email protected]\r\n"; let public_key: SshPublicKey = SshPublicKey::from_str(ssh_public_key).unwrap(); assert_eq!("[email protected]".to_owned(), public_key.comment); assert_eq!( SshBasePublicKey::Rsa(PublicKey::from_rsa_components( &BigUint::from_bytes_be(&[ 200, 246, 27, 118, 131, 106, 142, 62, 4, 134, 230, 27, 149, 98, 49, 84, 162, 236, 154, 195, 159, 127, 233, 11, 144, 169, 69, 70, 194, 9, 200, 78, 88, 81, 108, 207, 155, 146, 242, 80, 125, 203, 162, 169, 203, 254, 188, 63, 127, 243, 160, 223, 186, 9, 59, 246, 196, 159, 131, 246, 149, 43, 229, 127, 166, 90, 128, 1, 154, 46, 143, 63, 240, 0, 176, 227, 18, 152, 82, 196, 5, 28, 1, 31, 173, 226, 45, 133, 223, 211, 218, 239, 83, 18, 115, 126, 200, 244, 189, 244, 207, 125, 109, 113, 182, 181, 95, 186, 29, 238, 28, 235, 84, 201, 125, 138, 234, 228, 59, 32, 66, 227, 23, 8, 89, 173, 71, 242, 29, 38, 15, 42, 23, 201, 99, 211, 170, 132, 206, 52, 53, 30, 245, 208, 117, 122, 238, 134, 110, 44, 66, 125, 71, 49, 189, 213, 109, 210, 144, 21, 37, 55, 78, 153, 179, 87, 43, 4, 104, 229, 101, 223, 50, 187, 42, 42, 193, 83, 216, 7, 32, 225, 89, 184, 77, 242, 210, 133, 36, 148, 91, 138, 234, 51, 161, 142, 4, 39, 197, 234, 57, 241, 22, 244, 210, 13, 233, 237, 31, 152, 114, 146, 53, 139, 222, 83, 2, 130, 16, 254, 214, 18, 114, 57, 217, 204, 28, 144, 191, 230, 164, 212, 24, 224, 124, 232, 204, 108, 71, 132, 66, 94, 164, 190, 45, 154, 198, 164, 196, 156, 87, 32, 208, 129, 238, 235 ]), &BigUint::from_bytes_be(&[1, 0, 1]) )), public_key.inner_key ); } #[test] fn encode_ssh_rsa_4096_public_key() { // ssh-keygen -t rsa -b 4096 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDbUCK4dH1n4dOFBv/sjfMma4q5qe7SZ49j2GODGKr8DueZMWYLTck61uUMMlVBT3XyX6me6X4WsBoijzQWvgwpLCGTqlhQTntm5FphXHHkKxFvjMhPzCnHNS+L0ebzewcecsY5rtgw+6BhFwdZGhFBfif1/6s9q7y7+8Ge3hUIEqLdiMDDzxc66zIaW26jZxO4BMHuKp7Xln2JeDjsRHvz0vBNAddOfkvtp+gM72OH4tm9wS/V8bVOZ68oU0os8DuiEGnwA5RnjOjaFdHWt1mD8B+nRINxI8zYyQcqp3t4p552P0Frhvjgixi67Ryax0DUNuzN2MpQ0ORUgRkfy/xWvImUseP/BfqvNiWkFAWHNDDSsc50Wmr+g0JicG2gowHLYPxKRjLIbOq+JgxHrE4TdaA2NJoeUppJgWU4yuGl5fx1G+Bcdr0C+lsMj14Hp+aGajEOLQ7Mq3HzWEox9G1KgN4r266Mofd8T4vrjF6Ja9E+pp0pXgEv2cvtYJLP0qdrHWafb3lWsP4hJWnv/NaXP6ZAxiEeHsigrY98kmgZbHm/6AmiBJ7bKQ/S/PelYj3mTL0aYkGF79qVtAzSl7yI9yVyHsl7dt5jdmp6+IofuEtNfnAcfoaSLu0Ojotp9VBMvil6ojScbJNLBL8tGN4+urIcsNUvVjAOnwc3nothKw== [email protected]\r\n"; let public_key = SshPublicKey::from_str(ssh_public_key).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(ssh_public_key, ssh_public_key_after.as_str()); } #[test] fn encode_ssh_rsa_2048_public_key() { // ssh-keygen -t rsa -b 4096 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI9ht2g2qOPgSG5huVYjFUouyaw59/6QuQqUVGwgnITlhRbM+bkvJQfcuiqcv+vD9/86Dfugk79sSfg/aVK+V/plqAAZoujz/wALDjEphSxAUcAR+t4i2F39Pa71MSc37I9L30z31tcba1X7od7hzrVMl9iurkOyBC4xcIWa1H8h0mDyoXyWPTqoTONDUe9dB1eu6GbixCfUcxvdVt0pAVJTdOmbNXKwRo5WXfMrsqKsFT2Acg4Vm4TfLShSSUW4rqM6GOBCfF6jnxFvTSDentH5hykjWL3lMCghD+1hJyOdnMHJC/5qTUGOB86MxsR4RCXqS+LZrGpMScVyDQge7r [email protected]\r\n"; let public_key = SshPublicKey::from_str(ssh_public_key).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(ssh_public_key, ssh_public_key_after.as_str()); } #[rstest] #[case(test_files::SSH_PUBLIC_KEY_EC_P256)] #[case(test_files::SSH_PUBLIC_KEY_EC_P384)] #[case(test_files::SSH_PUBLIC_KEY_EC_P521)] fn ecdsa_roundtrip(#[case] key_str: &str) { let public_key = SshPublicKey::from_str(key_str).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(key_str, ssh_public_key_after.as_str()); } #[test] fn ed25519_roundtrip() { let public_key = SshPublicKey::from_str(test_files::SSH_PUBLIC_KEY_ED25519).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(test_files::SSH_PUBLIC_KEY_ED25519, ssh_public_key_after.as_str()); } }
random_line_split
public_key.rs
use crate::key::{KeyError, PublicKey}; use crate::ssh::decode::SshComplexTypeDecode; use crate::ssh::encode::SshComplexTypeEncode; use std::str::FromStr; use std::{io, string}; use thiserror::Error; #[derive(Debug, Error)] pub enum SshPublicKeyError { #[error(transparent)] IoError(#[from] io::Error), #[error(transparent)] FromUtf8Error(#[from] string::FromUtf8Error), #[error(transparent)] RsaError(#[from] rsa::errors::Error), #[error(transparent)] Base64DecodeError(#[from] base64::DecodeError), #[error("Unknown key type. We only support RSA")] UnknownKeyType, #[error(transparent)] KeyError(#[from] KeyError), } #[derive(Debug, Clone, PartialEq, Eq)] pub enum SshBasePublicKey { Rsa(PublicKey), Ec(PublicKey), Ed(PublicKey), } #[derive(Debug, Clone, PartialEq, Eq)] pub struct SshPublicKey { pub inner_key: SshBasePublicKey, pub comment: String, } impl SshPublicKey { pub fn to_string(&self) -> Result<String, SshPublicKeyError> { let mut buffer = Vec::with_capacity(1024); self.encode(&mut buffer)?; Ok(String::from_utf8(buffer)?) } } impl FromStr for SshPublicKey { type Err = SshPublicKeyError; fn from_str(s: &str) -> Result<Self, Self::Err> { SshComplexTypeDecode::decode(s.as_bytes()) } } #[cfg(test)] mod tests { use super::*; use crate::test_files; use num_bigint_dig::BigUint; use rstest::rstest; #[test] fn decode_ssh_rsa_4096_public_key() { // ssh-keygen -t rsa -b 4096 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDbUCK4dH1n4dOFBv/sjfMma4q5qe7SZ49j2GODGKr8DueZMWYLTck61uUMMlVBT3XyX6me6X4WsBoijzQWvgwpLCGTqlhQTntm5FphXHHkKxFvjMhPzCnHNS+L0ebzewcecsY5rtgw+6BhFwdZGhFBfif1/6s9q7y7+8Ge3hUIEqLdiMDDzxc66zIaW26jZxO4BMHuKp7Xln2JeDjsRHvz0vBNAddOfkvtp+gM72OH4tm9wS/V8bVOZ68oU0os8DuiEGnwA5RnjOjaFdHWt1mD8B+nRINxI8zYyQcqp3t4p552P0Frhvjgixi67Ryax0DUNuzN2MpQ0ORUgRkfy/xWvImUseP/BfqvNiWkFAWHNDDSsc50Wmr+g0JicG2gowHLYPxKRjLIbOq+JgxHrE4TdaA2NJoeUppJgWU4yuGl5fx1G+Bcdr0C+lsMj14Hp+aGajEOLQ7Mq3HzWEox9G1KgN4r266Mofd8T4vrjF6Ja9E+pp0pXgEv2cvtYJLP0qdrHWafb3lWsP4hJWnv/NaXP6ZAxiEeHsigrY98kmgZbHm/6AmiBJ7bKQ/S/PelYj3mTL0aYkGF79qVtAzSl7yI9yVyHsl7dt5jdmp6+IofuEtNfnAcfoaSLu0Ojotp9VBMvil6ojScbJNLBL8tGN4+urIcsNUvVjAOnwc3nothKw== [email protected]\r\n"; let public_key = SshPublicKey::from_str(ssh_public_key).unwrap(); assert_eq!("[email protected]".to_owned(), public_key.comment); assert_eq!( SshBasePublicKey::Rsa(PublicKey::from_rsa_components( &BigUint::from_bytes_be(&[ 219, 80, 34, 184, 116, 125, 103, 225, 211, 133, 6, 255, 236, 141, 243, 38, 107, 138, 185, 169, 238, 210, 103, 143, 99, 216, 99, 131, 24, 170, 252, 14, 231, 153, 49, 102, 11, 77, 201, 58, 214, 229, 12, 50, 85, 65, 79, 117, 242, 95, 169, 158, 233, 126, 22, 176, 26, 34, 143, 52, 22, 190, 12, 41, 44, 33, 147, 170, 88, 80, 78, 123, 102, 228, 90, 97, 92, 113, 228, 43, 17, 111, 140, 200, 79, 204, 41, 199, 53, 47, 139, 209, 230, 243, 123, 7, 30, 114, 198, 57, 174, 216, 48, 251, 160, 97, 23, 7, 89, 26, 17, 65, 126, 39, 245, 255, 171, 61, 171, 188, 187, 251, 193, 158, 222, 21, 8, 18, 162, 221, 136, 192, 195, 207, 23, 58, 235, 50, 26, 91, 110, 163, 103, 19, 184, 4, 193, 238, 42, 158, 215, 150, 125, 137, 120, 56, 236, 68, 123, 243, 210, 240, 77, 1, 215, 78, 126, 75, 237, 167, 232, 12, 239, 99, 135, 226, 217, 189, 193, 47, 213, 241, 181, 78, 103, 175, 40, 83, 74, 44, 240, 59, 162, 16, 105, 240, 3, 148, 103, 140, 232, 218, 21, 209, 214, 183, 89, 131, 240, 31, 167, 68, 131, 113, 35, 204, 216, 201, 7, 42, 167, 123, 120, 167, 158, 118, 63, 65, 107, 134, 248, 224, 139, 24, 186, 237, 28, 154, 199, 64, 212, 54, 236, 205, 216, 202, 80, 208, 228, 84, 129, 25, 31, 203, 252, 86, 188, 137, 148, 177, 227, 255, 5, 250, 175, 54, 37, 164, 20, 5, 135, 52, 48, 210, 177, 206, 116, 90, 106, 254, 131, 66, 98, 112, 109, 160, 163, 1, 203, 96, 252, 74, 70, 50, 200, 108, 234, 190, 38, 12, 71, 172, 78, 19, 117, 160, 54, 52, 154, 30, 82, 154, 73, 129, 101, 56, 202, 225, 165, 229, 252, 117, 27, 224, 92, 118, 189, 2, 250, 91, 12, 143, 94, 7, 167, 230, 134, 106, 49, 14, 45, 14, 204, 171, 113, 243, 88, 74, 49, 244, 109, 74, 128, 222, 43, 219, 174, 140, 161, 247, 124, 79, 139, 235, 140, 94, 137, 107, 209, 62, 166, 157, 41, 94, 1, 47, 217, 203, 237, 96, 146, 207, 210, 167, 107, 29, 102, 159, 111, 121, 86, 176, 254, 33, 37, 105, 239, 252, 214, 151, 63, 166, 64, 198, 33, 30, 30, 200, 160, 173, 143, 124, 146, 104, 25, 108, 121, 191, 232, 9, 162, 4, 158, 219, 41, 15, 210, 252, 247, 165, 98, 61, 230, 76, 189, 26, 98, 65, 133, 239, 218, 149, 180, 12, 210, 151, 188, 136, 247, 37, 114, 30, 201, 123, 118, 222, 99, 118, 106, 122, 248, 138, 31, 184, 75, 77, 126, 112, 28, 126, 134, 146, 46, 237, 14, 142, 139, 105, 245, 80, 76, 190, 41, 122, 162, 52, 156, 108, 147, 75, 4, 191, 45, 24, 222, 62, 186, 178, 28, 176, 213, 47, 86, 48, 14, 159, 7, 55, 158, 139, 97, 43 ]), &BigUint::from_bytes_be(&[1, 0, 1]) )), public_key.inner_key ); } #[test] fn
() { // ssh-keygen -t rsa -b 2048 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI9ht2g2qOPgSG5huVYjFUouyaw59/6QuQqUVGwgnITlhRbM+bkvJQfcuiqcv+vD9/86Dfugk79sSfg/aVK+V/plqAAZoujz/wALDjEphSxAUcAR+t4i2F39Pa71MSc37I9L30z31tcba1X7od7hzrVMl9iurkOyBC4xcIWa1H8h0mDyoXyWPTqoTONDUe9dB1eu6GbixCfUcxvdVt0pAVJTdOmbNXKwRo5WXfMrsqKsFT2Acg4Vm4TfLShSSUW4rqM6GOBCfF6jnxFvTSDentH5hykjWL3lMCghD+1hJyOdnMHJC/5qTUGOB86MxsR4RCXqS+LZrGpMScVyDQge7r [email protected]\r\n"; let public_key: SshPublicKey = SshPublicKey::from_str(ssh_public_key).unwrap(); assert_eq!("[email protected]".to_owned(), public_key.comment); assert_eq!( SshBasePublicKey::Rsa(PublicKey::from_rsa_components( &BigUint::from_bytes_be(&[ 200, 246, 27, 118, 131, 106, 142, 62, 4, 134, 230, 27, 149, 98, 49, 84, 162, 236, 154, 195, 159, 127, 233, 11, 144, 169, 69, 70, 194, 9, 200, 78, 88, 81, 108, 207, 155, 146, 242, 80, 125, 203, 162, 169, 203, 254, 188, 63, 127, 243, 160, 223, 186, 9, 59, 246, 196, 159, 131, 246, 149, 43, 229, 127, 166, 90, 128, 1, 154, 46, 143, 63, 240, 0, 176, 227, 18, 152, 82, 196, 5, 28, 1, 31, 173, 226, 45, 133, 223, 211, 218, 239, 83, 18, 115, 126, 200, 244, 189, 244, 207, 125, 109, 113, 182, 181, 95, 186, 29, 238, 28, 235, 84, 201, 125, 138, 234, 228, 59, 32, 66, 227, 23, 8, 89, 173, 71, 242, 29, 38, 15, 42, 23, 201, 99, 211, 170, 132, 206, 52, 53, 30, 245, 208, 117, 122, 238, 134, 110, 44, 66, 125, 71, 49, 189, 213, 109, 210, 144, 21, 37, 55, 78, 153, 179, 87, 43, 4, 104, 229, 101, 223, 50, 187, 42, 42, 193, 83, 216, 7, 32, 225, 89, 184, 77, 242, 210, 133, 36, 148, 91, 138, 234, 51, 161, 142, 4, 39, 197, 234, 57, 241, 22, 244, 210, 13, 233, 237, 31, 152, 114, 146, 53, 139, 222, 83, 2, 130, 16, 254, 214, 18, 114, 57, 217, 204, 28, 144, 191, 230, 164, 212, 24, 224, 124, 232, 204, 108, 71, 132, 66, 94, 164, 190, 45, 154, 198, 164, 196, 156, 87, 32, 208, 129, 238, 235 ]), &BigUint::from_bytes_be(&[1, 0, 1]) )), public_key.inner_key ); } #[test] fn encode_ssh_rsa_4096_public_key() { // ssh-keygen -t rsa -b 4096 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDbUCK4dH1n4dOFBv/sjfMma4q5qe7SZ49j2GODGKr8DueZMWYLTck61uUMMlVBT3XyX6me6X4WsBoijzQWvgwpLCGTqlhQTntm5FphXHHkKxFvjMhPzCnHNS+L0ebzewcecsY5rtgw+6BhFwdZGhFBfif1/6s9q7y7+8Ge3hUIEqLdiMDDzxc66zIaW26jZxO4BMHuKp7Xln2JeDjsRHvz0vBNAddOfkvtp+gM72OH4tm9wS/V8bVOZ68oU0os8DuiEGnwA5RnjOjaFdHWt1mD8B+nRINxI8zYyQcqp3t4p552P0Frhvjgixi67Ryax0DUNuzN2MpQ0ORUgRkfy/xWvImUseP/BfqvNiWkFAWHNDDSsc50Wmr+g0JicG2gowHLYPxKRjLIbOq+JgxHrE4TdaA2NJoeUppJgWU4yuGl5fx1G+Bcdr0C+lsMj14Hp+aGajEOLQ7Mq3HzWEox9G1KgN4r266Mofd8T4vrjF6Ja9E+pp0pXgEv2cvtYJLP0qdrHWafb3lWsP4hJWnv/NaXP6ZAxiEeHsigrY98kmgZbHm/6AmiBJ7bKQ/S/PelYj3mTL0aYkGF79qVtAzSl7yI9yVyHsl7dt5jdmp6+IofuEtNfnAcfoaSLu0Ojotp9VBMvil6ojScbJNLBL8tGN4+urIcsNUvVjAOnwc3nothKw== [email protected]\r\n"; let public_key = SshPublicKey::from_str(ssh_public_key).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(ssh_public_key, ssh_public_key_after.as_str()); } #[test] fn encode_ssh_rsa_2048_public_key() { // ssh-keygen -t rsa -b 4096 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI9ht2g2qOPgSG5huVYjFUouyaw59/6QuQqUVGwgnITlhRbM+bkvJQfcuiqcv+vD9/86Dfugk79sSfg/aVK+V/plqAAZoujz/wALDjEphSxAUcAR+t4i2F39Pa71MSc37I9L30z31tcba1X7od7hzrVMl9iurkOyBC4xcIWa1H8h0mDyoXyWPTqoTONDUe9dB1eu6GbixCfUcxvdVt0pAVJTdOmbNXKwRo5WXfMrsqKsFT2Acg4Vm4TfLShSSUW4rqM6GOBCfF6jnxFvTSDentH5hykjWL3lMCghD+1hJyOdnMHJC/5qTUGOB86MxsR4RCXqS+LZrGpMScVyDQge7r [email protected]\r\n"; let public_key = SshPublicKey::from_str(ssh_public_key).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(ssh_public_key, ssh_public_key_after.as_str()); } #[rstest] #[case(test_files::SSH_PUBLIC_KEY_EC_P256)] #[case(test_files::SSH_PUBLIC_KEY_EC_P384)] #[case(test_files::SSH_PUBLIC_KEY_EC_P521)] fn ecdsa_roundtrip(#[case] key_str: &str) { let public_key = SshPublicKey::from_str(key_str).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(key_str, ssh_public_key_after.as_str()); } #[test] fn ed25519_roundtrip() { let public_key = SshPublicKey::from_str(test_files::SSH_PUBLIC_KEY_ED25519).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(test_files::SSH_PUBLIC_KEY_ED25519, ssh_public_key_after.as_str()); } }
decode_ssh_rsa_2048_public_key
identifier_name
public_key.rs
use crate::key::{KeyError, PublicKey}; use crate::ssh::decode::SshComplexTypeDecode; use crate::ssh::encode::SshComplexTypeEncode; use std::str::FromStr; use std::{io, string}; use thiserror::Error; #[derive(Debug, Error)] pub enum SshPublicKeyError { #[error(transparent)] IoError(#[from] io::Error), #[error(transparent)] FromUtf8Error(#[from] string::FromUtf8Error), #[error(transparent)] RsaError(#[from] rsa::errors::Error), #[error(transparent)] Base64DecodeError(#[from] base64::DecodeError), #[error("Unknown key type. We only support RSA")] UnknownKeyType, #[error(transparent)] KeyError(#[from] KeyError), } #[derive(Debug, Clone, PartialEq, Eq)] pub enum SshBasePublicKey { Rsa(PublicKey), Ec(PublicKey), Ed(PublicKey), } #[derive(Debug, Clone, PartialEq, Eq)] pub struct SshPublicKey { pub inner_key: SshBasePublicKey, pub comment: String, } impl SshPublicKey { pub fn to_string(&self) -> Result<String, SshPublicKeyError> { let mut buffer = Vec::with_capacity(1024); self.encode(&mut buffer)?; Ok(String::from_utf8(buffer)?) } } impl FromStr for SshPublicKey { type Err = SshPublicKeyError; fn from_str(s: &str) -> Result<Self, Self::Err> { SshComplexTypeDecode::decode(s.as_bytes()) } } #[cfg(test)] mod tests { use super::*; use crate::test_files; use num_bigint_dig::BigUint; use rstest::rstest; #[test] fn decode_ssh_rsa_4096_public_key() { // ssh-keygen -t rsa -b 4096 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDbUCK4dH1n4dOFBv/sjfMma4q5qe7SZ49j2GODGKr8DueZMWYLTck61uUMMlVBT3XyX6me6X4WsBoijzQWvgwpLCGTqlhQTntm5FphXHHkKxFvjMhPzCnHNS+L0ebzewcecsY5rtgw+6BhFwdZGhFBfif1/6s9q7y7+8Ge3hUIEqLdiMDDzxc66zIaW26jZxO4BMHuKp7Xln2JeDjsRHvz0vBNAddOfkvtp+gM72OH4tm9wS/V8bVOZ68oU0os8DuiEGnwA5RnjOjaFdHWt1mD8B+nRINxI8zYyQcqp3t4p552P0Frhvjgixi67Ryax0DUNuzN2MpQ0ORUgRkfy/xWvImUseP/BfqvNiWkFAWHNDDSsc50Wmr+g0JicG2gowHLYPxKRjLIbOq+JgxHrE4TdaA2NJoeUppJgWU4yuGl5fx1G+Bcdr0C+lsMj14Hp+aGajEOLQ7Mq3HzWEox9G1KgN4r266Mofd8T4vrjF6Ja9E+pp0pXgEv2cvtYJLP0qdrHWafb3lWsP4hJWnv/NaXP6ZAxiEeHsigrY98kmgZbHm/6AmiBJ7bKQ/S/PelYj3mTL0aYkGF79qVtAzSl7yI9yVyHsl7dt5jdmp6+IofuEtNfnAcfoaSLu0Ojotp9VBMvil6ojScbJNLBL8tGN4+urIcsNUvVjAOnwc3nothKw== [email protected]\r\n"; let public_key = SshPublicKey::from_str(ssh_public_key).unwrap(); assert_eq!("[email protected]".to_owned(), public_key.comment); assert_eq!( SshBasePublicKey::Rsa(PublicKey::from_rsa_components( &BigUint::from_bytes_be(&[ 219, 80, 34, 184, 116, 125, 103, 225, 211, 133, 6, 255, 236, 141, 243, 38, 107, 138, 185, 169, 238, 210, 103, 143, 99, 216, 99, 131, 24, 170, 252, 14, 231, 153, 49, 102, 11, 77, 201, 58, 214, 229, 12, 50, 85, 65, 79, 117, 242, 95, 169, 158, 233, 126, 22, 176, 26, 34, 143, 52, 22, 190, 12, 41, 44, 33, 147, 170, 88, 80, 78, 123, 102, 228, 90, 97, 92, 113, 228, 43, 17, 111, 140, 200, 79, 204, 41, 199, 53, 47, 139, 209, 230, 243, 123, 7, 30, 114, 198, 57, 174, 216, 48, 251, 160, 97, 23, 7, 89, 26, 17, 65, 126, 39, 245, 255, 171, 61, 171, 188, 187, 251, 193, 158, 222, 21, 8, 18, 162, 221, 136, 192, 195, 207, 23, 58, 235, 50, 26, 91, 110, 163, 103, 19, 184, 4, 193, 238, 42, 158, 215, 150, 125, 137, 120, 56, 236, 68, 123, 243, 210, 240, 77, 1, 215, 78, 126, 75, 237, 167, 232, 12, 239, 99, 135, 226, 217, 189, 193, 47, 213, 241, 181, 78, 103, 175, 40, 83, 74, 44, 240, 59, 162, 16, 105, 240, 3, 148, 103, 140, 232, 218, 21, 209, 214, 183, 89, 131, 240, 31, 167, 68, 131, 113, 35, 204, 216, 201, 7, 42, 167, 123, 120, 167, 158, 118, 63, 65, 107, 134, 248, 224, 139, 24, 186, 237, 28, 154, 199, 64, 212, 54, 236, 205, 216, 202, 80, 208, 228, 84, 129, 25, 31, 203, 252, 86, 188, 137, 148, 177, 227, 255, 5, 250, 175, 54, 37, 164, 20, 5, 135, 52, 48, 210, 177, 206, 116, 90, 106, 254, 131, 66, 98, 112, 109, 160, 163, 1, 203, 96, 252, 74, 70, 50, 200, 108, 234, 190, 38, 12, 71, 172, 78, 19, 117, 160, 54, 52, 154, 30, 82, 154, 73, 129, 101, 56, 202, 225, 165, 229, 252, 117, 27, 224, 92, 118, 189, 2, 250, 91, 12, 143, 94, 7, 167, 230, 134, 106, 49, 14, 45, 14, 204, 171, 113, 243, 88, 74, 49, 244, 109, 74, 128, 222, 43, 219, 174, 140, 161, 247, 124, 79, 139, 235, 140, 94, 137, 107, 209, 62, 166, 157, 41, 94, 1, 47, 217, 203, 237, 96, 146, 207, 210, 167, 107, 29, 102, 159, 111, 121, 86, 176, 254, 33, 37, 105, 239, 252, 214, 151, 63, 166, 64, 198, 33, 30, 30, 200, 160, 173, 143, 124, 146, 104, 25, 108, 121, 191, 232, 9, 162, 4, 158, 219, 41, 15, 210, 252, 247, 165, 98, 61, 230, 76, 189, 26, 98, 65, 133, 239, 218, 149, 180, 12, 210, 151, 188, 136, 247, 37, 114, 30, 201, 123, 118, 222, 99, 118, 106, 122, 248, 138, 31, 184, 75, 77, 126, 112, 28, 126, 134, 146, 46, 237, 14, 142, 139, 105, 245, 80, 76, 190, 41, 122, 162, 52, 156, 108, 147, 75, 4, 191, 45, 24, 222, 62, 186, 178, 28, 176, 213, 47, 86, 48, 14, 159, 7, 55, 158, 139, 97, 43 ]), &BigUint::from_bytes_be(&[1, 0, 1]) )), public_key.inner_key ); } #[test] fn decode_ssh_rsa_2048_public_key() { // ssh-keygen -t rsa -b 2048 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI9ht2g2qOPgSG5huVYjFUouyaw59/6QuQqUVGwgnITlhRbM+bkvJQfcuiqcv+vD9/86Dfugk79sSfg/aVK+V/plqAAZoujz/wALDjEphSxAUcAR+t4i2F39Pa71MSc37I9L30z31tcba1X7od7hzrVMl9iurkOyBC4xcIWa1H8h0mDyoXyWPTqoTONDUe9dB1eu6GbixCfUcxvdVt0pAVJTdOmbNXKwRo5WXfMrsqKsFT2Acg4Vm4TfLShSSUW4rqM6GOBCfF6jnxFvTSDentH5hykjWL3lMCghD+1hJyOdnMHJC/5qTUGOB86MxsR4RCXqS+LZrGpMScVyDQge7r [email protected]\r\n"; let public_key: SshPublicKey = SshPublicKey::from_str(ssh_public_key).unwrap(); assert_eq!("[email protected]".to_owned(), public_key.comment); assert_eq!( SshBasePublicKey::Rsa(PublicKey::from_rsa_components( &BigUint::from_bytes_be(&[ 200, 246, 27, 118, 131, 106, 142, 62, 4, 134, 230, 27, 149, 98, 49, 84, 162, 236, 154, 195, 159, 127, 233, 11, 144, 169, 69, 70, 194, 9, 200, 78, 88, 81, 108, 207, 155, 146, 242, 80, 125, 203, 162, 169, 203, 254, 188, 63, 127, 243, 160, 223, 186, 9, 59, 246, 196, 159, 131, 246, 149, 43, 229, 127, 166, 90, 128, 1, 154, 46, 143, 63, 240, 0, 176, 227, 18, 152, 82, 196, 5, 28, 1, 31, 173, 226, 45, 133, 223, 211, 218, 239, 83, 18, 115, 126, 200, 244, 189, 244, 207, 125, 109, 113, 182, 181, 95, 186, 29, 238, 28, 235, 84, 201, 125, 138, 234, 228, 59, 32, 66, 227, 23, 8, 89, 173, 71, 242, 29, 38, 15, 42, 23, 201, 99, 211, 170, 132, 206, 52, 53, 30, 245, 208, 117, 122, 238, 134, 110, 44, 66, 125, 71, 49, 189, 213, 109, 210, 144, 21, 37, 55, 78, 153, 179, 87, 43, 4, 104, 229, 101, 223, 50, 187, 42, 42, 193, 83, 216, 7, 32, 225, 89, 184, 77, 242, 210, 133, 36, 148, 91, 138, 234, 51, 161, 142, 4, 39, 197, 234, 57, 241, 22, 244, 210, 13, 233, 237, 31, 152, 114, 146, 53, 139, 222, 83, 2, 130, 16, 254, 214, 18, 114, 57, 217, 204, 28, 144, 191, 230, 164, 212, 24, 224, 124, 232, 204, 108, 71, 132, 66, 94, 164, 190, 45, 154, 198, 164, 196, 156, 87, 32, 208, 129, 238, 235 ]), &BigUint::from_bytes_be(&[1, 0, 1]) )), public_key.inner_key ); } #[test] fn encode_ssh_rsa_4096_public_key() { // ssh-keygen -t rsa -b 4096 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDbUCK4dH1n4dOFBv/sjfMma4q5qe7SZ49j2GODGKr8DueZMWYLTck61uUMMlVBT3XyX6me6X4WsBoijzQWvgwpLCGTqlhQTntm5FphXHHkKxFvjMhPzCnHNS+L0ebzewcecsY5rtgw+6BhFwdZGhFBfif1/6s9q7y7+8Ge3hUIEqLdiMDDzxc66zIaW26jZxO4BMHuKp7Xln2JeDjsRHvz0vBNAddOfkvtp+gM72OH4tm9wS/V8bVOZ68oU0os8DuiEGnwA5RnjOjaFdHWt1mD8B+nRINxI8zYyQcqp3t4p552P0Frhvjgixi67Ryax0DUNuzN2MpQ0ORUgRkfy/xWvImUseP/BfqvNiWkFAWHNDDSsc50Wmr+g0JicG2gowHLYPxKRjLIbOq+JgxHrE4TdaA2NJoeUppJgWU4yuGl5fx1G+Bcdr0C+lsMj14Hp+aGajEOLQ7Mq3HzWEox9G1KgN4r266Mofd8T4vrjF6Ja9E+pp0pXgEv2cvtYJLP0qdrHWafb3lWsP4hJWnv/NaXP6ZAxiEeHsigrY98kmgZbHm/6AmiBJ7bKQ/S/PelYj3mTL0aYkGF79qVtAzSl7yI9yVyHsl7dt5jdmp6+IofuEtNfnAcfoaSLu0Ojotp9VBMvil6ojScbJNLBL8tGN4+urIcsNUvVjAOnwc3nothKw== [email protected]\r\n"; let public_key = SshPublicKey::from_str(ssh_public_key).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(ssh_public_key, ssh_public_key_after.as_str()); } #[test] fn encode_ssh_rsa_2048_public_key() { // ssh-keygen -t rsa -b 4096 -C "[email protected]" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI9ht2g2qOPgSG5huVYjFUouyaw59/6QuQqUVGwgnITlhRbM+bkvJQfcuiqcv+vD9/86Dfugk79sSfg/aVK+V/plqAAZoujz/wALDjEphSxAUcAR+t4i2F39Pa71MSc37I9L30z31tcba1X7od7hzrVMl9iurkOyBC4xcIWa1H8h0mDyoXyWPTqoTONDUe9dB1eu6GbixCfUcxvdVt0pAVJTdOmbNXKwRo5WXfMrsqKsFT2Acg4Vm4TfLShSSUW4rqM6GOBCfF6jnxFvTSDentH5hykjWL3lMCghD+1hJyOdnMHJC/5qTUGOB86MxsR4RCXqS+LZrGpMScVyDQge7r [email protected]\r\n"; let public_key = SshPublicKey::from_str(ssh_public_key).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(ssh_public_key, ssh_public_key_after.as_str()); } #[rstest] #[case(test_files::SSH_PUBLIC_KEY_EC_P256)] #[case(test_files::SSH_PUBLIC_KEY_EC_P384)] #[case(test_files::SSH_PUBLIC_KEY_EC_P521)] fn ecdsa_roundtrip(#[case] key_str: &str)
#[test] fn ed25519_roundtrip() { let public_key = SshPublicKey::from_str(test_files::SSH_PUBLIC_KEY_ED25519).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(test_files::SSH_PUBLIC_KEY_ED25519, ssh_public_key_after.as_str()); } }
{ let public_key = SshPublicKey::from_str(key_str).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(key_str, ssh_public_key_after.as_str()); }
identifier_body
exception.rs
// Copyright 2020 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![allow(non_snake_case)] use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::net::AddrParseError; use std::string::FromUtf8Error; use std::sync::Arc; use backtrace::Backtrace; use thiserror::Error; use tonic::Code; use tonic::Status; pub static ABORT_SESSION: u16 = 42; pub static ABORT_QUERY: u16 = 43; #[derive(Clone)] pub enum ErrorCodeBacktrace { Serialized(Arc<String>), Origin(Arc<Backtrace>), } impl ToString for ErrorCodeBacktrace { fn to_string(&self) -> String { match self { ErrorCodeBacktrace::Serialized(backtrace) => Arc::as_ref(backtrace).clone(), ErrorCodeBacktrace::Origin(backtrace) => { format!("{:?}", backtrace) } } } } #[derive(Error)] pub struct ErrorCode { code: u16, display_text: String, // cause is only used to contain an `anyhow::Error`. // TODO: remove `cause` when we completely get rid of `anyhow::Error`. cause: Option<Box<dyn std::error::Error + Sync + Send>>, backtrace: Option<ErrorCodeBacktrace>, } impl ErrorCode { pub fn code(&self) -> u16 { self.code } pub fn message(&self) -> String { self.cause .as_ref() .map(|cause| format!("{}\n{:?}", self.display_text, cause)) .unwrap_or_else(|| self.display_text.clone()) } pub fn add_message(self, msg: impl AsRef<str>) -> Self { Self { code: self.code(), display_text: format!("{}\n{}", msg.as_ref(), self.display_text), cause: self.cause, backtrace: self.backtrace, } } pub fn add_message_back(self, msg: impl AsRef<str>) -> Self { Self { code: self.code(), display_text: format!("{}{}", self.display_text, msg.as_ref()), cause: self.cause, backtrace: self.backtrace, } } pub fn backtrace(&self) -> Option<ErrorCodeBacktrace> { self.backtrace.clone() } pub fn backtrace_str(&self) -> String { match self.backtrace.as_ref() { None => "".to_string(), Some(backtrace) => backtrace.to_string(), } } } macro_rules! build_exceptions { ($($body:ident($code:expr)),*$(,)*) => { impl ErrorCode { $( pub fn $body(display_text: impl Into<String>) -> ErrorCode { ErrorCode { code: $code, display_text: display_text.into(), cause: None, backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } paste::item! { pub fn [< $body:snake _ code >] () -> u16{ $code } pub fn [< $body Code >] () -> u16{ $code } } )* } } } build_exceptions! { Ok(0), UnknownTypeOfQuery(1), UnImplement(2), UnknownDatabase(3), UnknownSetting(4), SyntaxException(5), BadArguments(6), IllegalDataType(7), UnknownFunction(8), IllegalFunctionState(9), BadDataValueType(10), UnknownPlan(11), IllegalPipelineState(12), BadTransformType(13), IllegalTransformConnectionState(14), LogicalError(15), EmptyData(16), DataStructMissMatch(17), BadDataArrayLength(18), UnknownContextID(19), UnknownVariable(20), UnknownTableFunction(21), BadOption(22), CannotReadFile(23), ParquetError(24), UnknownTable(25), IllegalAggregateExp(26), UnknownAggregateFunction(27), NumberArgumentsNotMatch(28), NotFoundStream(29), EmptyDataFromServer(30), NotFoundLocalNode(31), PlanScheduleError(32), BadPlanInputs(33), DuplicateClusterNode(34), NotFoundClusterNode(35), BadAddressFormat(36), DnsParseError(37), CannotConnectNode(38), DuplicateGetStream(39), Timeout(40), TooManyUserConnections(41), AbortedSession(ABORT_SESSION), AbortedQuery(ABORT_QUERY), NotFoundSession(44), CannotListenerPort(45), BadBytes(46), InitPrometheusFailure(47), ScalarSubqueryBadRows(48), Overflow(49), InvalidMetaBinaryFormat(50), AuthenticateFailure(51), TLSConfigurationFailure(52), UnknownSession(53), UnexpectedError(54), DateTimeParseError(55), BadPredicateRows(56), SHA1CheckFailed(57), // uncategorized UnexpectedResponseType(600), UnknownException(1000), TokioError(1001), } // Store errors build_exceptions! { FileMetaNotFound(2001), FileDamaged(2002), // dfs node errors UnknownNode(2101), // meta service errors // meta service does not work. MetaServiceError(2201), // meta service is shut down. MetaServiceShutdown(2202), // meta service is unavailable for now. MetaServiceUnavailable(2203), // config errors InvalidConfig(2301), // meta store errors MetaStoreDamaged(2401), MetaStoreAlreadyExists(2402), MetaStoreNotFound(2403), ConcurrentSnapshotInstall(2404), IllegalSnapshot(2405), UnknownTableId(2406), TableVersionMissMatch(2407), // KVSrv server error KVSrvError(2501), // FS error IllegalFileName(2601), // Store server error DatabendStoreError(2701), // TODO // We may need to separate front-end errors from API errors (and system errors?) // That may depend which components are using these error codes, and for what purposes, // let's figure it out latter. // user-api error codes UnknownUser(3000), UserAlreadyExists(3001), IllegalUserInfoFormat(3002), // meta-api error codes DatabaseAlreadyExists(4001), TableAlreadyExists(4003), IllegalMetaOperationArgument(4004), IllegalSchema(4005), IllegalMetaState(4006), MetaNodeInternalError(4007), TruncateTableFailedError(4008), CommitTableError(4009), // namespace error. NamespaceUnknownNode(4058), NamespaceNodeAlreadyExists(4059), NamespaceIllegalNodeFormat(4050), // storage-api error codes IllegalScanPlan(5000), ReadFileError(5001), BrokenChannel(5002), // kv-api error codes UnknownKey(6000), // DAL error DALTransportError(7000), UnknownStorageSchemeName(7001), SecretKeyNotSet(7002), // datasource error DuplicatedTableEngineProvider(8000), UnknownDatabaseEngine(8001), UnknownTableEngine(8002), DuplicatedDatabaseEngineProvider(8003), } // General errors build_exceptions! { // A task that already stopped and can not stop twice. AlreadyStarted(7101), // A task that already started and can not start twice. AlreadyStopped(7102), // Trying to cast to a invalid type InvalidCast(7201), } pub type Result<T> = std::result::Result<T, ErrorCode>; impl Debug for ErrorCode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Code: {}, displayText = {}.", self.code(), self.message(), )?; match self.backtrace.as_ref() { None => Ok(()), // no backtrace Some(backtrace) => { // TODO: Custom stack frame format for print match backtrace { ErrorCodeBacktrace::Origin(backtrace) => write!(f, "\n\n{:?}", backtrace), ErrorCodeBacktrace::Serialized(backtrace) => write!(f, "\n\n{:?}", backtrace), } } } } } impl Display for ErrorCode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Code: {}, displayText = {}.", self.code(), self.message(), ) } } #[derive(Error)] enum OtherErrors { AnyHow { error: anyhow::Error }, } impl Display for OtherErrors { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { OtherErrors::AnyHow { error } => write!(f, "{}", error), } } } impl Debug for OtherErrors { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { OtherErrors::AnyHow { error } => write!(f, "{:?}", error), } } } impl From<anyhow::Error> for ErrorCode { fn from(error: anyhow::Error) -> Self { ErrorCode { code: 1002, display_text: format!("{}, source: {:?}", error, error.source()), cause: Some(Box::new(OtherErrors::AnyHow { error })), backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } } impl From<std::num::ParseIntError> for ErrorCode { fn from(error: std::num::ParseIntError) -> Self { ErrorCode::from_std_error(error) } } impl From<std::num::ParseFloatError> for ErrorCode { fn from(error: std::num::ParseFloatError) -> Self { ErrorCode::from_std_error(error) } } impl From<common_arrow::arrow::error::ArrowError> for ErrorCode { fn from(error: common_arrow::arrow::error::ArrowError) -> Self { ErrorCode::from_std_error(error) } } impl From<serde_json::Error> for ErrorCode { fn from(error: serde_json::Error) -> Self { ErrorCode::from_std_error(error) } } impl From<sqlparser::parser::ParserError> for ErrorCode { fn from(error: sqlparser::parser::ParserError) -> Self { ErrorCode::from_std_error(error) } } impl From<std::io::Error> for ErrorCode { fn from(error: std::io::Error) -> Self { ErrorCode::from_std_error(error) } } impl From<std::net::AddrParseError> for ErrorCode { fn from(error: AddrParseError) -> Self { ErrorCode::BadAddressFormat(format!("Bad address format, cause: {}", error)) } } impl From<FromUtf8Error> for ErrorCode { fn from(error: FromUtf8Error) -> Self { ErrorCode::BadBytes(format!( "Bad bytes, cannot parse bytes with UTF8, cause: {}", error )) } } impl From<prost::EncodeError> for ErrorCode { fn from(error: prost::EncodeError) -> Self { ErrorCode::BadBytes(format!( "Bad bytes, cannot parse bytes with prost, cause: {}",
impl ErrorCode { pub fn from_std_error<T: std::error::Error>(error: T) -> Self { ErrorCode { code: 1002, display_text: format!("{}", error), cause: None, backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } pub fn create( code: u16, display_text: String, backtrace: Option<ErrorCodeBacktrace>, ) -> ErrorCode { ErrorCode { code, display_text, cause: None, backtrace, } } } /// Provides the `map_err_to_code` method for `Result`. /// /// ``` /// use common_exception::ToErrorCode; /// use common_exception::ErrorCode; /// /// let x: std::result::Result<(), std::fmt::Error> = Err(std::fmt::Error {}); /// let y: common_exception::Result<()> = /// x.map_err_to_code(ErrorCode::UnknownException, || 123); /// /// assert_eq!( /// "Code: 1000, displayText = 123, cause: an error occurred when formatting an argument.", /// format!("{}", y.unwrap_err()) /// ); /// ``` pub trait ToErrorCode<T, E, CtxFn> where E: Display + Send + Sync +'static { /// Wrap the error value with ErrorCode. It is lazily evaluated: /// only when an error does occur. /// /// `err_code_fn` is one of the ErrorCode builder function such as `ErrorCode::Ok`. /// `context_fn` builds display_text for the ErrorCode. fn map_err_to_code<ErrFn, D>(self, err_code_fn: ErrFn, context_fn: CtxFn) -> Result<T> where ErrFn: FnOnce(String) -> ErrorCode, D: Display, CtxFn: FnOnce() -> D; } impl<T, E, CtxFn> ToErrorCode<T, E, CtxFn> for std::result::Result<T, E> where E: Display + Send + Sync +'static { fn map_err_to_code<ErrFn, D>(self, make_exception: ErrFn, context_fn: CtxFn) -> Result<T> where ErrFn: FnOnce(String) -> ErrorCode, D: Display, CtxFn: FnOnce() -> D, { self.map_err(|error| { let err_text = format!("{}, cause: {}", context_fn(), error); make_exception(err_text) }) } } // === ser/de to/from tonic::Status === #[derive(serde::Serialize, serde::Deserialize)] struct SerializedError { code: u16, message: String, backtrace: String, } impl From<&Status> for ErrorCode { fn from(status: &Status) -> Self { match status.code() { tonic::Code::Unknown => { let details = status.details(); if details.is_empty() { return ErrorCode::UnknownException(status.message()); } match serde_json::from_slice::<SerializedError>(details) { Err(error) => ErrorCode::from(error), Ok(serialized_error) => match serialized_error.backtrace.len() { 0 => { ErrorCode::create(serialized_error.code, serialized_error.message, None) } _ => ErrorCode::create( serialized_error.code, serialized_error.message, Some(ErrorCodeBacktrace::Serialized(Arc::new( serialized_error.backtrace, ))), ), }, } } _ => ErrorCode::UnImplement(status.to_string()), } } } impl From<Status> for ErrorCode { fn from(status: Status) -> Self { (&status).into() } } impl From<ErrorCode> for Status { fn from(err: ErrorCode) -> Self { let rst_json = serde_json::to_vec::<SerializedError>(&SerializedError { code: err.code(), message: err.message(), backtrace: { let mut str = err.backtrace_str(); str.truncate(2 * 1024); str }, }); match rst_json { Ok(serialized_error_json) => { // Code::Internal will be used by h2, if something goes wrong internally. // To distinguish from that, we use Code::Unknown here Status::with_details(Code::Unknown, err.message(), serialized_error_json.into()) } Err(error) => Status::unknown(error.to_string()), } } } impl Clone for ErrorCode { fn clone(&self) -> Self { ErrorCode::create(self.code(), self.message(), self.backtrace()) } }
error )) } }
random_line_split
exception.rs
// Copyright 2020 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![allow(non_snake_case)] use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::net::AddrParseError; use std::string::FromUtf8Error; use std::sync::Arc; use backtrace::Backtrace; use thiserror::Error; use tonic::Code; use tonic::Status; pub static ABORT_SESSION: u16 = 42; pub static ABORT_QUERY: u16 = 43; #[derive(Clone)] pub enum ErrorCodeBacktrace { Serialized(Arc<String>), Origin(Arc<Backtrace>), } impl ToString for ErrorCodeBacktrace { fn to_string(&self) -> String { match self { ErrorCodeBacktrace::Serialized(backtrace) => Arc::as_ref(backtrace).clone(), ErrorCodeBacktrace::Origin(backtrace) => { format!("{:?}", backtrace) } } } } #[derive(Error)] pub struct ErrorCode { code: u16, display_text: String, // cause is only used to contain an `anyhow::Error`. // TODO: remove `cause` when we completely get rid of `anyhow::Error`. cause: Option<Box<dyn std::error::Error + Sync + Send>>, backtrace: Option<ErrorCodeBacktrace>, } impl ErrorCode { pub fn code(&self) -> u16 { self.code } pub fn message(&self) -> String { self.cause .as_ref() .map(|cause| format!("{}\n{:?}", self.display_text, cause)) .unwrap_or_else(|| self.display_text.clone()) } pub fn add_message(self, msg: impl AsRef<str>) -> Self { Self { code: self.code(), display_text: format!("{}\n{}", msg.as_ref(), self.display_text), cause: self.cause, backtrace: self.backtrace, } } pub fn add_message_back(self, msg: impl AsRef<str>) -> Self { Self { code: self.code(), display_text: format!("{}{}", self.display_text, msg.as_ref()), cause: self.cause, backtrace: self.backtrace, } } pub fn backtrace(&self) -> Option<ErrorCodeBacktrace> { self.backtrace.clone() } pub fn backtrace_str(&self) -> String { match self.backtrace.as_ref() { None => "".to_string(), Some(backtrace) => backtrace.to_string(), } } } macro_rules! build_exceptions { ($($body:ident($code:expr)),*$(,)*) => { impl ErrorCode { $( pub fn $body(display_text: impl Into<String>) -> ErrorCode { ErrorCode { code: $code, display_text: display_text.into(), cause: None, backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } paste::item! { pub fn [< $body:snake _ code >] () -> u16{ $code } pub fn [< $body Code >] () -> u16{ $code } } )* } } } build_exceptions! { Ok(0), UnknownTypeOfQuery(1), UnImplement(2), UnknownDatabase(3), UnknownSetting(4), SyntaxException(5), BadArguments(6), IllegalDataType(7), UnknownFunction(8), IllegalFunctionState(9), BadDataValueType(10), UnknownPlan(11), IllegalPipelineState(12), BadTransformType(13), IllegalTransformConnectionState(14), LogicalError(15), EmptyData(16), DataStructMissMatch(17), BadDataArrayLength(18), UnknownContextID(19), UnknownVariable(20), UnknownTableFunction(21), BadOption(22), CannotReadFile(23), ParquetError(24), UnknownTable(25), IllegalAggregateExp(26), UnknownAggregateFunction(27), NumberArgumentsNotMatch(28), NotFoundStream(29), EmptyDataFromServer(30), NotFoundLocalNode(31), PlanScheduleError(32), BadPlanInputs(33), DuplicateClusterNode(34), NotFoundClusterNode(35), BadAddressFormat(36), DnsParseError(37), CannotConnectNode(38), DuplicateGetStream(39), Timeout(40), TooManyUserConnections(41), AbortedSession(ABORT_SESSION), AbortedQuery(ABORT_QUERY), NotFoundSession(44), CannotListenerPort(45), BadBytes(46), InitPrometheusFailure(47), ScalarSubqueryBadRows(48), Overflow(49), InvalidMetaBinaryFormat(50), AuthenticateFailure(51), TLSConfigurationFailure(52), UnknownSession(53), UnexpectedError(54), DateTimeParseError(55), BadPredicateRows(56), SHA1CheckFailed(57), // uncategorized UnexpectedResponseType(600), UnknownException(1000), TokioError(1001), } // Store errors build_exceptions! { FileMetaNotFound(2001), FileDamaged(2002), // dfs node errors UnknownNode(2101), // meta service errors // meta service does not work. MetaServiceError(2201), // meta service is shut down. MetaServiceShutdown(2202), // meta service is unavailable for now. MetaServiceUnavailable(2203), // config errors InvalidConfig(2301), // meta store errors MetaStoreDamaged(2401), MetaStoreAlreadyExists(2402), MetaStoreNotFound(2403), ConcurrentSnapshotInstall(2404), IllegalSnapshot(2405), UnknownTableId(2406), TableVersionMissMatch(2407), // KVSrv server error KVSrvError(2501), // FS error IllegalFileName(2601), // Store server error DatabendStoreError(2701), // TODO // We may need to separate front-end errors from API errors (and system errors?) // That may depend which components are using these error codes, and for what purposes, // let's figure it out latter. // user-api error codes UnknownUser(3000), UserAlreadyExists(3001), IllegalUserInfoFormat(3002), // meta-api error codes DatabaseAlreadyExists(4001), TableAlreadyExists(4003), IllegalMetaOperationArgument(4004), IllegalSchema(4005), IllegalMetaState(4006), MetaNodeInternalError(4007), TruncateTableFailedError(4008), CommitTableError(4009), // namespace error. NamespaceUnknownNode(4058), NamespaceNodeAlreadyExists(4059), NamespaceIllegalNodeFormat(4050), // storage-api error codes IllegalScanPlan(5000), ReadFileError(5001), BrokenChannel(5002), // kv-api error codes UnknownKey(6000), // DAL error DALTransportError(7000), UnknownStorageSchemeName(7001), SecretKeyNotSet(7002), // datasource error DuplicatedTableEngineProvider(8000), UnknownDatabaseEngine(8001), UnknownTableEngine(8002), DuplicatedDatabaseEngineProvider(8003), } // General errors build_exceptions! { // A task that already stopped and can not stop twice. AlreadyStarted(7101), // A task that already started and can not start twice. AlreadyStopped(7102), // Trying to cast to a invalid type InvalidCast(7201), } pub type Result<T> = std::result::Result<T, ErrorCode>; impl Debug for ErrorCode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Code: {}, displayText = {}.", self.code(), self.message(), )?; match self.backtrace.as_ref() { None => Ok(()), // no backtrace Some(backtrace) => { // TODO: Custom stack frame format for print match backtrace { ErrorCodeBacktrace::Origin(backtrace) => write!(f, "\n\n{:?}", backtrace), ErrorCodeBacktrace::Serialized(backtrace) => write!(f, "\n\n{:?}", backtrace), } } } } } impl Display for ErrorCode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Code: {}, displayText = {}.", self.code(), self.message(), ) } } #[derive(Error)] enum OtherErrors { AnyHow { error: anyhow::Error }, } impl Display for OtherErrors { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { OtherErrors::AnyHow { error } => write!(f, "{}", error), } } } impl Debug for OtherErrors { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { OtherErrors::AnyHow { error } => write!(f, "{:?}", error), } } } impl From<anyhow::Error> for ErrorCode { fn from(error: anyhow::Error) -> Self { ErrorCode { code: 1002, display_text: format!("{}, source: {:?}", error, error.source()), cause: Some(Box::new(OtherErrors::AnyHow { error })), backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } } impl From<std::num::ParseIntError> for ErrorCode { fn
(error: std::num::ParseIntError) -> Self { ErrorCode::from_std_error(error) } } impl From<std::num::ParseFloatError> for ErrorCode { fn from(error: std::num::ParseFloatError) -> Self { ErrorCode::from_std_error(error) } } impl From<common_arrow::arrow::error::ArrowError> for ErrorCode { fn from(error: common_arrow::arrow::error::ArrowError) -> Self { ErrorCode::from_std_error(error) } } impl From<serde_json::Error> for ErrorCode { fn from(error: serde_json::Error) -> Self { ErrorCode::from_std_error(error) } } impl From<sqlparser::parser::ParserError> for ErrorCode { fn from(error: sqlparser::parser::ParserError) -> Self { ErrorCode::from_std_error(error) } } impl From<std::io::Error> for ErrorCode { fn from(error: std::io::Error) -> Self { ErrorCode::from_std_error(error) } } impl From<std::net::AddrParseError> for ErrorCode { fn from(error: AddrParseError) -> Self { ErrorCode::BadAddressFormat(format!("Bad address format, cause: {}", error)) } } impl From<FromUtf8Error> for ErrorCode { fn from(error: FromUtf8Error) -> Self { ErrorCode::BadBytes(format!( "Bad bytes, cannot parse bytes with UTF8, cause: {}", error )) } } impl From<prost::EncodeError> for ErrorCode { fn from(error: prost::EncodeError) -> Self { ErrorCode::BadBytes(format!( "Bad bytes, cannot parse bytes with prost, cause: {}", error )) } } impl ErrorCode { pub fn from_std_error<T: std::error::Error>(error: T) -> Self { ErrorCode { code: 1002, display_text: format!("{}", error), cause: None, backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } pub fn create( code: u16, display_text: String, backtrace: Option<ErrorCodeBacktrace>, ) -> ErrorCode { ErrorCode { code, display_text, cause: None, backtrace, } } } /// Provides the `map_err_to_code` method for `Result`. /// /// ``` /// use common_exception::ToErrorCode; /// use common_exception::ErrorCode; /// /// let x: std::result::Result<(), std::fmt::Error> = Err(std::fmt::Error {}); /// let y: common_exception::Result<()> = /// x.map_err_to_code(ErrorCode::UnknownException, || 123); /// /// assert_eq!( /// "Code: 1000, displayText = 123, cause: an error occurred when formatting an argument.", /// format!("{}", y.unwrap_err()) /// ); /// ``` pub trait ToErrorCode<T, E, CtxFn> where E: Display + Send + Sync +'static { /// Wrap the error value with ErrorCode. It is lazily evaluated: /// only when an error does occur. /// /// `err_code_fn` is one of the ErrorCode builder function such as `ErrorCode::Ok`. /// `context_fn` builds display_text for the ErrorCode. fn map_err_to_code<ErrFn, D>(self, err_code_fn: ErrFn, context_fn: CtxFn) -> Result<T> where ErrFn: FnOnce(String) -> ErrorCode, D: Display, CtxFn: FnOnce() -> D; } impl<T, E, CtxFn> ToErrorCode<T, E, CtxFn> for std::result::Result<T, E> where E: Display + Send + Sync +'static { fn map_err_to_code<ErrFn, D>(self, make_exception: ErrFn, context_fn: CtxFn) -> Result<T> where ErrFn: FnOnce(String) -> ErrorCode, D: Display, CtxFn: FnOnce() -> D, { self.map_err(|error| { let err_text = format!("{}, cause: {}", context_fn(), error); make_exception(err_text) }) } } // === ser/de to/from tonic::Status === #[derive(serde::Serialize, serde::Deserialize)] struct SerializedError { code: u16, message: String, backtrace: String, } impl From<&Status> for ErrorCode { fn from(status: &Status) -> Self { match status.code() { tonic::Code::Unknown => { let details = status.details(); if details.is_empty() { return ErrorCode::UnknownException(status.message()); } match serde_json::from_slice::<SerializedError>(details) { Err(error) => ErrorCode::from(error), Ok(serialized_error) => match serialized_error.backtrace.len() { 0 => { ErrorCode::create(serialized_error.code, serialized_error.message, None) } _ => ErrorCode::create( serialized_error.code, serialized_error.message, Some(ErrorCodeBacktrace::Serialized(Arc::new( serialized_error.backtrace, ))), ), }, } } _ => ErrorCode::UnImplement(status.to_string()), } } } impl From<Status> for ErrorCode { fn from(status: Status) -> Self { (&status).into() } } impl From<ErrorCode> for Status { fn from(err: ErrorCode) -> Self { let rst_json = serde_json::to_vec::<SerializedError>(&SerializedError { code: err.code(), message: err.message(), backtrace: { let mut str = err.backtrace_str(); str.truncate(2 * 1024); str }, }); match rst_json { Ok(serialized_error_json) => { // Code::Internal will be used by h2, if something goes wrong internally. // To distinguish from that, we use Code::Unknown here Status::with_details(Code::Unknown, err.message(), serialized_error_json.into()) } Err(error) => Status::unknown(error.to_string()), } } } impl Clone for ErrorCode { fn clone(&self) -> Self { ErrorCode::create(self.code(), self.message(), self.backtrace()) } }
from
identifier_name
exception.rs
// Copyright 2020 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![allow(non_snake_case)] use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::net::AddrParseError; use std::string::FromUtf8Error; use std::sync::Arc; use backtrace::Backtrace; use thiserror::Error; use tonic::Code; use tonic::Status; pub static ABORT_SESSION: u16 = 42; pub static ABORT_QUERY: u16 = 43; #[derive(Clone)] pub enum ErrorCodeBacktrace { Serialized(Arc<String>), Origin(Arc<Backtrace>), } impl ToString for ErrorCodeBacktrace { fn to_string(&self) -> String { match self { ErrorCodeBacktrace::Serialized(backtrace) => Arc::as_ref(backtrace).clone(), ErrorCodeBacktrace::Origin(backtrace) => { format!("{:?}", backtrace) } } } } #[derive(Error)] pub struct ErrorCode { code: u16, display_text: String, // cause is only used to contain an `anyhow::Error`. // TODO: remove `cause` when we completely get rid of `anyhow::Error`. cause: Option<Box<dyn std::error::Error + Sync + Send>>, backtrace: Option<ErrorCodeBacktrace>, } impl ErrorCode { pub fn code(&self) -> u16 { self.code } pub fn message(&self) -> String { self.cause .as_ref() .map(|cause| format!("{}\n{:?}", self.display_text, cause)) .unwrap_or_else(|| self.display_text.clone()) } pub fn add_message(self, msg: impl AsRef<str>) -> Self { Self { code: self.code(), display_text: format!("{}\n{}", msg.as_ref(), self.display_text), cause: self.cause, backtrace: self.backtrace, } } pub fn add_message_back(self, msg: impl AsRef<str>) -> Self { Self { code: self.code(), display_text: format!("{}{}", self.display_text, msg.as_ref()), cause: self.cause, backtrace: self.backtrace, } } pub fn backtrace(&self) -> Option<ErrorCodeBacktrace> { self.backtrace.clone() } pub fn backtrace_str(&self) -> String { match self.backtrace.as_ref() { None => "".to_string(), Some(backtrace) => backtrace.to_string(), } } } macro_rules! build_exceptions { ($($body:ident($code:expr)),*$(,)*) => { impl ErrorCode { $( pub fn $body(display_text: impl Into<String>) -> ErrorCode { ErrorCode { code: $code, display_text: display_text.into(), cause: None, backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } paste::item! { pub fn [< $body:snake _ code >] () -> u16{ $code } pub fn [< $body Code >] () -> u16{ $code } } )* } } } build_exceptions! { Ok(0), UnknownTypeOfQuery(1), UnImplement(2), UnknownDatabase(3), UnknownSetting(4), SyntaxException(5), BadArguments(6), IllegalDataType(7), UnknownFunction(8), IllegalFunctionState(9), BadDataValueType(10), UnknownPlan(11), IllegalPipelineState(12), BadTransformType(13), IllegalTransformConnectionState(14), LogicalError(15), EmptyData(16), DataStructMissMatch(17), BadDataArrayLength(18), UnknownContextID(19), UnknownVariable(20), UnknownTableFunction(21), BadOption(22), CannotReadFile(23), ParquetError(24), UnknownTable(25), IllegalAggregateExp(26), UnknownAggregateFunction(27), NumberArgumentsNotMatch(28), NotFoundStream(29), EmptyDataFromServer(30), NotFoundLocalNode(31), PlanScheduleError(32), BadPlanInputs(33), DuplicateClusterNode(34), NotFoundClusterNode(35), BadAddressFormat(36), DnsParseError(37), CannotConnectNode(38), DuplicateGetStream(39), Timeout(40), TooManyUserConnections(41), AbortedSession(ABORT_SESSION), AbortedQuery(ABORT_QUERY), NotFoundSession(44), CannotListenerPort(45), BadBytes(46), InitPrometheusFailure(47), ScalarSubqueryBadRows(48), Overflow(49), InvalidMetaBinaryFormat(50), AuthenticateFailure(51), TLSConfigurationFailure(52), UnknownSession(53), UnexpectedError(54), DateTimeParseError(55), BadPredicateRows(56), SHA1CheckFailed(57), // uncategorized UnexpectedResponseType(600), UnknownException(1000), TokioError(1001), } // Store errors build_exceptions! { FileMetaNotFound(2001), FileDamaged(2002), // dfs node errors UnknownNode(2101), // meta service errors // meta service does not work. MetaServiceError(2201), // meta service is shut down. MetaServiceShutdown(2202), // meta service is unavailable for now. MetaServiceUnavailable(2203), // config errors InvalidConfig(2301), // meta store errors MetaStoreDamaged(2401), MetaStoreAlreadyExists(2402), MetaStoreNotFound(2403), ConcurrentSnapshotInstall(2404), IllegalSnapshot(2405), UnknownTableId(2406), TableVersionMissMatch(2407), // KVSrv server error KVSrvError(2501), // FS error IllegalFileName(2601), // Store server error DatabendStoreError(2701), // TODO // We may need to separate front-end errors from API errors (and system errors?) // That may depend which components are using these error codes, and for what purposes, // let's figure it out latter. // user-api error codes UnknownUser(3000), UserAlreadyExists(3001), IllegalUserInfoFormat(3002), // meta-api error codes DatabaseAlreadyExists(4001), TableAlreadyExists(4003), IllegalMetaOperationArgument(4004), IllegalSchema(4005), IllegalMetaState(4006), MetaNodeInternalError(4007), TruncateTableFailedError(4008), CommitTableError(4009), // namespace error. NamespaceUnknownNode(4058), NamespaceNodeAlreadyExists(4059), NamespaceIllegalNodeFormat(4050), // storage-api error codes IllegalScanPlan(5000), ReadFileError(5001), BrokenChannel(5002), // kv-api error codes UnknownKey(6000), // DAL error DALTransportError(7000), UnknownStorageSchemeName(7001), SecretKeyNotSet(7002), // datasource error DuplicatedTableEngineProvider(8000), UnknownDatabaseEngine(8001), UnknownTableEngine(8002), DuplicatedDatabaseEngineProvider(8003), } // General errors build_exceptions! { // A task that already stopped and can not stop twice. AlreadyStarted(7101), // A task that already started and can not start twice. AlreadyStopped(7102), // Trying to cast to a invalid type InvalidCast(7201), } pub type Result<T> = std::result::Result<T, ErrorCode>; impl Debug for ErrorCode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Code: {}, displayText = {}.", self.code(), self.message(), )?; match self.backtrace.as_ref() { None => Ok(()), // no backtrace Some(backtrace) => { // TODO: Custom stack frame format for print match backtrace { ErrorCodeBacktrace::Origin(backtrace) => write!(f, "\n\n{:?}", backtrace), ErrorCodeBacktrace::Serialized(backtrace) => write!(f, "\n\n{:?}", backtrace), } } } } } impl Display for ErrorCode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Code: {}, displayText = {}.", self.code(), self.message(), ) } } #[derive(Error)] enum OtherErrors { AnyHow { error: anyhow::Error }, } impl Display for OtherErrors { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { OtherErrors::AnyHow { error } => write!(f, "{}", error), } } } impl Debug for OtherErrors { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { OtherErrors::AnyHow { error } => write!(f, "{:?}", error), } } } impl From<anyhow::Error> for ErrorCode { fn from(error: anyhow::Error) -> Self { ErrorCode { code: 1002, display_text: format!("{}, source: {:?}", error, error.source()), cause: Some(Box::new(OtherErrors::AnyHow { error })), backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } } impl From<std::num::ParseIntError> for ErrorCode { fn from(error: std::num::ParseIntError) -> Self
} impl From<std::num::ParseFloatError> for ErrorCode { fn from(error: std::num::ParseFloatError) -> Self { ErrorCode::from_std_error(error) } } impl From<common_arrow::arrow::error::ArrowError> for ErrorCode { fn from(error: common_arrow::arrow::error::ArrowError) -> Self { ErrorCode::from_std_error(error) } } impl From<serde_json::Error> for ErrorCode { fn from(error: serde_json::Error) -> Self { ErrorCode::from_std_error(error) } } impl From<sqlparser::parser::ParserError> for ErrorCode { fn from(error: sqlparser::parser::ParserError) -> Self { ErrorCode::from_std_error(error) } } impl From<std::io::Error> for ErrorCode { fn from(error: std::io::Error) -> Self { ErrorCode::from_std_error(error) } } impl From<std::net::AddrParseError> for ErrorCode { fn from(error: AddrParseError) -> Self { ErrorCode::BadAddressFormat(format!("Bad address format, cause: {}", error)) } } impl From<FromUtf8Error> for ErrorCode { fn from(error: FromUtf8Error) -> Self { ErrorCode::BadBytes(format!( "Bad bytes, cannot parse bytes with UTF8, cause: {}", error )) } } impl From<prost::EncodeError> for ErrorCode { fn from(error: prost::EncodeError) -> Self { ErrorCode::BadBytes(format!( "Bad bytes, cannot parse bytes with prost, cause: {}", error )) } } impl ErrorCode { pub fn from_std_error<T: std::error::Error>(error: T) -> Self { ErrorCode { code: 1002, display_text: format!("{}", error), cause: None, backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } pub fn create( code: u16, display_text: String, backtrace: Option<ErrorCodeBacktrace>, ) -> ErrorCode { ErrorCode { code, display_text, cause: None, backtrace, } } } /// Provides the `map_err_to_code` method for `Result`. /// /// ``` /// use common_exception::ToErrorCode; /// use common_exception::ErrorCode; /// /// let x: std::result::Result<(), std::fmt::Error> = Err(std::fmt::Error {}); /// let y: common_exception::Result<()> = /// x.map_err_to_code(ErrorCode::UnknownException, || 123); /// /// assert_eq!( /// "Code: 1000, displayText = 123, cause: an error occurred when formatting an argument.", /// format!("{}", y.unwrap_err()) /// ); /// ``` pub trait ToErrorCode<T, E, CtxFn> where E: Display + Send + Sync +'static { /// Wrap the error value with ErrorCode. It is lazily evaluated: /// only when an error does occur. /// /// `err_code_fn` is one of the ErrorCode builder function such as `ErrorCode::Ok`. /// `context_fn` builds display_text for the ErrorCode. fn map_err_to_code<ErrFn, D>(self, err_code_fn: ErrFn, context_fn: CtxFn) -> Result<T> where ErrFn: FnOnce(String) -> ErrorCode, D: Display, CtxFn: FnOnce() -> D; } impl<T, E, CtxFn> ToErrorCode<T, E, CtxFn> for std::result::Result<T, E> where E: Display + Send + Sync +'static { fn map_err_to_code<ErrFn, D>(self, make_exception: ErrFn, context_fn: CtxFn) -> Result<T> where ErrFn: FnOnce(String) -> ErrorCode, D: Display, CtxFn: FnOnce() -> D, { self.map_err(|error| { let err_text = format!("{}, cause: {}", context_fn(), error); make_exception(err_text) }) } } // === ser/de to/from tonic::Status === #[derive(serde::Serialize, serde::Deserialize)] struct SerializedError { code: u16, message: String, backtrace: String, } impl From<&Status> for ErrorCode { fn from(status: &Status) -> Self { match status.code() { tonic::Code::Unknown => { let details = status.details(); if details.is_empty() { return ErrorCode::UnknownException(status.message()); } match serde_json::from_slice::<SerializedError>(details) { Err(error) => ErrorCode::from(error), Ok(serialized_error) => match serialized_error.backtrace.len() { 0 => { ErrorCode::create(serialized_error.code, serialized_error.message, None) } _ => ErrorCode::create( serialized_error.code, serialized_error.message, Some(ErrorCodeBacktrace::Serialized(Arc::new( serialized_error.backtrace, ))), ), }, } } _ => ErrorCode::UnImplement(status.to_string()), } } } impl From<Status> for ErrorCode { fn from(status: Status) -> Self { (&status).into() } } impl From<ErrorCode> for Status { fn from(err: ErrorCode) -> Self { let rst_json = serde_json::to_vec::<SerializedError>(&SerializedError { code: err.code(), message: err.message(), backtrace: { let mut str = err.backtrace_str(); str.truncate(2 * 1024); str }, }); match rst_json { Ok(serialized_error_json) => { // Code::Internal will be used by h2, if something goes wrong internally. // To distinguish from that, we use Code::Unknown here Status::with_details(Code::Unknown, err.message(), serialized_error_json.into()) } Err(error) => Status::unknown(error.to_string()), } } } impl Clone for ErrorCode { fn clone(&self) -> Self { ErrorCode::create(self.code(), self.message(), self.backtrace()) } }
{ ErrorCode::from_std_error(error) }
identifier_body
mailbox.rs
// use byteorder::{ByteOrder, NativeEndian}; use core::{ convert::TryInto, fmt, mem, ops, slice, sync::atomic::{fence, Ordering}, }; use field_offset::offset_of; use super::mmu::align_up; const MAIL_BASE: usize = 0xB880; const MAIL_FULL: u32 = 0x8000_0000; const MAIL_EMPTY: u32 = 0x4000_0000; // const MAPPED_REGISTERS_BASE: usize = 0x2000_0000; const MAPPED_REGISTERS_BASE: usize = 0x3f00_0000; // const MAPPED_REGISTERS_BASE: usize = 0x7E00_0000; #[derive(Copy, Clone, Debug)] struct MailboxRegisterOffsets { read: u8, peek: u8, sender: u8, status: u8, config: u8, write: u8, } const MAILBOX_OFFFSETS: MailboxRegisterOffsets = MailboxRegisterOffsets { read: 0x00, peek: 0x10, sender: 0x14, status: 0x18, config: 0x1c, write: 0x20, }; // MailboxRegisterOffsets { // read: 0x20, // peek: 0x30, // sender: 0x34, // status: 0x38, // config: 0x3c, // write: 0x40, // }, // ]; #[inline] unsafe fn read_reg(base: usize, offset: u8) -> u32 { ((MAPPED_REGISTERS_BASE + base + offset as usize) as *const u32).read_volatile() } #[inline] unsafe fn
(base: usize, offset: u8, value: u32) { ((MAPPED_REGISTERS_BASE + base + offset as usize) as *mut u32).write_volatile(value) } unsafe fn read_mailbox(channel: u8) -> u32 { // 1. Read the status register until the empty flag is not set. // 2. Read data from the read register. // 3. If the lower four bits do not match the channel number desired repeat // from 1. // 4. The upper 28 bits are the returned data. // Wait for the mailbox to be non-empty // Execute a memory barrier // Read MAIL0_STATUS // Goto step 1 if MAIL_EMPTY bit is set // Execute a memory barrier // Read from MAIL0_READ // Check the channel (lowest 4 bits) of the read value for the correct channel // If the channel is not the one we wish to read from (i.e: 1), go to step 1 // Return the data (i.e: the read value >> 4) // println!("Reading mailbox (want channel {})", channel); let mut limit = 10; loop { let mut empty_limit = 10; loop { fence(Ordering::SeqCst); if read_reg(MAIL_BASE, MAILBOX_OFFFSETS.status) & MAIL_EMPTY == 0 { break; } if empty_limit == 0 { panic!( "Gave up waiting for mail when reading from mailbox (channel {})", channel ); } empty_limit -= 1; } fence(Ordering::SeqCst); let data: u32 = read_reg(MAIL_BASE, MAILBOX_OFFFSETS.read); let read_channel = (data & 0x0F) as u8; let data = data >> 4; // println!( // "Got data from mailbox: {:#8x} (from channel {})", // data, read_channel // ); if read_channel!= channel { // println!("Wrong channel, trying again..."); if limit == 0 { panic!( "Got trampled too many times when reading from mailbox (channel {})", channel ); } limit -= 1; continue; } return data; } } unsafe fn write_mailbox(channel: u8, data: u32) { // 1. Read the status register until the full flag is not set. // 2. Write the data (shifted into the upper 28 bits) combined with the // channel (in the lower four bits) to the write register. // println!("Writing {:#8x} to mailbox channel {}", data, channel); let mut limit = 10; loop { // Wait for space fence(Ordering::SeqCst); if read_reg(MAIL_BASE, MAILBOX_OFFFSETS.status + 0x20) & MAIL_FULL == 0 { break; } if limit == 0 { panic!( "Gave up waiting for space to write to mailbox (channel {}, data: 0x{:08x})", channel, data ); } limit -= 1; } write_reg(MAIL_BASE, MAILBOX_OFFFSETS.write, data | (channel as u32)); fence(Ordering::SeqCst); // println!("Finished writing to mailbox"); } pub trait PropertyTagList: Sized { fn prepare(self) -> PropertyMessageWrapper<Self> { PropertyMessageWrapper::new(self) } } macro_rules! impl_ptl { ( $( $t:ident ),+ ) => { impl< $($t),+ > PropertyTagList for ( $(PropertyMessage< $t >, )+ ) where $( $t: Sized, )+ {} }; } impl<T: Sized> PropertyTagList for PropertyMessage<T> {} // impl_ptl!(T1); // impl_ptl!(T1, T2); // impl_ptl!(T1, T2, T3); // impl_ptl!(T1, T2, T3, T4); // impl_ptl!(T1, T2, T3, T4, T5); // impl_ptl!(T1, T2, T3, T4, T5, T6); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8, T9); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); #[repr(C, align(16))] #[derive(Debug)] pub struct PropertyMessageWrapper<TL: PropertyTagList> { buffer_size: u32, code: u32, tags: TL, // extra: [u32; 10], } impl<TL: PropertyTagList> PropertyMessageWrapper<TL> { #[inline] fn new(tags: TL) -> Self { // let extra_offset = offset_of!(Self => extra).get_byte_offset(); // assert!(extra_offset % 4 == 0); let buffer_size = core::mem::size_of::<Self>(); PropertyMessageWrapper { buffer_size: buffer_size .try_into() .expect("Property message list size in bytes is too big to fit in a u32"), code: 0x0000_0000, tags, // extra: [0; 10], } } fn as_quads(&self) -> &[u32] { let size_bytes = mem::size_of::<Self>(); debug_assert_eq!(size_bytes % 4, 0); let u32_size: usize = size_bytes / 4; unsafe { slice::from_raw_parts((self as *const Self) as *const u32, u32_size) } } pub fn send<'a>(&'a mut self) -> Option<&'a TL> where TL: fmt::Debug, { // println!("Property message before sending over mailbox: {:#x?}", self); // println!( // "Property message quads before sending over mailbox: {:#x?}", // self.as_quads() // ); const CHANNEL: u8 = Channel::PropertyTagsSend as u8; println!("sending message {:x?}", self); unsafe { let ptr = self as *const Self; let addr = ptr as usize; write_mailbox(CHANNEL, addr.try_into().ok()?); let resp_addr = read_mailbox(CHANNEL); } // let resp_ptr = resp_addr as *const u32; // println!("Got response from mailbox: {:#?}", &*resp_ptr); // let resp_code: u32 = *resp_ptr.offset(1); // println!( // "Property message after response {:#8x}: {:#x?}", // resp_addr, self // ); // { // let message_quads = self.as_quads(); // println!("Property message words: {:#x?}", message_quads); // } if self.code!= 0x8000_0000 { return None; } // let msg_ptr = resp_ptr.offset(2); // let value_buffer_size_ptr = msg_ptr.offset(1); // let value_buffer_size = (*value_buffer_size_ptr) as usize; // let value_buffer_ptr = msg_ptr.offset(3) as *const T; // assert_eq!(value_buffer_size, mem::size_of::<T>()); // let value_ref = &*(value_buffer_ptr as *const T); // Some(value_ref) println!("received message: {:#x?}", self); Some(&self.tags) } } impl<TL: PropertyTagList> ops::Deref for PropertyMessageWrapper<TL> { type Target = TL; fn deref(&self) -> &TL { &self.tags } } impl<TL: PropertyTagList> ops::DerefMut for PropertyMessageWrapper<TL> { fn deref_mut(&mut self) -> &mut TL { &mut self.tags } } #[repr(C, align(4))] #[derive(Debug)] pub struct PropertyMessage<T> { tag: u32, buffer_size: u32, code: u32, buffer: T, } impl<T> ops::Deref for PropertyMessage<T> { type Target = T; fn deref(&self) -> &T { &self.buffer } } impl<T> ops::DerefMut for PropertyMessage<T> { fn deref_mut(&mut self) -> &mut T { &mut self.buffer } } impl<T: Sized> From<(u32, T)> for PropertyMessage<T> { fn from((tag, buffer): (u32, T)) -> PropertyMessage<T> { PropertyMessage::new(tag, buffer) } } impl<T> PropertyMessage<T> { pub fn new(tag: u32, buffer: T) -> Self { let buffer_size = align_up(mem::size_of::<T>(), 2) .try_into() .expect("Property message size is too big to fit in a u32"); let msg = PropertyMessage { tag, buffer_size, code: 0, buffer, }; let tag_offset = offset_of!(Self => tag); assert_eq!(tag_offset.get_byte_offset(), 0); let size_offset = offset_of!(Self => buffer_size); assert_eq!(size_offset.get_byte_offset(), 4); let code_offset = offset_of!(Self => code); assert_eq!(code_offset.get_byte_offset(), 8); let buffer_offset = offset_of!(Self => buffer); assert_eq!(buffer_offset.get_byte_offset(), 12); msg } pub fn value(&self) -> &T { &self.buffer } } // impl<T: fmt::Debug> PropertyMessage<T> { // pub fn new(tag: u32, buffer: T) -> Self { // PropertyMessage { // } // } // } pub fn send_raw_message<T: fmt::Debug>(channel: Channel, msg: &mut T) -> Result<u32, ()> { let resp: u32; let msg_ptr = msg as *mut T; let msg_addr_usize = msg_ptr as usize; let msg_addr_u32 = msg_addr_usize.try_into().map_err(|_| ())?; unsafe { write_mailbox(channel as u8, msg_addr_u32); resp = read_mailbox(channel as u8); } // println!( // "Got response {:#8x} after raw message send: {:#x?}", // resp, msg // ); Ok(resp) } #[repr(u8)] #[derive(Copy, Clone, Debug)] pub enum Channel { Power = 0, Framebuffer = 1, VirtualUART = 2, VCHIQ = 3, LEDs = 4, Buttons = 5, TouchScreen = 6, Unknown7 = 7, PropertyTagsSend = 8, PropertyTagsReceive = 9, }
write_reg
identifier_name
mailbox.rs
// use byteorder::{ByteOrder, NativeEndian}; use core::{ convert::TryInto, fmt, mem, ops, slice, sync::atomic::{fence, Ordering}, }; use field_offset::offset_of; use super::mmu::align_up; const MAIL_BASE: usize = 0xB880; const MAIL_FULL: u32 = 0x8000_0000; const MAIL_EMPTY: u32 = 0x4000_0000; // const MAPPED_REGISTERS_BASE: usize = 0x2000_0000; const MAPPED_REGISTERS_BASE: usize = 0x3f00_0000; // const MAPPED_REGISTERS_BASE: usize = 0x7E00_0000; #[derive(Copy, Clone, Debug)] struct MailboxRegisterOffsets { read: u8, peek: u8, sender: u8, status: u8, config: u8, write: u8, } const MAILBOX_OFFFSETS: MailboxRegisterOffsets = MailboxRegisterOffsets { read: 0x00, peek: 0x10, sender: 0x14, status: 0x18, config: 0x1c, write: 0x20, }; // MailboxRegisterOffsets { // read: 0x20, // peek: 0x30, // sender: 0x34, // status: 0x38, // config: 0x3c, // write: 0x40, // }, // ]; #[inline] unsafe fn read_reg(base: usize, offset: u8) -> u32 { ((MAPPED_REGISTERS_BASE + base + offset as usize) as *const u32).read_volatile() } #[inline] unsafe fn write_reg(base: usize, offset: u8, value: u32) { ((MAPPED_REGISTERS_BASE + base + offset as usize) as *mut u32).write_volatile(value) } unsafe fn read_mailbox(channel: u8) -> u32 { // 1. Read the status register until the empty flag is not set. // 2. Read data from the read register. // 3. If the lower four bits do not match the channel number desired repeat // from 1. // 4. The upper 28 bits are the returned data. // Wait for the mailbox to be non-empty // Execute a memory barrier // Read MAIL0_STATUS // Goto step 1 if MAIL_EMPTY bit is set // Execute a memory barrier // Read from MAIL0_READ // Check the channel (lowest 4 bits) of the read value for the correct channel // If the channel is not the one we wish to read from (i.e: 1), go to step 1 // Return the data (i.e: the read value >> 4) // println!("Reading mailbox (want channel {})", channel); let mut limit = 10; loop { let mut empty_limit = 10; loop { fence(Ordering::SeqCst); if read_reg(MAIL_BASE, MAILBOX_OFFFSETS.status) & MAIL_EMPTY == 0 { break; } if empty_limit == 0 { panic!( "Gave up waiting for mail when reading from mailbox (channel {})", channel ); } empty_limit -= 1; } fence(Ordering::SeqCst); let data: u32 = read_reg(MAIL_BASE, MAILBOX_OFFFSETS.read); let read_channel = (data & 0x0F) as u8; let data = data >> 4; // println!( // "Got data from mailbox: {:#8x} (from channel {})", // data, read_channel // ); if read_channel!= channel { // println!("Wrong channel, trying again..."); if limit == 0 { panic!( "Got trampled too many times when reading from mailbox (channel {})", channel ); } limit -= 1; continue; } return data; } } unsafe fn write_mailbox(channel: u8, data: u32) { // 1. Read the status register until the full flag is not set. // 2. Write the data (shifted into the upper 28 bits) combined with the // channel (in the lower four bits) to the write register. // println!("Writing {:#8x} to mailbox channel {}", data, channel); let mut limit = 10; loop { // Wait for space fence(Ordering::SeqCst); if read_reg(MAIL_BASE, MAILBOX_OFFFSETS.status + 0x20) & MAIL_FULL == 0 { break; } if limit == 0
limit -= 1; } write_reg(MAIL_BASE, MAILBOX_OFFFSETS.write, data | (channel as u32)); fence(Ordering::SeqCst); // println!("Finished writing to mailbox"); } pub trait PropertyTagList: Sized { fn prepare(self) -> PropertyMessageWrapper<Self> { PropertyMessageWrapper::new(self) } } macro_rules! impl_ptl { ( $( $t:ident ),+ ) => { impl< $($t),+ > PropertyTagList for ( $(PropertyMessage< $t >, )+ ) where $( $t: Sized, )+ {} }; } impl<T: Sized> PropertyTagList for PropertyMessage<T> {} // impl_ptl!(T1); // impl_ptl!(T1, T2); // impl_ptl!(T1, T2, T3); // impl_ptl!(T1, T2, T3, T4); // impl_ptl!(T1, T2, T3, T4, T5); // impl_ptl!(T1, T2, T3, T4, T5, T6); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8, T9); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); #[repr(C, align(16))] #[derive(Debug)] pub struct PropertyMessageWrapper<TL: PropertyTagList> { buffer_size: u32, code: u32, tags: TL, // extra: [u32; 10], } impl<TL: PropertyTagList> PropertyMessageWrapper<TL> { #[inline] fn new(tags: TL) -> Self { // let extra_offset = offset_of!(Self => extra).get_byte_offset(); // assert!(extra_offset % 4 == 0); let buffer_size = core::mem::size_of::<Self>(); PropertyMessageWrapper { buffer_size: buffer_size .try_into() .expect("Property message list size in bytes is too big to fit in a u32"), code: 0x0000_0000, tags, // extra: [0; 10], } } fn as_quads(&self) -> &[u32] { let size_bytes = mem::size_of::<Self>(); debug_assert_eq!(size_bytes % 4, 0); let u32_size: usize = size_bytes / 4; unsafe { slice::from_raw_parts((self as *const Self) as *const u32, u32_size) } } pub fn send<'a>(&'a mut self) -> Option<&'a TL> where TL: fmt::Debug, { // println!("Property message before sending over mailbox: {:#x?}", self); // println!( // "Property message quads before sending over mailbox: {:#x?}", // self.as_quads() // ); const CHANNEL: u8 = Channel::PropertyTagsSend as u8; println!("sending message {:x?}", self); unsafe { let ptr = self as *const Self; let addr = ptr as usize; write_mailbox(CHANNEL, addr.try_into().ok()?); let resp_addr = read_mailbox(CHANNEL); } // let resp_ptr = resp_addr as *const u32; // println!("Got response from mailbox: {:#?}", &*resp_ptr); // let resp_code: u32 = *resp_ptr.offset(1); // println!( // "Property message after response {:#8x}: {:#x?}", // resp_addr, self // ); // { // let message_quads = self.as_quads(); // println!("Property message words: {:#x?}", message_quads); // } if self.code!= 0x8000_0000 { return None; } // let msg_ptr = resp_ptr.offset(2); // let value_buffer_size_ptr = msg_ptr.offset(1); // let value_buffer_size = (*value_buffer_size_ptr) as usize; // let value_buffer_ptr = msg_ptr.offset(3) as *const T; // assert_eq!(value_buffer_size, mem::size_of::<T>()); // let value_ref = &*(value_buffer_ptr as *const T); // Some(value_ref) println!("received message: {:#x?}", self); Some(&self.tags) } } impl<TL: PropertyTagList> ops::Deref for PropertyMessageWrapper<TL> { type Target = TL; fn deref(&self) -> &TL { &self.tags } } impl<TL: PropertyTagList> ops::DerefMut for PropertyMessageWrapper<TL> { fn deref_mut(&mut self) -> &mut TL { &mut self.tags } } #[repr(C, align(4))] #[derive(Debug)] pub struct PropertyMessage<T> { tag: u32, buffer_size: u32, code: u32, buffer: T, } impl<T> ops::Deref for PropertyMessage<T> { type Target = T; fn deref(&self) -> &T { &self.buffer } } impl<T> ops::DerefMut for PropertyMessage<T> { fn deref_mut(&mut self) -> &mut T { &mut self.buffer } } impl<T: Sized> From<(u32, T)> for PropertyMessage<T> { fn from((tag, buffer): (u32, T)) -> PropertyMessage<T> { PropertyMessage::new(tag, buffer) } } impl<T> PropertyMessage<T> { pub fn new(tag: u32, buffer: T) -> Self { let buffer_size = align_up(mem::size_of::<T>(), 2) .try_into() .expect("Property message size is too big to fit in a u32"); let msg = PropertyMessage { tag, buffer_size, code: 0, buffer, }; let tag_offset = offset_of!(Self => tag); assert_eq!(tag_offset.get_byte_offset(), 0); let size_offset = offset_of!(Self => buffer_size); assert_eq!(size_offset.get_byte_offset(), 4); let code_offset = offset_of!(Self => code); assert_eq!(code_offset.get_byte_offset(), 8); let buffer_offset = offset_of!(Self => buffer); assert_eq!(buffer_offset.get_byte_offset(), 12); msg } pub fn value(&self) -> &T { &self.buffer } } // impl<T: fmt::Debug> PropertyMessage<T> { // pub fn new(tag: u32, buffer: T) -> Self { // PropertyMessage { // } // } // } pub fn send_raw_message<T: fmt::Debug>(channel: Channel, msg: &mut T) -> Result<u32, ()> { let resp: u32; let msg_ptr = msg as *mut T; let msg_addr_usize = msg_ptr as usize; let msg_addr_u32 = msg_addr_usize.try_into().map_err(|_| ())?; unsafe { write_mailbox(channel as u8, msg_addr_u32); resp = read_mailbox(channel as u8); } // println!( // "Got response {:#8x} after raw message send: {:#x?}", // resp, msg // ); Ok(resp) } #[repr(u8)] #[derive(Copy, Clone, Debug)] pub enum Channel { Power = 0, Framebuffer = 1, VirtualUART = 2, VCHIQ = 3, LEDs = 4, Buttons = 5, TouchScreen = 6, Unknown7 = 7, PropertyTagsSend = 8, PropertyTagsReceive = 9, }
{ panic!( "Gave up waiting for space to write to mailbox (channel {}, data: 0x{:08x})", channel, data ); }
conditional_block
mailbox.rs
// use byteorder::{ByteOrder, NativeEndian}; use core::{ convert::TryInto, fmt, mem, ops, slice, sync::atomic::{fence, Ordering}, }; use field_offset::offset_of; use super::mmu::align_up; const MAIL_BASE: usize = 0xB880; const MAIL_FULL: u32 = 0x8000_0000; const MAIL_EMPTY: u32 = 0x4000_0000; // const MAPPED_REGISTERS_BASE: usize = 0x2000_0000; const MAPPED_REGISTERS_BASE: usize = 0x3f00_0000; // const MAPPED_REGISTERS_BASE: usize = 0x7E00_0000; #[derive(Copy, Clone, Debug)] struct MailboxRegisterOffsets { read: u8, peek: u8, sender: u8, status: u8, config: u8, write: u8, } const MAILBOX_OFFFSETS: MailboxRegisterOffsets = MailboxRegisterOffsets { read: 0x00, peek: 0x10, sender: 0x14, status: 0x18, config: 0x1c, write: 0x20, }; // MailboxRegisterOffsets { // read: 0x20, // peek: 0x30, // sender: 0x34, // status: 0x38, // config: 0x3c, // write: 0x40, // }, // ]; #[inline] unsafe fn read_reg(base: usize, offset: u8) -> u32 { ((MAPPED_REGISTERS_BASE + base + offset as usize) as *const u32).read_volatile() } #[inline] unsafe fn write_reg(base: usize, offset: u8, value: u32) { ((MAPPED_REGISTERS_BASE + base + offset as usize) as *mut u32).write_volatile(value) } unsafe fn read_mailbox(channel: u8) -> u32 { // 1. Read the status register until the empty flag is not set. // 2. Read data from the read register. // 3. If the lower four bits do not match the channel number desired repeat // from 1. // 4. The upper 28 bits are the returned data. // Wait for the mailbox to be non-empty // Execute a memory barrier // Read MAIL0_STATUS // Goto step 1 if MAIL_EMPTY bit is set // Execute a memory barrier // Read from MAIL0_READ // Check the channel (lowest 4 bits) of the read value for the correct channel // If the channel is not the one we wish to read from (i.e: 1), go to step 1 // Return the data (i.e: the read value >> 4) // println!("Reading mailbox (want channel {})", channel); let mut limit = 10; loop { let mut empty_limit = 10; loop { fence(Ordering::SeqCst); if read_reg(MAIL_BASE, MAILBOX_OFFFSETS.status) & MAIL_EMPTY == 0 { break; } if empty_limit == 0 { panic!( "Gave up waiting for mail when reading from mailbox (channel {})", channel ); } empty_limit -= 1; } fence(Ordering::SeqCst); let data: u32 = read_reg(MAIL_BASE, MAILBOX_OFFFSETS.read); let read_channel = (data & 0x0F) as u8; let data = data >> 4; // println!( // "Got data from mailbox: {:#8x} (from channel {})", // data, read_channel // ); if read_channel!= channel { // println!("Wrong channel, trying again..."); if limit == 0 { panic!( "Got trampled too many times when reading from mailbox (channel {})", channel ); } limit -= 1; continue; } return data; } } unsafe fn write_mailbox(channel: u8, data: u32) { // 1. Read the status register until the full flag is not set. // 2. Write the data (shifted into the upper 28 bits) combined with the // channel (in the lower four bits) to the write register. // println!("Writing {:#8x} to mailbox channel {}", data, channel); let mut limit = 10; loop { // Wait for space fence(Ordering::SeqCst); if read_reg(MAIL_BASE, MAILBOX_OFFFSETS.status + 0x20) & MAIL_FULL == 0 { break; } if limit == 0 { panic!( "Gave up waiting for space to write to mailbox (channel {}, data: 0x{:08x})", channel, data ); } limit -= 1; } write_reg(MAIL_BASE, MAILBOX_OFFFSETS.write, data | (channel as u32)); fence(Ordering::SeqCst); // println!("Finished writing to mailbox"); } pub trait PropertyTagList: Sized { fn prepare(self) -> PropertyMessageWrapper<Self> { PropertyMessageWrapper::new(self) } } macro_rules! impl_ptl { ( $( $t:ident ),+ ) => { impl< $($t),+ > PropertyTagList for ( $(PropertyMessage< $t >, )+ ) where $( $t: Sized, )+ {} }; } impl<T: Sized> PropertyTagList for PropertyMessage<T> {} // impl_ptl!(T1); // impl_ptl!(T1, T2); // impl_ptl!(T1, T2, T3); // impl_ptl!(T1, T2, T3, T4); // impl_ptl!(T1, T2, T3, T4, T5); // impl_ptl!(T1, T2, T3, T4, T5, T6); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8, T9); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); #[repr(C, align(16))] #[derive(Debug)] pub struct PropertyMessageWrapper<TL: PropertyTagList> { buffer_size: u32, code: u32, tags: TL, // extra: [u32; 10], } impl<TL: PropertyTagList> PropertyMessageWrapper<TL> { #[inline] fn new(tags: TL) -> Self { // let extra_offset = offset_of!(Self => extra).get_byte_offset(); // assert!(extra_offset % 4 == 0); let buffer_size = core::mem::size_of::<Self>(); PropertyMessageWrapper { buffer_size: buffer_size .try_into() .expect("Property message list size in bytes is too big to fit in a u32"), code: 0x0000_0000, tags, // extra: [0; 10], } } fn as_quads(&self) -> &[u32] { let size_bytes = mem::size_of::<Self>(); debug_assert_eq!(size_bytes % 4, 0); let u32_size: usize = size_bytes / 4; unsafe { slice::from_raw_parts((self as *const Self) as *const u32, u32_size) } } pub fn send<'a>(&'a mut self) -> Option<&'a TL> where TL: fmt::Debug, { // println!("Property message before sending over mailbox: {:#x?}", self); // println!( // "Property message quads before sending over mailbox: {:#x?}", // self.as_quads() // ); const CHANNEL: u8 = Channel::PropertyTagsSend as u8; println!("sending message {:x?}", self); unsafe { let ptr = self as *const Self; let addr = ptr as usize; write_mailbox(CHANNEL, addr.try_into().ok()?); let resp_addr = read_mailbox(CHANNEL); } // let resp_ptr = resp_addr as *const u32; // println!("Got response from mailbox: {:#?}", &*resp_ptr); // let resp_code: u32 = *resp_ptr.offset(1); // println!( // "Property message after response {:#8x}: {:#x?}", // resp_addr, self // ); // { // let message_quads = self.as_quads(); // println!("Property message words: {:#x?}", message_quads); // } if self.code!= 0x8000_0000 { return None; } // let msg_ptr = resp_ptr.offset(2); // let value_buffer_size_ptr = msg_ptr.offset(1); // let value_buffer_size = (*value_buffer_size_ptr) as usize; // let value_buffer_ptr = msg_ptr.offset(3) as *const T; // assert_eq!(value_buffer_size, mem::size_of::<T>()); // let value_ref = &*(value_buffer_ptr as *const T); // Some(value_ref) println!("received message: {:#x?}", self); Some(&self.tags) } } impl<TL: PropertyTagList> ops::Deref for PropertyMessageWrapper<TL> { type Target = TL; fn deref(&self) -> &TL { &self.tags } } impl<TL: PropertyTagList> ops::DerefMut for PropertyMessageWrapper<TL> { fn deref_mut(&mut self) -> &mut TL { &mut self.tags } } #[repr(C, align(4))] #[derive(Debug)] pub struct PropertyMessage<T> { tag: u32, buffer_size: u32, code: u32, buffer: T, } impl<T> ops::Deref for PropertyMessage<T> { type Target = T; fn deref(&self) -> &T { &self.buffer } } impl<T> ops::DerefMut for PropertyMessage<T> { fn deref_mut(&mut self) -> &mut T { &mut self.buffer } } impl<T: Sized> From<(u32, T)> for PropertyMessage<T> { fn from((tag, buffer): (u32, T)) -> PropertyMessage<T> { PropertyMessage::new(tag, buffer) } } impl<T> PropertyMessage<T> { pub fn new(tag: u32, buffer: T) -> Self { let buffer_size = align_up(mem::size_of::<T>(), 2) .try_into() .expect("Property message size is too big to fit in a u32"); let msg = PropertyMessage { tag, buffer_size, code: 0, buffer, }; let tag_offset = offset_of!(Self => tag); assert_eq!(tag_offset.get_byte_offset(), 0); let size_offset = offset_of!(Self => buffer_size); assert_eq!(size_offset.get_byte_offset(), 4); let code_offset = offset_of!(Self => code); assert_eq!(code_offset.get_byte_offset(), 8); let buffer_offset = offset_of!(Self => buffer); assert_eq!(buffer_offset.get_byte_offset(), 12); msg } pub fn value(&self) -> &T { &self.buffer } } // impl<T: fmt::Debug> PropertyMessage<T> { // pub fn new(tag: u32, buffer: T) -> Self { // PropertyMessage { // } // } // } pub fn send_raw_message<T: fmt::Debug>(channel: Channel, msg: &mut T) -> Result<u32, ()>
#[repr(u8)] #[derive(Copy, Clone, Debug)] pub enum Channel { Power = 0, Framebuffer = 1, VirtualUART = 2, VCHIQ = 3, LEDs = 4, Buttons = 5, TouchScreen = 6, Unknown7 = 7, PropertyTagsSend = 8, PropertyTagsReceive = 9, }
{ let resp: u32; let msg_ptr = msg as *mut T; let msg_addr_usize = msg_ptr as usize; let msg_addr_u32 = msg_addr_usize.try_into().map_err(|_| ())?; unsafe { write_mailbox(channel as u8, msg_addr_u32); resp = read_mailbox(channel as u8); } // println!( // "Got response {:#8x} after raw message send: {:#x?}", // resp, msg // ); Ok(resp) }
identifier_body
mailbox.rs
// use byteorder::{ByteOrder, NativeEndian}; use core::{ convert::TryInto, fmt, mem, ops, slice, sync::atomic::{fence, Ordering}, }; use field_offset::offset_of; use super::mmu::align_up; const MAIL_BASE: usize = 0xB880; const MAIL_FULL: u32 = 0x8000_0000; const MAIL_EMPTY: u32 = 0x4000_0000; // const MAPPED_REGISTERS_BASE: usize = 0x2000_0000; const MAPPED_REGISTERS_BASE: usize = 0x3f00_0000; // const MAPPED_REGISTERS_BASE: usize = 0x7E00_0000; #[derive(Copy, Clone, Debug)] struct MailboxRegisterOffsets { read: u8, peek: u8, sender: u8, status: u8, config: u8, write: u8, } const MAILBOX_OFFFSETS: MailboxRegisterOffsets = MailboxRegisterOffsets { read: 0x00, peek: 0x10, sender: 0x14, status: 0x18, config: 0x1c, write: 0x20, }; // MailboxRegisterOffsets { // read: 0x20, // peek: 0x30, // sender: 0x34, // status: 0x38, // config: 0x3c, // write: 0x40, // }, // ]; #[inline] unsafe fn read_reg(base: usize, offset: u8) -> u32 { ((MAPPED_REGISTERS_BASE + base + offset as usize) as *const u32).read_volatile() } #[inline] unsafe fn write_reg(base: usize, offset: u8, value: u32) { ((MAPPED_REGISTERS_BASE + base + offset as usize) as *mut u32).write_volatile(value) } unsafe fn read_mailbox(channel: u8) -> u32 { // 1. Read the status register until the empty flag is not set. // 2. Read data from the read register. // 3. If the lower four bits do not match the channel number desired repeat // from 1. // 4. The upper 28 bits are the returned data. // Wait for the mailbox to be non-empty // Execute a memory barrier // Read MAIL0_STATUS // Goto step 1 if MAIL_EMPTY bit is set
// Check the channel (lowest 4 bits) of the read value for the correct channel // If the channel is not the one we wish to read from (i.e: 1), go to step 1 // Return the data (i.e: the read value >> 4) // println!("Reading mailbox (want channel {})", channel); let mut limit = 10; loop { let mut empty_limit = 10; loop { fence(Ordering::SeqCst); if read_reg(MAIL_BASE, MAILBOX_OFFFSETS.status) & MAIL_EMPTY == 0 { break; } if empty_limit == 0 { panic!( "Gave up waiting for mail when reading from mailbox (channel {})", channel ); } empty_limit -= 1; } fence(Ordering::SeqCst); let data: u32 = read_reg(MAIL_BASE, MAILBOX_OFFFSETS.read); let read_channel = (data & 0x0F) as u8; let data = data >> 4; // println!( // "Got data from mailbox: {:#8x} (from channel {})", // data, read_channel // ); if read_channel!= channel { // println!("Wrong channel, trying again..."); if limit == 0 { panic!( "Got trampled too many times when reading from mailbox (channel {})", channel ); } limit -= 1; continue; } return data; } } unsafe fn write_mailbox(channel: u8, data: u32) { // 1. Read the status register until the full flag is not set. // 2. Write the data (shifted into the upper 28 bits) combined with the // channel (in the lower four bits) to the write register. // println!("Writing {:#8x} to mailbox channel {}", data, channel); let mut limit = 10; loop { // Wait for space fence(Ordering::SeqCst); if read_reg(MAIL_BASE, MAILBOX_OFFFSETS.status + 0x20) & MAIL_FULL == 0 { break; } if limit == 0 { panic!( "Gave up waiting for space to write to mailbox (channel {}, data: 0x{:08x})", channel, data ); } limit -= 1; } write_reg(MAIL_BASE, MAILBOX_OFFFSETS.write, data | (channel as u32)); fence(Ordering::SeqCst); // println!("Finished writing to mailbox"); } pub trait PropertyTagList: Sized { fn prepare(self) -> PropertyMessageWrapper<Self> { PropertyMessageWrapper::new(self) } } macro_rules! impl_ptl { ( $( $t:ident ),+ ) => { impl< $($t),+ > PropertyTagList for ( $(PropertyMessage< $t >, )+ ) where $( $t: Sized, )+ {} }; } impl<T: Sized> PropertyTagList for PropertyMessage<T> {} // impl_ptl!(T1); // impl_ptl!(T1, T2); // impl_ptl!(T1, T2, T3); // impl_ptl!(T1, T2, T3, T4); // impl_ptl!(T1, T2, T3, T4, T5); // impl_ptl!(T1, T2, T3, T4, T5, T6); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8, T9); // impl_ptl!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); #[repr(C, align(16))] #[derive(Debug)] pub struct PropertyMessageWrapper<TL: PropertyTagList> { buffer_size: u32, code: u32, tags: TL, // extra: [u32; 10], } impl<TL: PropertyTagList> PropertyMessageWrapper<TL> { #[inline] fn new(tags: TL) -> Self { // let extra_offset = offset_of!(Self => extra).get_byte_offset(); // assert!(extra_offset % 4 == 0); let buffer_size = core::mem::size_of::<Self>(); PropertyMessageWrapper { buffer_size: buffer_size .try_into() .expect("Property message list size in bytes is too big to fit in a u32"), code: 0x0000_0000, tags, // extra: [0; 10], } } fn as_quads(&self) -> &[u32] { let size_bytes = mem::size_of::<Self>(); debug_assert_eq!(size_bytes % 4, 0); let u32_size: usize = size_bytes / 4; unsafe { slice::from_raw_parts((self as *const Self) as *const u32, u32_size) } } pub fn send<'a>(&'a mut self) -> Option<&'a TL> where TL: fmt::Debug, { // println!("Property message before sending over mailbox: {:#x?}", self); // println!( // "Property message quads before sending over mailbox: {:#x?}", // self.as_quads() // ); const CHANNEL: u8 = Channel::PropertyTagsSend as u8; println!("sending message {:x?}", self); unsafe { let ptr = self as *const Self; let addr = ptr as usize; write_mailbox(CHANNEL, addr.try_into().ok()?); let resp_addr = read_mailbox(CHANNEL); } // let resp_ptr = resp_addr as *const u32; // println!("Got response from mailbox: {:#?}", &*resp_ptr); // let resp_code: u32 = *resp_ptr.offset(1); // println!( // "Property message after response {:#8x}: {:#x?}", // resp_addr, self // ); // { // let message_quads = self.as_quads(); // println!("Property message words: {:#x?}", message_quads); // } if self.code!= 0x8000_0000 { return None; } // let msg_ptr = resp_ptr.offset(2); // let value_buffer_size_ptr = msg_ptr.offset(1); // let value_buffer_size = (*value_buffer_size_ptr) as usize; // let value_buffer_ptr = msg_ptr.offset(3) as *const T; // assert_eq!(value_buffer_size, mem::size_of::<T>()); // let value_ref = &*(value_buffer_ptr as *const T); // Some(value_ref) println!("received message: {:#x?}", self); Some(&self.tags) } } impl<TL: PropertyTagList> ops::Deref for PropertyMessageWrapper<TL> { type Target = TL; fn deref(&self) -> &TL { &self.tags } } impl<TL: PropertyTagList> ops::DerefMut for PropertyMessageWrapper<TL> { fn deref_mut(&mut self) -> &mut TL { &mut self.tags } } #[repr(C, align(4))] #[derive(Debug)] pub struct PropertyMessage<T> { tag: u32, buffer_size: u32, code: u32, buffer: T, } impl<T> ops::Deref for PropertyMessage<T> { type Target = T; fn deref(&self) -> &T { &self.buffer } } impl<T> ops::DerefMut for PropertyMessage<T> { fn deref_mut(&mut self) -> &mut T { &mut self.buffer } } impl<T: Sized> From<(u32, T)> for PropertyMessage<T> { fn from((tag, buffer): (u32, T)) -> PropertyMessage<T> { PropertyMessage::new(tag, buffer) } } impl<T> PropertyMessage<T> { pub fn new(tag: u32, buffer: T) -> Self { let buffer_size = align_up(mem::size_of::<T>(), 2) .try_into() .expect("Property message size is too big to fit in a u32"); let msg = PropertyMessage { tag, buffer_size, code: 0, buffer, }; let tag_offset = offset_of!(Self => tag); assert_eq!(tag_offset.get_byte_offset(), 0); let size_offset = offset_of!(Self => buffer_size); assert_eq!(size_offset.get_byte_offset(), 4); let code_offset = offset_of!(Self => code); assert_eq!(code_offset.get_byte_offset(), 8); let buffer_offset = offset_of!(Self => buffer); assert_eq!(buffer_offset.get_byte_offset(), 12); msg } pub fn value(&self) -> &T { &self.buffer } } // impl<T: fmt::Debug> PropertyMessage<T> { // pub fn new(tag: u32, buffer: T) -> Self { // PropertyMessage { // } // } // } pub fn send_raw_message<T: fmt::Debug>(channel: Channel, msg: &mut T) -> Result<u32, ()> { let resp: u32; let msg_ptr = msg as *mut T; let msg_addr_usize = msg_ptr as usize; let msg_addr_u32 = msg_addr_usize.try_into().map_err(|_| ())?; unsafe { write_mailbox(channel as u8, msg_addr_u32); resp = read_mailbox(channel as u8); } // println!( // "Got response {:#8x} after raw message send: {:#x?}", // resp, msg // ); Ok(resp) } #[repr(u8)] #[derive(Copy, Clone, Debug)] pub enum Channel { Power = 0, Framebuffer = 1, VirtualUART = 2, VCHIQ = 3, LEDs = 4, Buttons = 5, TouchScreen = 6, Unknown7 = 7, PropertyTagsSend = 8, PropertyTagsReceive = 9, }
// Execute a memory barrier // Read from MAIL0_READ
random_line_split
internal.rs
extern crate proc_macro; use ink_lang_ir::Callable; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, }; use std::{ collections::HashMap, convert::TryFrom, }; use syn::{ ext::IdentExt, parenthesized, parse::{ Parse, ParseStream, }, ItemImpl, }; use crate::{ metadata::Metadata, trait_definition::{ EXTERNAL_METHOD_SUFFIX, EXTERNAL_TRAIT_SUFFIX, WRAPPER_TRAIT_SUFFIX, }, }; pub(crate) const BRUSH_PREFIX: &'static str = "__brush"; pub(crate) struct MetaList { pub path: syn::Path, pub _paren_token: syn::token::Paren, pub nested: syn::punctuated::Punctuated<TokenStream2, syn::Token![,]>, } // Like Path::parse_mod_style but accepts keywords in the path. fn parse_meta_path(input: ParseStream) -> syn::Result<syn::Path> { Ok(syn::Path { leading_colon: input.parse()?, segments: { let mut segments = syn::punctuated::Punctuated::new(); while input.peek(syn::Ident::peek_any) { let ident = syn::Ident::parse_any(input)?; segments.push_value(syn::PathSegment::from(ident)); if!input.peek(syn::Token![::]) { break } let punct = input.parse()?; segments.push_punct(punct); } if segments.is_empty() { return Err(input.error("expected path")) } else if segments.trailing_punct() { return Err(input.error("expected path segment")) } segments }, }) } fn parse_meta_list_after_path(path: syn::Path, input: ParseStream) -> syn::Result<MetaList> { let content; Ok(MetaList { path, _paren_token: parenthesized!(content in input), nested: content.parse_terminated(TokenStream2::parse)?, }) } fn parse_meta_after_path(path: syn::Path, input: ParseStream) -> syn::Result<NestedMeta> { if input.peek(syn::token::Paren) { parse_meta_list_after_path(path, input).map(NestedMeta::List) } else { Ok(NestedMeta::Path(path)) } } impl Parse for MetaList { fn parse(input: ParseStream) -> syn::Result<Self> { let path = input.call(parse_meta_path)?; parse_meta_list_after_path(path, input) } } pub(crate) enum NestedMeta { Path(syn::Path), List(MetaList), } impl Parse for NestedMeta { fn parse(input: ParseStream) -> syn::Result<Self> { let path = input.call(parse_meta_path)?; parse_meta_after_path(path, input) } } pub(crate) struct AttributeArgs(Vec<NestedMeta>); impl Parse for AttributeArgs { fn parse(input: ParseStream) -> syn::Result<Self> { let mut attrs = Vec::new(); while input.peek(syn::Ident::peek_any) { attrs.push(input.parse()?); if input.is_empty() { break } let _: syn::token::Comma = input.parse()?; } Ok(AttributeArgs { 0: attrs }) } } impl std::ops::Deref for AttributeArgs { type Target = Vec<NestedMeta>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for AttributeArgs { fn deref_mut(&mut self) -> &mut Vec<NestedMeta> { &mut self.0 } } pub(crate) struct Attributes(Vec<syn::Attribute>); impl Parse for Attributes { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Self(syn::Attribute::parse_outer(input)?)) } } impl Attributes { pub(crate) fn attr(&self) -> &Vec<syn::Attribute> { &self.0 } } // Returns "ink-as-dependency" and not("ink-as-dependency") impls pub(crate) fn impl_external_trait( mut impl_item: syn::ItemImpl, trait_ident: &syn::Ident, metadata: &Metadata, ) -> (Vec<syn::Item>, Vec<syn::Item>) { let impl_ink_attrs = extract_attr(&mut impl_item.attrs, "ink"); let mut ink_methods: HashMap<String, syn::TraitItemMethod> = HashMap::new(); metadata .external_traits .get(&trait_ident.to_string()) .methods() .iter() .for_each(|method| { if is_attr(&method.attrs, "ink") { let mut empty_method = method.clone(); empty_method.default = Some( syn::parse2(quote! { { unimplemented!() } }) .unwrap(), ); let mut attrs = empty_method.attrs.clone(); empty_method.attrs = extract_attr(&mut attrs, "doc"); empty_method.attrs.append(&mut extract_attr(&mut attrs, "ink")); ink_methods.insert(method.sig.ident.to_string(), empty_method); } }); // Move ink! attrs from internal trait to external impl_item.items.iter_mut().for_each(|mut item| { if let syn::ImplItem::Method(method) = &mut item { let method_key = method.sig.ident.to_string(); if ink_methods.contains_key(&method_key) { // Internal attrs will override external, so user must include full declaration with ink(message) and etc. ink_methods.get_mut(&method_key).unwrap().attrs = extract_attr(&mut method.attrs, "doc"); ink_methods .get_mut(&method_key) .unwrap() .attrs .append(&mut extract_attr(&mut method.attrs, "ink")); } } }); let ink_methods_iter = ink_methods.iter().map(|(_, value)| value); let self_ty = impl_item.self_ty.clone().as_ref().clone(); let draft_impl: ItemImpl = syn::parse2(quote! { #(#impl_ink_attrs)* impl #trait_ident for #self_ty { #(#ink_methods_iter)* } }) .unwrap(); // Evaluate selector and metadata_name for each method based on rules in ink! let ink_impl = ::ink_lang_ir::ItemImpl::try_from(draft_impl).unwrap(); ink_impl.iter_messages().for_each(|message| { let method = ink_methods.get_mut(&message.ident().to_string()).unwrap(); if message.user_provided_selector().is_none() { let selector_u32 = u32::from_be_bytes(message.composed_selector().as_bytes().clone()) as usize; let selector = format!("{:#010x}", selector_u32); method.attrs.push(new_attribute(quote! {#[ink(selector = #selector)]})); } if message.metadata_name() == message.ident().to_string() { let selector = format!("{}", message.metadata_name()); method .attrs .push(new_attribute(quote! {#[ink(metadata_name = #selector)]})); } let original_name = message.ident(); let inputs_params = message.inputs().map(|pat_type| &pat_type.pat); method.default = Some( syn::parse2(quote! { { #trait_ident::#original_name(self #(, #inputs_params )* ) } }) .unwrap(), ); }); let ink_methods_iter = ink_methods.iter().map(|(_, value)| value); let wrapper_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, WRAPPER_TRAIT_SUFFIX); // We only want to use this implementation in case when ink-as-dependency for wrapper. // It will provide methods with the same name like in initial trait. let wrapper_impl: ItemImpl = syn::parse2(quote! { #(#impl_ink_attrs)* impl #wrapper_trait_ident for #self_ty { #(#ink_methods_iter)* } }) .unwrap(); let trait_name = ink_impl .trait_path() .map(|path| path.segments.last().unwrap().ident.to_string()); let mut metadata_name_attr = quote! {}; if trait_name == ink_impl.trait_metadata_name()
let external_ink_methods_iter = ink_methods.iter_mut().map(|(_, value)| { value.sig.ident = format_ident!("{}_{}{}", BRUSH_PREFIX, value.sig.ident, EXTERNAL_METHOD_SUFFIX); value }); let external_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, EXTERNAL_TRAIT_SUFFIX); // It is implementation of "external" trait(trait where all method marked with ink!) // This trait has another name with external suffix. And all methods have external signature. // But ABI generated by this impl section is the same as ABI generated by original trait. let external_impl: ItemImpl = syn::parse2(quote! { #metadata_name_attr #(#impl_ink_attrs)* impl #external_trait_ident for #self_ty { #(#external_ink_methods_iter)* } }) .unwrap(); // Internal implementation must be disable during "ink-as-dependency" let internal_impl = impl_item; ( vec![syn::Item::from(wrapper_impl)], vec![syn::Item::from(internal_impl), syn::Item::from(external_impl)], ) } #[inline] pub(crate) fn is_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> bool { if let None = attrs .iter() .find(|attr| attr.path.segments.last().expect("No segments in path").ident == ident) { false } else { true } } #[inline] #[allow(dead_code)] pub(crate) fn get_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> Option<syn::Attribute> { for attr in attrs.iter() { if is_attr(&vec![attr.clone()], ident) { return Some(attr.clone()) } } None } #[inline] pub(crate) fn remove_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> Vec<syn::Attribute> { attrs .clone() .into_iter() .filter_map(|attr| { if is_attr(&vec![attr.clone()], ident) { None } else { Some(attr) } }) .collect() } #[inline] pub(crate) fn extract_attr(attrs: &mut Vec<syn::Attribute>, ident: &str) -> Vec<syn::Attribute> { attrs.drain_filter(|attr| is_attr(&vec![attr.clone()], ident)).collect() } #[inline] pub(crate) fn new_attribute(attr_stream: TokenStream2) -> syn::Attribute { syn::parse2::<Attributes>(attr_stream).unwrap().attr()[0].clone() } /// Computes the BLAKE-2b 256-bit hash for the given input and stores it in output. #[inline] pub fn blake2b_256(input: &[u8], output: &mut [u8]) { use ::blake2::digest::{ Update as _, VariableOutput as _, }; let mut blake2 = blake2::VarBlake2b::new_keyed(&[], 32); blake2.update(input); blake2.finalize_variable(|result| output.copy_from_slice(result)); } #[inline] pub(crate) fn blake2b_256_str(input: String) -> [u8; 32] { let mut output: [u8; 32] = [0; 32]; blake2b_256(&input.into_bytes(), &mut output); output } #[inline] pub(crate) fn sanitize_to_str(input: TokenStream) -> String { let mut str = input.to_string(); // Remove quotes rom the string str.drain(1..str.len() - 1).collect() }
{ let name = format!("{}", trait_name.unwrap()); metadata_name_attr = quote! { #[ink(metadata_name = #name)] } }
conditional_block
internal.rs
extern crate proc_macro; use ink_lang_ir::Callable; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, }; use std::{ collections::HashMap, convert::TryFrom, }; use syn::{ ext::IdentExt, parenthesized,
Parse, ParseStream, }, ItemImpl, }; use crate::{ metadata::Metadata, trait_definition::{ EXTERNAL_METHOD_SUFFIX, EXTERNAL_TRAIT_SUFFIX, WRAPPER_TRAIT_SUFFIX, }, }; pub(crate) const BRUSH_PREFIX: &'static str = "__brush"; pub(crate) struct MetaList { pub path: syn::Path, pub _paren_token: syn::token::Paren, pub nested: syn::punctuated::Punctuated<TokenStream2, syn::Token![,]>, } // Like Path::parse_mod_style but accepts keywords in the path. fn parse_meta_path(input: ParseStream) -> syn::Result<syn::Path> { Ok(syn::Path { leading_colon: input.parse()?, segments: { let mut segments = syn::punctuated::Punctuated::new(); while input.peek(syn::Ident::peek_any) { let ident = syn::Ident::parse_any(input)?; segments.push_value(syn::PathSegment::from(ident)); if!input.peek(syn::Token![::]) { break } let punct = input.parse()?; segments.push_punct(punct); } if segments.is_empty() { return Err(input.error("expected path")) } else if segments.trailing_punct() { return Err(input.error("expected path segment")) } segments }, }) } fn parse_meta_list_after_path(path: syn::Path, input: ParseStream) -> syn::Result<MetaList> { let content; Ok(MetaList { path, _paren_token: parenthesized!(content in input), nested: content.parse_terminated(TokenStream2::parse)?, }) } fn parse_meta_after_path(path: syn::Path, input: ParseStream) -> syn::Result<NestedMeta> { if input.peek(syn::token::Paren) { parse_meta_list_after_path(path, input).map(NestedMeta::List) } else { Ok(NestedMeta::Path(path)) } } impl Parse for MetaList { fn parse(input: ParseStream) -> syn::Result<Self> { let path = input.call(parse_meta_path)?; parse_meta_list_after_path(path, input) } } pub(crate) enum NestedMeta { Path(syn::Path), List(MetaList), } impl Parse for NestedMeta { fn parse(input: ParseStream) -> syn::Result<Self> { let path = input.call(parse_meta_path)?; parse_meta_after_path(path, input) } } pub(crate) struct AttributeArgs(Vec<NestedMeta>); impl Parse for AttributeArgs { fn parse(input: ParseStream) -> syn::Result<Self> { let mut attrs = Vec::new(); while input.peek(syn::Ident::peek_any) { attrs.push(input.parse()?); if input.is_empty() { break } let _: syn::token::Comma = input.parse()?; } Ok(AttributeArgs { 0: attrs }) } } impl std::ops::Deref for AttributeArgs { type Target = Vec<NestedMeta>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for AttributeArgs { fn deref_mut(&mut self) -> &mut Vec<NestedMeta> { &mut self.0 } } pub(crate) struct Attributes(Vec<syn::Attribute>); impl Parse for Attributes { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Self(syn::Attribute::parse_outer(input)?)) } } impl Attributes { pub(crate) fn attr(&self) -> &Vec<syn::Attribute> { &self.0 } } // Returns "ink-as-dependency" and not("ink-as-dependency") impls pub(crate) fn impl_external_trait( mut impl_item: syn::ItemImpl, trait_ident: &syn::Ident, metadata: &Metadata, ) -> (Vec<syn::Item>, Vec<syn::Item>) { let impl_ink_attrs = extract_attr(&mut impl_item.attrs, "ink"); let mut ink_methods: HashMap<String, syn::TraitItemMethod> = HashMap::new(); metadata .external_traits .get(&trait_ident.to_string()) .methods() .iter() .for_each(|method| { if is_attr(&method.attrs, "ink") { let mut empty_method = method.clone(); empty_method.default = Some( syn::parse2(quote! { { unimplemented!() } }) .unwrap(), ); let mut attrs = empty_method.attrs.clone(); empty_method.attrs = extract_attr(&mut attrs, "doc"); empty_method.attrs.append(&mut extract_attr(&mut attrs, "ink")); ink_methods.insert(method.sig.ident.to_string(), empty_method); } }); // Move ink! attrs from internal trait to external impl_item.items.iter_mut().for_each(|mut item| { if let syn::ImplItem::Method(method) = &mut item { let method_key = method.sig.ident.to_string(); if ink_methods.contains_key(&method_key) { // Internal attrs will override external, so user must include full declaration with ink(message) and etc. ink_methods.get_mut(&method_key).unwrap().attrs = extract_attr(&mut method.attrs, "doc"); ink_methods .get_mut(&method_key) .unwrap() .attrs .append(&mut extract_attr(&mut method.attrs, "ink")); } } }); let ink_methods_iter = ink_methods.iter().map(|(_, value)| value); let self_ty = impl_item.self_ty.clone().as_ref().clone(); let draft_impl: ItemImpl = syn::parse2(quote! { #(#impl_ink_attrs)* impl #trait_ident for #self_ty { #(#ink_methods_iter)* } }) .unwrap(); // Evaluate selector and metadata_name for each method based on rules in ink! let ink_impl = ::ink_lang_ir::ItemImpl::try_from(draft_impl).unwrap(); ink_impl.iter_messages().for_each(|message| { let method = ink_methods.get_mut(&message.ident().to_string()).unwrap(); if message.user_provided_selector().is_none() { let selector_u32 = u32::from_be_bytes(message.composed_selector().as_bytes().clone()) as usize; let selector = format!("{:#010x}", selector_u32); method.attrs.push(new_attribute(quote! {#[ink(selector = #selector)]})); } if message.metadata_name() == message.ident().to_string() { let selector = format!("{}", message.metadata_name()); method .attrs .push(new_attribute(quote! {#[ink(metadata_name = #selector)]})); } let original_name = message.ident(); let inputs_params = message.inputs().map(|pat_type| &pat_type.pat); method.default = Some( syn::parse2(quote! { { #trait_ident::#original_name(self #(, #inputs_params )* ) } }) .unwrap(), ); }); let ink_methods_iter = ink_methods.iter().map(|(_, value)| value); let wrapper_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, WRAPPER_TRAIT_SUFFIX); // We only want to use this implementation in case when ink-as-dependency for wrapper. // It will provide methods with the same name like in initial trait. let wrapper_impl: ItemImpl = syn::parse2(quote! { #(#impl_ink_attrs)* impl #wrapper_trait_ident for #self_ty { #(#ink_methods_iter)* } }) .unwrap(); let trait_name = ink_impl .trait_path() .map(|path| path.segments.last().unwrap().ident.to_string()); let mut metadata_name_attr = quote! {}; if trait_name == ink_impl.trait_metadata_name() { let name = format!("{}", trait_name.unwrap()); metadata_name_attr = quote! { #[ink(metadata_name = #name)] } } let external_ink_methods_iter = ink_methods.iter_mut().map(|(_, value)| { value.sig.ident = format_ident!("{}_{}{}", BRUSH_PREFIX, value.sig.ident, EXTERNAL_METHOD_SUFFIX); value }); let external_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, EXTERNAL_TRAIT_SUFFIX); // It is implementation of "external" trait(trait where all method marked with ink!) // This trait has another name with external suffix. And all methods have external signature. // But ABI generated by this impl section is the same as ABI generated by original trait. let external_impl: ItemImpl = syn::parse2(quote! { #metadata_name_attr #(#impl_ink_attrs)* impl #external_trait_ident for #self_ty { #(#external_ink_methods_iter)* } }) .unwrap(); // Internal implementation must be disable during "ink-as-dependency" let internal_impl = impl_item; ( vec![syn::Item::from(wrapper_impl)], vec![syn::Item::from(internal_impl), syn::Item::from(external_impl)], ) } #[inline] pub(crate) fn is_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> bool { if let None = attrs .iter() .find(|attr| attr.path.segments.last().expect("No segments in path").ident == ident) { false } else { true } } #[inline] #[allow(dead_code)] pub(crate) fn get_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> Option<syn::Attribute> { for attr in attrs.iter() { if is_attr(&vec![attr.clone()], ident) { return Some(attr.clone()) } } None } #[inline] pub(crate) fn remove_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> Vec<syn::Attribute> { attrs .clone() .into_iter() .filter_map(|attr| { if is_attr(&vec![attr.clone()], ident) { None } else { Some(attr) } }) .collect() } #[inline] pub(crate) fn extract_attr(attrs: &mut Vec<syn::Attribute>, ident: &str) -> Vec<syn::Attribute> { attrs.drain_filter(|attr| is_attr(&vec![attr.clone()], ident)).collect() } #[inline] pub(crate) fn new_attribute(attr_stream: TokenStream2) -> syn::Attribute { syn::parse2::<Attributes>(attr_stream).unwrap().attr()[0].clone() } /// Computes the BLAKE-2b 256-bit hash for the given input and stores it in output. #[inline] pub fn blake2b_256(input: &[u8], output: &mut [u8]) { use ::blake2::digest::{ Update as _, VariableOutput as _, }; let mut blake2 = blake2::VarBlake2b::new_keyed(&[], 32); blake2.update(input); blake2.finalize_variable(|result| output.copy_from_slice(result)); } #[inline] pub(crate) fn blake2b_256_str(input: String) -> [u8; 32] { let mut output: [u8; 32] = [0; 32]; blake2b_256(&input.into_bytes(), &mut output); output } #[inline] pub(crate) fn sanitize_to_str(input: TokenStream) -> String { let mut str = input.to_string(); // Remove quotes rom the string str.drain(1..str.len() - 1).collect() }
parse::{
random_line_split
internal.rs
extern crate proc_macro; use ink_lang_ir::Callable; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, }; use std::{ collections::HashMap, convert::TryFrom, }; use syn::{ ext::IdentExt, parenthesized, parse::{ Parse, ParseStream, }, ItemImpl, }; use crate::{ metadata::Metadata, trait_definition::{ EXTERNAL_METHOD_SUFFIX, EXTERNAL_TRAIT_SUFFIX, WRAPPER_TRAIT_SUFFIX, }, }; pub(crate) const BRUSH_PREFIX: &'static str = "__brush"; pub(crate) struct MetaList { pub path: syn::Path, pub _paren_token: syn::token::Paren, pub nested: syn::punctuated::Punctuated<TokenStream2, syn::Token![,]>, } // Like Path::parse_mod_style but accepts keywords in the path. fn parse_meta_path(input: ParseStream) -> syn::Result<syn::Path> { Ok(syn::Path { leading_colon: input.parse()?, segments: { let mut segments = syn::punctuated::Punctuated::new(); while input.peek(syn::Ident::peek_any) { let ident = syn::Ident::parse_any(input)?; segments.push_value(syn::PathSegment::from(ident)); if!input.peek(syn::Token![::]) { break } let punct = input.parse()?; segments.push_punct(punct); } if segments.is_empty() { return Err(input.error("expected path")) } else if segments.trailing_punct() { return Err(input.error("expected path segment")) } segments }, }) } fn parse_meta_list_after_path(path: syn::Path, input: ParseStream) -> syn::Result<MetaList> { let content; Ok(MetaList { path, _paren_token: parenthesized!(content in input), nested: content.parse_terminated(TokenStream2::parse)?, }) } fn parse_meta_after_path(path: syn::Path, input: ParseStream) -> syn::Result<NestedMeta> { if input.peek(syn::token::Paren) { parse_meta_list_after_path(path, input).map(NestedMeta::List) } else { Ok(NestedMeta::Path(path)) } } impl Parse for MetaList { fn
(input: ParseStream) -> syn::Result<Self> { let path = input.call(parse_meta_path)?; parse_meta_list_after_path(path, input) } } pub(crate) enum NestedMeta { Path(syn::Path), List(MetaList), } impl Parse for NestedMeta { fn parse(input: ParseStream) -> syn::Result<Self> { let path = input.call(parse_meta_path)?; parse_meta_after_path(path, input) } } pub(crate) struct AttributeArgs(Vec<NestedMeta>); impl Parse for AttributeArgs { fn parse(input: ParseStream) -> syn::Result<Self> { let mut attrs = Vec::new(); while input.peek(syn::Ident::peek_any) { attrs.push(input.parse()?); if input.is_empty() { break } let _: syn::token::Comma = input.parse()?; } Ok(AttributeArgs { 0: attrs }) } } impl std::ops::Deref for AttributeArgs { type Target = Vec<NestedMeta>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for AttributeArgs { fn deref_mut(&mut self) -> &mut Vec<NestedMeta> { &mut self.0 } } pub(crate) struct Attributes(Vec<syn::Attribute>); impl Parse for Attributes { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Self(syn::Attribute::parse_outer(input)?)) } } impl Attributes { pub(crate) fn attr(&self) -> &Vec<syn::Attribute> { &self.0 } } // Returns "ink-as-dependency" and not("ink-as-dependency") impls pub(crate) fn impl_external_trait( mut impl_item: syn::ItemImpl, trait_ident: &syn::Ident, metadata: &Metadata, ) -> (Vec<syn::Item>, Vec<syn::Item>) { let impl_ink_attrs = extract_attr(&mut impl_item.attrs, "ink"); let mut ink_methods: HashMap<String, syn::TraitItemMethod> = HashMap::new(); metadata .external_traits .get(&trait_ident.to_string()) .methods() .iter() .for_each(|method| { if is_attr(&method.attrs, "ink") { let mut empty_method = method.clone(); empty_method.default = Some( syn::parse2(quote! { { unimplemented!() } }) .unwrap(), ); let mut attrs = empty_method.attrs.clone(); empty_method.attrs = extract_attr(&mut attrs, "doc"); empty_method.attrs.append(&mut extract_attr(&mut attrs, "ink")); ink_methods.insert(method.sig.ident.to_string(), empty_method); } }); // Move ink! attrs from internal trait to external impl_item.items.iter_mut().for_each(|mut item| { if let syn::ImplItem::Method(method) = &mut item { let method_key = method.sig.ident.to_string(); if ink_methods.contains_key(&method_key) { // Internal attrs will override external, so user must include full declaration with ink(message) and etc. ink_methods.get_mut(&method_key).unwrap().attrs = extract_attr(&mut method.attrs, "doc"); ink_methods .get_mut(&method_key) .unwrap() .attrs .append(&mut extract_attr(&mut method.attrs, "ink")); } } }); let ink_methods_iter = ink_methods.iter().map(|(_, value)| value); let self_ty = impl_item.self_ty.clone().as_ref().clone(); let draft_impl: ItemImpl = syn::parse2(quote! { #(#impl_ink_attrs)* impl #trait_ident for #self_ty { #(#ink_methods_iter)* } }) .unwrap(); // Evaluate selector and metadata_name for each method based on rules in ink! let ink_impl = ::ink_lang_ir::ItemImpl::try_from(draft_impl).unwrap(); ink_impl.iter_messages().for_each(|message| { let method = ink_methods.get_mut(&message.ident().to_string()).unwrap(); if message.user_provided_selector().is_none() { let selector_u32 = u32::from_be_bytes(message.composed_selector().as_bytes().clone()) as usize; let selector = format!("{:#010x}", selector_u32); method.attrs.push(new_attribute(quote! {#[ink(selector = #selector)]})); } if message.metadata_name() == message.ident().to_string() { let selector = format!("{}", message.metadata_name()); method .attrs .push(new_attribute(quote! {#[ink(metadata_name = #selector)]})); } let original_name = message.ident(); let inputs_params = message.inputs().map(|pat_type| &pat_type.pat); method.default = Some( syn::parse2(quote! { { #trait_ident::#original_name(self #(, #inputs_params )* ) } }) .unwrap(), ); }); let ink_methods_iter = ink_methods.iter().map(|(_, value)| value); let wrapper_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, WRAPPER_TRAIT_SUFFIX); // We only want to use this implementation in case when ink-as-dependency for wrapper. // It will provide methods with the same name like in initial trait. let wrapper_impl: ItemImpl = syn::parse2(quote! { #(#impl_ink_attrs)* impl #wrapper_trait_ident for #self_ty { #(#ink_methods_iter)* } }) .unwrap(); let trait_name = ink_impl .trait_path() .map(|path| path.segments.last().unwrap().ident.to_string()); let mut metadata_name_attr = quote! {}; if trait_name == ink_impl.trait_metadata_name() { let name = format!("{}", trait_name.unwrap()); metadata_name_attr = quote! { #[ink(metadata_name = #name)] } } let external_ink_methods_iter = ink_methods.iter_mut().map(|(_, value)| { value.sig.ident = format_ident!("{}_{}{}", BRUSH_PREFIX, value.sig.ident, EXTERNAL_METHOD_SUFFIX); value }); let external_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, EXTERNAL_TRAIT_SUFFIX); // It is implementation of "external" trait(trait where all method marked with ink!) // This trait has another name with external suffix. And all methods have external signature. // But ABI generated by this impl section is the same as ABI generated by original trait. let external_impl: ItemImpl = syn::parse2(quote! { #metadata_name_attr #(#impl_ink_attrs)* impl #external_trait_ident for #self_ty { #(#external_ink_methods_iter)* } }) .unwrap(); // Internal implementation must be disable during "ink-as-dependency" let internal_impl = impl_item; ( vec![syn::Item::from(wrapper_impl)], vec![syn::Item::from(internal_impl), syn::Item::from(external_impl)], ) } #[inline] pub(crate) fn is_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> bool { if let None = attrs .iter() .find(|attr| attr.path.segments.last().expect("No segments in path").ident == ident) { false } else { true } } #[inline] #[allow(dead_code)] pub(crate) fn get_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> Option<syn::Attribute> { for attr in attrs.iter() { if is_attr(&vec![attr.clone()], ident) { return Some(attr.clone()) } } None } #[inline] pub(crate) fn remove_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> Vec<syn::Attribute> { attrs .clone() .into_iter() .filter_map(|attr| { if is_attr(&vec![attr.clone()], ident) { None } else { Some(attr) } }) .collect() } #[inline] pub(crate) fn extract_attr(attrs: &mut Vec<syn::Attribute>, ident: &str) -> Vec<syn::Attribute> { attrs.drain_filter(|attr| is_attr(&vec![attr.clone()], ident)).collect() } #[inline] pub(crate) fn new_attribute(attr_stream: TokenStream2) -> syn::Attribute { syn::parse2::<Attributes>(attr_stream).unwrap().attr()[0].clone() } /// Computes the BLAKE-2b 256-bit hash for the given input and stores it in output. #[inline] pub fn blake2b_256(input: &[u8], output: &mut [u8]) { use ::blake2::digest::{ Update as _, VariableOutput as _, }; let mut blake2 = blake2::VarBlake2b::new_keyed(&[], 32); blake2.update(input); blake2.finalize_variable(|result| output.copy_from_slice(result)); } #[inline] pub(crate) fn blake2b_256_str(input: String) -> [u8; 32] { let mut output: [u8; 32] = [0; 32]; blake2b_256(&input.into_bytes(), &mut output); output } #[inline] pub(crate) fn sanitize_to_str(input: TokenStream) -> String { let mut str = input.to_string(); // Remove quotes rom the string str.drain(1..str.len() - 1).collect() }
parse
identifier_name
internal.rs
extern crate proc_macro; use ink_lang_ir::Callable; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, }; use std::{ collections::HashMap, convert::TryFrom, }; use syn::{ ext::IdentExt, parenthesized, parse::{ Parse, ParseStream, }, ItemImpl, }; use crate::{ metadata::Metadata, trait_definition::{ EXTERNAL_METHOD_SUFFIX, EXTERNAL_TRAIT_SUFFIX, WRAPPER_TRAIT_SUFFIX, }, }; pub(crate) const BRUSH_PREFIX: &'static str = "__brush"; pub(crate) struct MetaList { pub path: syn::Path, pub _paren_token: syn::token::Paren, pub nested: syn::punctuated::Punctuated<TokenStream2, syn::Token![,]>, } // Like Path::parse_mod_style but accepts keywords in the path. fn parse_meta_path(input: ParseStream) -> syn::Result<syn::Path>
}, }) } fn parse_meta_list_after_path(path: syn::Path, input: ParseStream) -> syn::Result<MetaList> { let content; Ok(MetaList { path, _paren_token: parenthesized!(content in input), nested: content.parse_terminated(TokenStream2::parse)?, }) } fn parse_meta_after_path(path: syn::Path, input: ParseStream) -> syn::Result<NestedMeta> { if input.peek(syn::token::Paren) { parse_meta_list_after_path(path, input).map(NestedMeta::List) } else { Ok(NestedMeta::Path(path)) } } impl Parse for MetaList { fn parse(input: ParseStream) -> syn::Result<Self> { let path = input.call(parse_meta_path)?; parse_meta_list_after_path(path, input) } } pub(crate) enum NestedMeta { Path(syn::Path), List(MetaList), } impl Parse for NestedMeta { fn parse(input: ParseStream) -> syn::Result<Self> { let path = input.call(parse_meta_path)?; parse_meta_after_path(path, input) } } pub(crate) struct AttributeArgs(Vec<NestedMeta>); impl Parse for AttributeArgs { fn parse(input: ParseStream) -> syn::Result<Self> { let mut attrs = Vec::new(); while input.peek(syn::Ident::peek_any) { attrs.push(input.parse()?); if input.is_empty() { break } let _: syn::token::Comma = input.parse()?; } Ok(AttributeArgs { 0: attrs }) } } impl std::ops::Deref for AttributeArgs { type Target = Vec<NestedMeta>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for AttributeArgs { fn deref_mut(&mut self) -> &mut Vec<NestedMeta> { &mut self.0 } } pub(crate) struct Attributes(Vec<syn::Attribute>); impl Parse for Attributes { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Self(syn::Attribute::parse_outer(input)?)) } } impl Attributes { pub(crate) fn attr(&self) -> &Vec<syn::Attribute> { &self.0 } } // Returns "ink-as-dependency" and not("ink-as-dependency") impls pub(crate) fn impl_external_trait( mut impl_item: syn::ItemImpl, trait_ident: &syn::Ident, metadata: &Metadata, ) -> (Vec<syn::Item>, Vec<syn::Item>) { let impl_ink_attrs = extract_attr(&mut impl_item.attrs, "ink"); let mut ink_methods: HashMap<String, syn::TraitItemMethod> = HashMap::new(); metadata .external_traits .get(&trait_ident.to_string()) .methods() .iter() .for_each(|method| { if is_attr(&method.attrs, "ink") { let mut empty_method = method.clone(); empty_method.default = Some( syn::parse2(quote! { { unimplemented!() } }) .unwrap(), ); let mut attrs = empty_method.attrs.clone(); empty_method.attrs = extract_attr(&mut attrs, "doc"); empty_method.attrs.append(&mut extract_attr(&mut attrs, "ink")); ink_methods.insert(method.sig.ident.to_string(), empty_method); } }); // Move ink! attrs from internal trait to external impl_item.items.iter_mut().for_each(|mut item| { if let syn::ImplItem::Method(method) = &mut item { let method_key = method.sig.ident.to_string(); if ink_methods.contains_key(&method_key) { // Internal attrs will override external, so user must include full declaration with ink(message) and etc. ink_methods.get_mut(&method_key).unwrap().attrs = extract_attr(&mut method.attrs, "doc"); ink_methods .get_mut(&method_key) .unwrap() .attrs .append(&mut extract_attr(&mut method.attrs, "ink")); } } }); let ink_methods_iter = ink_methods.iter().map(|(_, value)| value); let self_ty = impl_item.self_ty.clone().as_ref().clone(); let draft_impl: ItemImpl = syn::parse2(quote! { #(#impl_ink_attrs)* impl #trait_ident for #self_ty { #(#ink_methods_iter)* } }) .unwrap(); // Evaluate selector and metadata_name for each method based on rules in ink! let ink_impl = ::ink_lang_ir::ItemImpl::try_from(draft_impl).unwrap(); ink_impl.iter_messages().for_each(|message| { let method = ink_methods.get_mut(&message.ident().to_string()).unwrap(); if message.user_provided_selector().is_none() { let selector_u32 = u32::from_be_bytes(message.composed_selector().as_bytes().clone()) as usize; let selector = format!("{:#010x}", selector_u32); method.attrs.push(new_attribute(quote! {#[ink(selector = #selector)]})); } if message.metadata_name() == message.ident().to_string() { let selector = format!("{}", message.metadata_name()); method .attrs .push(new_attribute(quote! {#[ink(metadata_name = #selector)]})); } let original_name = message.ident(); let inputs_params = message.inputs().map(|pat_type| &pat_type.pat); method.default = Some( syn::parse2(quote! { { #trait_ident::#original_name(self #(, #inputs_params )* ) } }) .unwrap(), ); }); let ink_methods_iter = ink_methods.iter().map(|(_, value)| value); let wrapper_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, WRAPPER_TRAIT_SUFFIX); // We only want to use this implementation in case when ink-as-dependency for wrapper. // It will provide methods with the same name like in initial trait. let wrapper_impl: ItemImpl = syn::parse2(quote! { #(#impl_ink_attrs)* impl #wrapper_trait_ident for #self_ty { #(#ink_methods_iter)* } }) .unwrap(); let trait_name = ink_impl .trait_path() .map(|path| path.segments.last().unwrap().ident.to_string()); let mut metadata_name_attr = quote! {}; if trait_name == ink_impl.trait_metadata_name() { let name = format!("{}", trait_name.unwrap()); metadata_name_attr = quote! { #[ink(metadata_name = #name)] } } let external_ink_methods_iter = ink_methods.iter_mut().map(|(_, value)| { value.sig.ident = format_ident!("{}_{}{}", BRUSH_PREFIX, value.sig.ident, EXTERNAL_METHOD_SUFFIX); value }); let external_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, EXTERNAL_TRAIT_SUFFIX); // It is implementation of "external" trait(trait where all method marked with ink!) // This trait has another name with external suffix. And all methods have external signature. // But ABI generated by this impl section is the same as ABI generated by original trait. let external_impl: ItemImpl = syn::parse2(quote! { #metadata_name_attr #(#impl_ink_attrs)* impl #external_trait_ident for #self_ty { #(#external_ink_methods_iter)* } }) .unwrap(); // Internal implementation must be disable during "ink-as-dependency" let internal_impl = impl_item; ( vec![syn::Item::from(wrapper_impl)], vec![syn::Item::from(internal_impl), syn::Item::from(external_impl)], ) } #[inline] pub(crate) fn is_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> bool { if let None = attrs .iter() .find(|attr| attr.path.segments.last().expect("No segments in path").ident == ident) { false } else { true } } #[inline] #[allow(dead_code)] pub(crate) fn get_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> Option<syn::Attribute> { for attr in attrs.iter() { if is_attr(&vec![attr.clone()], ident) { return Some(attr.clone()) } } None } #[inline] pub(crate) fn remove_attr(attrs: &Vec<syn::Attribute>, ident: &str) -> Vec<syn::Attribute> { attrs .clone() .into_iter() .filter_map(|attr| { if is_attr(&vec![attr.clone()], ident) { None } else { Some(attr) } }) .collect() } #[inline] pub(crate) fn extract_attr(attrs: &mut Vec<syn::Attribute>, ident: &str) -> Vec<syn::Attribute> { attrs.drain_filter(|attr| is_attr(&vec![attr.clone()], ident)).collect() } #[inline] pub(crate) fn new_attribute(attr_stream: TokenStream2) -> syn::Attribute { syn::parse2::<Attributes>(attr_stream).unwrap().attr()[0].clone() } /// Computes the BLAKE-2b 256-bit hash for the given input and stores it in output. #[inline] pub fn blake2b_256(input: &[u8], output: &mut [u8]) { use ::blake2::digest::{ Update as _, VariableOutput as _, }; let mut blake2 = blake2::VarBlake2b::new_keyed(&[], 32); blake2.update(input); blake2.finalize_variable(|result| output.copy_from_slice(result)); } #[inline] pub(crate) fn blake2b_256_str(input: String) -> [u8; 32] { let mut output: [u8; 32] = [0; 32]; blake2b_256(&input.into_bytes(), &mut output); output } #[inline] pub(crate) fn sanitize_to_str(input: TokenStream) -> String { let mut str = input.to_string(); // Remove quotes rom the string str.drain(1..str.len() - 1).collect() }
{ Ok(syn::Path { leading_colon: input.parse()?, segments: { let mut segments = syn::punctuated::Punctuated::new(); while input.peek(syn::Ident::peek_any) { let ident = syn::Ident::parse_any(input)?; segments.push_value(syn::PathSegment::from(ident)); if !input.peek(syn::Token![::]) { break } let punct = input.parse()?; segments.push_punct(punct); } if segments.is_empty() { return Err(input.error("expected path")) } else if segments.trailing_punct() { return Err(input.error("expected path segment")) } segments
identifier_body
main.rs
extern crate ginseng; use ginseng::guest::Guest; use ginseng::guest::Range; use std::cmp::min; use std::cmp::Ordering; use std:collections::HashMap; use std::vec::Vec; fn social_welfare(proposed_allocation: &Vec<(&Guest, u64)>) -> u64 { let mut total_welfare: u64 = 0; for (guest, allocation) in proposed_allocation { total_welfare += guest.mem_unit_price * allocation; } total_welfare } // assumes that `guest_list` has already been sorted // just doles out memory in sorted order such that we // don't give anyone any more memory than they asked for // it's still possible that we give people too little memory // which should be checked after getting the result of this // function // I think what I really want to return from this is a vector of allocation amounts // it'll even take up less space than (reference, allocation) pairs and will be much // less problematic fn naive_allocation ( guest_list: &Vec<&Guest>, available_memory: u64 ) -> Vec<(u64)> { let mut remaining_memory: u64 = available_memory; guest_list.iter().map ( |guest| { // if there's no memory left to hand out our job is simple if remaining_memory == 0 { 0 } // otherwise get the maximum amount memory this guest // wants to pay for and give them that else { // if the last forbidden range goes to infinity we want //to use the minimum of that forbidden range let upper_bound = guest .forbidden_ranges .last() .filter(|range| {range.max == u64::max_value()}) .map(|range| {range.min}) .unwrap_or(u64::max_value()); let mem_to_alloc = min(remaining_memory, upper_bound); remaining_memory -= mem_to_alloc; mem_to_alloc } } ).collect() } // this guy already returns indices instead of references fn
(proposed_allocations: &Vec<(&Guest, u64)>) -> Vec<(usize, Range)> { let mut violations: Vec<(usize, Range)> = Vec::new(); let mut index: usize = 0; for &(guest, amount) in proposed_allocations.iter() { // we want to get the guest's forbidden range with the greatest // min value that is less than amount. This would probably best // be done with a binary search, but for now iterative is fine for range in guest.forbidden_ranges.clone() { if range.min < amount && range.max > amount { violations.push((index, range)); } } index = index + 1; } violations } fn public_auction_function ( guest_list: &Vec<&Guest>, available_memory: u64 ) -> Vec<u64> { auction_with_pinned_allocations(guest_list, available_memory, Vec::new()) } // returns the list of allocations of the provided memory to the list of // provided guests which results in the maximal social welfare possible without // changing the provided pinned allocations fn auction_with_pinned_allocations ( guest_list: &Vec<&Guest>, available_memory: u64, pinned_allocations: &HashMap<u64, u64> //list of (index, allocation) pairs ) -> Vec<u64> { // so I think the idea is we filter the pinned allocations out in an // enumerate into a filter into a map that discards the index into a // collect // then we put them back into the result of the recursive case with an // enumerate into a flatmap that returns element + // contiguous-succesive-elements. So we just need a mutable `index_correction` // variable that gets incremented every time we insert an element so we // can keep track of each elements place in the new list so we can map positions in // the enumerate to positions in the original list let my_copy = guest_list .iter() .enumerate() .filter(|(index, &guest)|!pinned_allocations.contains_key(index)) .map(|(index, &guest)| guest.clone()) .collect() // let mut my_copy = guest_list.clone(); let invalid = invalid_allocations(my_copy.iter().zip(naive_allocation(my_copy, available_memory)) } // Given the applicable range for an invalid allocation and the amount of available_memory // this function returns the one to two allocation options available to replace the // invalid allocation fn two_options(applicable_range: Range, available_memory: u64) -> Vec<u64> { match applicable_range.max.cmp(&available_memory) { Ordering::Less | Ordering::Equal => vec![applicable_range.min, applicable_range.max], Ordering::Greater => vec![applicable_range.min], } } //I think I want an immutable list slice that I jut progressively slice more off of // or present different iterators of maybe? // the payment rule should be implemented in a different function // so that we can use this function recursively // I think what we should really return from this is a list of (index, allocation) pairs // and take as input a list of inidices of invalid allocations (we can have a helper function //without that argument that passes an empty list into this function) // fn auction<'a>(guest_list: &'a mut Vec<&'a Guest>, available_memory: u64) -> Vec<(&'a Guest, u64)> // { // if guest_list.is_empty() // { // return Vec::new(); // } // // // so first we try just try giving as much as // // possible of the remaining_memory // // to each guest // let applicable_range: Range; // let invalid_guest_number; // { // //then we first attempt a naive allocation based solely on the sorting // //and any upper bounds the guests may have set // // naive_allocation should maintain the same ordering of geusts as guest_list // // so indices of proposed_allocation can be used to index into guest_list // let proposed_allocations = naive_allocation(guest_list, available_memory); // // let mut invalid = invalid_allocations(&proposed_allocations); // // // yup, commenting out this early return got rid of two of the 3 compile errors // // and the third is pretty obviously a good thing to error out on because it let me know // //I was adding two guests for case two instead of just one // // if invalid.is_empty() // // { // // return proposed_allocations; // // } // // // so with this first attempt we want to first check and see if we're // // assigning someone an amount of memory in one of their forbidden ranges // // and for each case in which someone was allocated an invalid amount, we // // need to try two cases. // // so we just need to try removing the first invalid allocation, which means // // we can just mutate the guest_list instead of cloning every time // let (_invalid_guest_number, _applicable_range) = invalid.remove(0); // invalid_guest_number = _invalid_guest_number; // applicable_range = _applicable_range; // // } // //so we remove the first invalid allcoation // let badly_served_guest = guest_list.remove(invalid_guest_number); // // // and then we try the two cases with that guest // // // So I think the idea is that we try the minimum and maximum of the // // forbidden range that the invalid value fell into // // //case one is no more than the minimum of the forbidden range // let allocation_amount_one = applicable_range.min; // // let mut case_one_proposal = auction(guest_list, available_memory - allocation_amount_one); // // case_one_proposal.push((badly_served_guest, allocation_amount_one)); // // let case_one_welfare = social_welfare(&case_one_proposal); // // //case two is at least as much as the maximum of the forbidden range // let allocation_amount_two = applicable_range.max; // // let (case_two_welfare, case_two_proposal) = // if allocation_amount_two <= available_memory // { // let mut inner_case_two_proposal = // auction(guest_list, available_memory - allocation_amount_two); // // inner_case_two_proposal.push((badly_served_guest, allocation_amount_two)); // // (social_welfare(&inner_case_two_proposal), inner_case_two_proposal) // } // else // { // (0, Vec::new()) // }; // // // // //return the one with greater welfare, or if equal, the one that allocates less memory // match case_one_welfare.cmp(&case_two_welfare) // { // Ordering::Less => case_two_proposal, // // Ordering::Greater => case_one_proposal, // // Ordering::Equal => case_one_proposal, // } // } // fn registerGuest(baseMemory: i64) // { // // } // fn makeBid(mem_unit_price: f64, guest: Guest) // { // // } fn main() { let guest1 = Guest { mem_unit_price: 2, current_holdings: 1, forbidden_ranges: vec! [ Range{min: 0, max: 3}, Range{min: 4, max: u64::max_value()} ], base_memory: 10 }; let guest2 = Guest { mem_unit_price: 1, current_holdings: 1, forbidden_ranges: vec! [ Range{min: 0, max: 3}, Range{min: 5, max: u64::max_value()} ], base_memory: 10 }; let mut guest_list = vec![&guest1, &guest2]; guest_list.sort_unstable(); { for guest in &guest_list { println!("{:?}", guest); } } { let naive = naive_allocation(&guest_list, 6); println!("The naive allocation is: ", ); { for (ref guest, allocated) in &naive { println!("{:?} gets {:?}", guest, allocated); } } println!("it has a social welfare of {:?}", social_welfare(&naive)); } let final_allocation = auction(&mut guest_list, 6); println!("The final allocation is: ", ); { for (ref guest, allocated) in &final_allocation { println!("{:?} gets {:?}", guest, allocated); } } println!("it has a social welfare of {:?}", social_welfare(&final_allocation)); println!("Hello, world!"); }
invalid_allocations
identifier_name
main.rs
extern crate ginseng; use ginseng::guest::Guest; use ginseng::guest::Range; use std::cmp::min; use std::cmp::Ordering; use std:collections::HashMap; use std::vec::Vec; fn social_welfare(proposed_allocation: &Vec<(&Guest, u64)>) -> u64 { let mut total_welfare: u64 = 0; for (guest, allocation) in proposed_allocation { total_welfare += guest.mem_unit_price * allocation; } total_welfare } // assumes that `guest_list` has already been sorted // just doles out memory in sorted order such that we // don't give anyone any more memory than they asked for // it's still possible that we give people too little memory // which should be checked after getting the result of this // function // I think what I really want to return from this is a vector of allocation amounts // it'll even take up less space than (reference, allocation) pairs and will be much // less problematic fn naive_allocation ( guest_list: &Vec<&Guest>, available_memory: u64 ) -> Vec<(u64)>
.forbidden_ranges .last() .filter(|range| {range.max == u64::max_value()}) .map(|range| {range.min}) .unwrap_or(u64::max_value()); let mem_to_alloc = min(remaining_memory, upper_bound); remaining_memory -= mem_to_alloc; mem_to_alloc } } ).collect() } // this guy already returns indices instead of references fn invalid_allocations(proposed_allocations: &Vec<(&Guest, u64)>) -> Vec<(usize, Range)> { let mut violations: Vec<(usize, Range)> = Vec::new(); let mut index: usize = 0; for &(guest, amount) in proposed_allocations.iter() { // we want to get the guest's forbidden range with the greatest // min value that is less than amount. This would probably best // be done with a binary search, but for now iterative is fine for range in guest.forbidden_ranges.clone() { if range.min < amount && range.max > amount { violations.push((index, range)); } } index = index + 1; } violations } fn public_auction_function ( guest_list: &Vec<&Guest>, available_memory: u64 ) -> Vec<u64> { auction_with_pinned_allocations(guest_list, available_memory, Vec::new()) } // returns the list of allocations of the provided memory to the list of // provided guests which results in the maximal social welfare possible without // changing the provided pinned allocations fn auction_with_pinned_allocations ( guest_list: &Vec<&Guest>, available_memory: u64, pinned_allocations: &HashMap<u64, u64> //list of (index, allocation) pairs ) -> Vec<u64> { // so I think the idea is we filter the pinned allocations out in an // enumerate into a filter into a map that discards the index into a // collect // then we put them back into the result of the recursive case with an // enumerate into a flatmap that returns element + // contiguous-succesive-elements. So we just need a mutable `index_correction` // variable that gets incremented every time we insert an element so we // can keep track of each elements place in the new list so we can map positions in // the enumerate to positions in the original list let my_copy = guest_list .iter() .enumerate() .filter(|(index, &guest)|!pinned_allocations.contains_key(index)) .map(|(index, &guest)| guest.clone()) .collect() // let mut my_copy = guest_list.clone(); let invalid = invalid_allocations(my_copy.iter().zip(naive_allocation(my_copy, available_memory)) } // Given the applicable range for an invalid allocation and the amount of available_memory // this function returns the one to two allocation options available to replace the // invalid allocation fn two_options(applicable_range: Range, available_memory: u64) -> Vec<u64> { match applicable_range.max.cmp(&available_memory) { Ordering::Less | Ordering::Equal => vec![applicable_range.min, applicable_range.max], Ordering::Greater => vec![applicable_range.min], } } //I think I want an immutable list slice that I jut progressively slice more off of // or present different iterators of maybe? // the payment rule should be implemented in a different function // so that we can use this function recursively // I think what we should really return from this is a list of (index, allocation) pairs // and take as input a list of inidices of invalid allocations (we can have a helper function //without that argument that passes an empty list into this function) // fn auction<'a>(guest_list: &'a mut Vec<&'a Guest>, available_memory: u64) -> Vec<(&'a Guest, u64)> // { // if guest_list.is_empty() // { // return Vec::new(); // } // // // so first we try just try giving as much as // // possible of the remaining_memory // // to each guest // let applicable_range: Range; // let invalid_guest_number; // { // //then we first attempt a naive allocation based solely on the sorting // //and any upper bounds the guests may have set // // naive_allocation should maintain the same ordering of geusts as guest_list // // so indices of proposed_allocation can be used to index into guest_list // let proposed_allocations = naive_allocation(guest_list, available_memory); // // let mut invalid = invalid_allocations(&proposed_allocations); // // // yup, commenting out this early return got rid of two of the 3 compile errors // // and the third is pretty obviously a good thing to error out on because it let me know // //I was adding two guests for case two instead of just one // // if invalid.is_empty() // // { // // return proposed_allocations; // // } // // // so with this first attempt we want to first check and see if we're // // assigning someone an amount of memory in one of their forbidden ranges // // and for each case in which someone was allocated an invalid amount, we // // need to try two cases. // // so we just need to try removing the first invalid allocation, which means // // we can just mutate the guest_list instead of cloning every time // let (_invalid_guest_number, _applicable_range) = invalid.remove(0); // invalid_guest_number = _invalid_guest_number; // applicable_range = _applicable_range; // // } // //so we remove the first invalid allcoation // let badly_served_guest = guest_list.remove(invalid_guest_number); // // // and then we try the two cases with that guest // // // So I think the idea is that we try the minimum and maximum of the // // forbidden range that the invalid value fell into // // //case one is no more than the minimum of the forbidden range // let allocation_amount_one = applicable_range.min; // // let mut case_one_proposal = auction(guest_list, available_memory - allocation_amount_one); // // case_one_proposal.push((badly_served_guest, allocation_amount_one)); // // let case_one_welfare = social_welfare(&case_one_proposal); // // //case two is at least as much as the maximum of the forbidden range // let allocation_amount_two = applicable_range.max; // // let (case_two_welfare, case_two_proposal) = // if allocation_amount_two <= available_memory // { // let mut inner_case_two_proposal = // auction(guest_list, available_memory - allocation_amount_two); // // inner_case_two_proposal.push((badly_served_guest, allocation_amount_two)); // // (social_welfare(&inner_case_two_proposal), inner_case_two_proposal) // } // else // { // (0, Vec::new()) // }; // // // // //return the one with greater welfare, or if equal, the one that allocates less memory // match case_one_welfare.cmp(&case_two_welfare) // { // Ordering::Less => case_two_proposal, // // Ordering::Greater => case_one_proposal, // // Ordering::Equal => case_one_proposal, // } // } // fn registerGuest(baseMemory: i64) // { // // } // fn makeBid(mem_unit_price: f64, guest: Guest) // { // // } fn main() { let guest1 = Guest { mem_unit_price: 2, current_holdings: 1, forbidden_ranges: vec! [ Range{min: 0, max: 3}, Range{min: 4, max: u64::max_value()} ], base_memory: 10 }; let guest2 = Guest { mem_unit_price: 1, current_holdings: 1, forbidden_ranges: vec! [ Range{min: 0, max: 3}, Range{min: 5, max: u64::max_value()} ], base_memory: 10 }; let mut guest_list = vec![&guest1, &guest2]; guest_list.sort_unstable(); { for guest in &guest_list { println!("{:?}", guest); } } { let naive = naive_allocation(&guest_list, 6); println!("The naive allocation is: ", ); { for (ref guest, allocated) in &naive { println!("{:?} gets {:?}", guest, allocated); } } println!("it has a social welfare of {:?}", social_welfare(&naive)); } let final_allocation = auction(&mut guest_list, 6); println!("The final allocation is: ", ); { for (ref guest, allocated) in &final_allocation { println!("{:?} gets {:?}", guest, allocated); } } println!("it has a social welfare of {:?}", social_welfare(&final_allocation)); println!("Hello, world!"); }
{ let mut remaining_memory: u64 = available_memory; guest_list.iter().map ( |guest| { // if there's no memory left to hand out our job is simple if remaining_memory == 0 { 0 } // otherwise get the maximum amount memory this guest // wants to pay for and give them that else { // if the last forbidden range goes to infinity we want //to use the minimum of that forbidden range let upper_bound = guest
identifier_body
main.rs
extern crate ginseng; use ginseng::guest::Guest; use ginseng::guest::Range; use std::cmp::min; use std::cmp::Ordering; use std:collections::HashMap; use std::vec::Vec; fn social_welfare(proposed_allocation: &Vec<(&Guest, u64)>) -> u64 { let mut total_welfare: u64 = 0; for (guest, allocation) in proposed_allocation { total_welfare += guest.mem_unit_price * allocation; } total_welfare } // assumes that `guest_list` has already been sorted // just doles out memory in sorted order such that we // don't give anyone any more memory than they asked for // it's still possible that we give people too little memory
// which should be checked after getting the result of this // function // I think what I really want to return from this is a vector of allocation amounts // it'll even take up less space than (reference, allocation) pairs and will be much // less problematic fn naive_allocation ( guest_list: &Vec<&Guest>, available_memory: u64 ) -> Vec<(u64)> { let mut remaining_memory: u64 = available_memory; guest_list.iter().map ( |guest| { // if there's no memory left to hand out our job is simple if remaining_memory == 0 { 0 } // otherwise get the maximum amount memory this guest // wants to pay for and give them that else { // if the last forbidden range goes to infinity we want //to use the minimum of that forbidden range let upper_bound = guest .forbidden_ranges .last() .filter(|range| {range.max == u64::max_value()}) .map(|range| {range.min}) .unwrap_or(u64::max_value()); let mem_to_alloc = min(remaining_memory, upper_bound); remaining_memory -= mem_to_alloc; mem_to_alloc } } ).collect() } // this guy already returns indices instead of references fn invalid_allocations(proposed_allocations: &Vec<(&Guest, u64)>) -> Vec<(usize, Range)> { let mut violations: Vec<(usize, Range)> = Vec::new(); let mut index: usize = 0; for &(guest, amount) in proposed_allocations.iter() { // we want to get the guest's forbidden range with the greatest // min value that is less than amount. This would probably best // be done with a binary search, but for now iterative is fine for range in guest.forbidden_ranges.clone() { if range.min < amount && range.max > amount { violations.push((index, range)); } } index = index + 1; } violations } fn public_auction_function ( guest_list: &Vec<&Guest>, available_memory: u64 ) -> Vec<u64> { auction_with_pinned_allocations(guest_list, available_memory, Vec::new()) } // returns the list of allocations of the provided memory to the list of // provided guests which results in the maximal social welfare possible without // changing the provided pinned allocations fn auction_with_pinned_allocations ( guest_list: &Vec<&Guest>, available_memory: u64, pinned_allocations: &HashMap<u64, u64> //list of (index, allocation) pairs ) -> Vec<u64> { // so I think the idea is we filter the pinned allocations out in an // enumerate into a filter into a map that discards the index into a // collect // then we put them back into the result of the recursive case with an // enumerate into a flatmap that returns element + // contiguous-succesive-elements. So we just need a mutable `index_correction` // variable that gets incremented every time we insert an element so we // can keep track of each elements place in the new list so we can map positions in // the enumerate to positions in the original list let my_copy = guest_list .iter() .enumerate() .filter(|(index, &guest)|!pinned_allocations.contains_key(index)) .map(|(index, &guest)| guest.clone()) .collect() // let mut my_copy = guest_list.clone(); let invalid = invalid_allocations(my_copy.iter().zip(naive_allocation(my_copy, available_memory)) } // Given the applicable range for an invalid allocation and the amount of available_memory // this function returns the one to two allocation options available to replace the // invalid allocation fn two_options(applicable_range: Range, available_memory: u64) -> Vec<u64> { match applicable_range.max.cmp(&available_memory) { Ordering::Less | Ordering::Equal => vec![applicable_range.min, applicable_range.max], Ordering::Greater => vec![applicable_range.min], } } //I think I want an immutable list slice that I jut progressively slice more off of // or present different iterators of maybe? // the payment rule should be implemented in a different function // so that we can use this function recursively // I think what we should really return from this is a list of (index, allocation) pairs // and take as input a list of inidices of invalid allocations (we can have a helper function //without that argument that passes an empty list into this function) // fn auction<'a>(guest_list: &'a mut Vec<&'a Guest>, available_memory: u64) -> Vec<(&'a Guest, u64)> // { // if guest_list.is_empty() // { // return Vec::new(); // } // // // so first we try just try giving as much as // // possible of the remaining_memory // // to each guest // let applicable_range: Range; // let invalid_guest_number; // { // //then we first attempt a naive allocation based solely on the sorting // //and any upper bounds the guests may have set // // naive_allocation should maintain the same ordering of geusts as guest_list // // so indices of proposed_allocation can be used to index into guest_list // let proposed_allocations = naive_allocation(guest_list, available_memory); // // let mut invalid = invalid_allocations(&proposed_allocations); // // // yup, commenting out this early return got rid of two of the 3 compile errors // // and the third is pretty obviously a good thing to error out on because it let me know // //I was adding two guests for case two instead of just one // // if invalid.is_empty() // // { // // return proposed_allocations; // // } // // // so with this first attempt we want to first check and see if we're // // assigning someone an amount of memory in one of their forbidden ranges // // and for each case in which someone was allocated an invalid amount, we // // need to try two cases. // // so we just need to try removing the first invalid allocation, which means // // we can just mutate the guest_list instead of cloning every time // let (_invalid_guest_number, _applicable_range) = invalid.remove(0); // invalid_guest_number = _invalid_guest_number; // applicable_range = _applicable_range; // // } // //so we remove the first invalid allcoation // let badly_served_guest = guest_list.remove(invalid_guest_number); // // // and then we try the two cases with that guest // // // So I think the idea is that we try the minimum and maximum of the // // forbidden range that the invalid value fell into // // //case one is no more than the minimum of the forbidden range // let allocation_amount_one = applicable_range.min; // // let mut case_one_proposal = auction(guest_list, available_memory - allocation_amount_one); // // case_one_proposal.push((badly_served_guest, allocation_amount_one)); // // let case_one_welfare = social_welfare(&case_one_proposal); // // //case two is at least as much as the maximum of the forbidden range // let allocation_amount_two = applicable_range.max; // // let (case_two_welfare, case_two_proposal) = // if allocation_amount_two <= available_memory // { // let mut inner_case_two_proposal = // auction(guest_list, available_memory - allocation_amount_two); // // inner_case_two_proposal.push((badly_served_guest, allocation_amount_two)); // // (social_welfare(&inner_case_two_proposal), inner_case_two_proposal) // } // else // { // (0, Vec::new()) // }; // // // // //return the one with greater welfare, or if equal, the one that allocates less memory // match case_one_welfare.cmp(&case_two_welfare) // { // Ordering::Less => case_two_proposal, // // Ordering::Greater => case_one_proposal, // // Ordering::Equal => case_one_proposal, // } // } // fn registerGuest(baseMemory: i64) // { // // } // fn makeBid(mem_unit_price: f64, guest: Guest) // { // // } fn main() { let guest1 = Guest { mem_unit_price: 2, current_holdings: 1, forbidden_ranges: vec! [ Range{min: 0, max: 3}, Range{min: 4, max: u64::max_value()} ], base_memory: 10 }; let guest2 = Guest { mem_unit_price: 1, current_holdings: 1, forbidden_ranges: vec! [ Range{min: 0, max: 3}, Range{min: 5, max: u64::max_value()} ], base_memory: 10 }; let mut guest_list = vec![&guest1, &guest2]; guest_list.sort_unstable(); { for guest in &guest_list { println!("{:?}", guest); } } { let naive = naive_allocation(&guest_list, 6); println!("The naive allocation is: ", ); { for (ref guest, allocated) in &naive { println!("{:?} gets {:?}", guest, allocated); } } println!("it has a social welfare of {:?}", social_welfare(&naive)); } let final_allocation = auction(&mut guest_list, 6); println!("The final allocation is: ", ); { for (ref guest, allocated) in &final_allocation { println!("{:?} gets {:?}", guest, allocated); } } println!("it has a social welfare of {:?}", social_welfare(&final_allocation)); println!("Hello, world!"); }
random_line_split
map.rs
use super::BareDoomMap; use super::geom::{Coord, Point, Rect, Size}; use std::collections::HashMap; use std::marker::PhantomData; use std; // TODO // map diagnostics // - error: // - info: unused vertex // - info: unused side // - info: sector with no sides // - info: thing not in the map (polyobjs excluded) /// A fully-fledged map, independent (more or less) of any particular underlying format. // TODO actually i'm not so sure about that! should i, say, have different map impls that use // different types... pub struct Map { /* lines: Vec<Rc<RefCell<Line>>>, sides: Vec<Rc<RefCell<Side>>>, sectors: Vec<Rc<RefCell<Sector>>>, things: Vec<Rc<RefCell<Thing>>>, vertices: Vec<Rc<RefCell<Vertex>>>, */ lines: Vec<Line>, sides: Vec<Side>, sectors: Vec<Sector>, things: Vec<Thing>, vertices: Vec<Vertex>, bbox: Option<Rect>, } impl Map { pub fn new() -> Self { Map { lines: Vec::new(), sides: Vec::new(), sectors: Vec::new(), things: Vec::new(), vertices: Vec::new(), bbox: None, } } pub fn from_bare(bare_map: &BareDoomMap) -> Self { let mut map = Map::new(); for bare_sector in bare_map.sectors.iter() { let sectorh = map.add_sector(); let sector = &mut map.sectors[sectorh.0]; sector.tag = bare_sector.sector_tag as u32; sector.special = bare_sector.sector_type as u32; sector.floor_height = bare_sector.floor_height as i32; sector.ceiling_height = bare_sector.ceiling_height as i32; } for bare_vertex in bare_map.vertices.iter() { map.add_vertex(bare_vertex.x as f64, bare_vertex.y as f64); } for bare_side in bare_map.sides.iter() { let handle = map.add_side((bare_side.sector as usize).into()); let side = map.side_mut(handle); side.lower_texture = bare_side.lower_texture.into(); side.middle_texture = bare_side.middle_texture.into(); side.upper_texture = bare_side.upper_texture.into(); } for bare_line in bare_map.lines.iter() { let handle = map.add_line((bare_line.v0 as usize).into(), (bare_line.v1 as usize).into()); let line = map.line_mut(handle); line.flags = bare_line.flags as u32; // FIXME and here's where we start to go awry -- this should use a method. so should // new side w/ sector if bare_line.front_sidedef!= -1 { line.front = Some((bare_line.front_sidedef as usize).into()); } if bare_line.back_sidedef!= -1 { line.back = Some((bare_line.back_sidedef as usize).into()); } } for bare_thing in bare_map.things.iter() { map.things.push(Thing{ point: Point::new(bare_thing.x as Coord, bare_thing.y as Coord), doomednum: bare_thing.doomednum as u32, }); } map } fn side_mut(&mut self, handle: Handle<Side>) -> &mut Side { &mut self.sides[handle.0] } fn line_mut(&mut self, handle: Handle<Line>) -> &mut Line { &mut self.lines[handle.0] } fn add_sector(&mut self) -> Handle<Sector> { self.sectors.push(Sector{ special: 0, tag: 0, floor_height: 0, ceiling_height: 0 }); (self.sectors.len() - 1).into() } fn add_side(&mut self, sector: Handle<Sector>) -> Handle<Side> { self.sides.push(Side{ id: 0, lower_texture: "".into(), middle_texture: "".into(), upper_texture: "".into(), sector: sector, }); (self.sides.len() - 1).into() } fn add_vertex(&mut self, x: f64, y: f64) { self.vertices.push(Vertex{ x, y }); //self.vertices.push(vertex); //return vertex; } fn add_line(&mut self, start: Handle<Vertex>, end: Handle<Vertex>) -> Handle<Line> { self.lines.push(Line{ start, end, flags: 0, special: 0, front: None, back: None, }); (self.lines.len() - 1).into() } pub fn iter_lines(&self) -> <Vec<BoundLine> as IntoIterator>::IntoIter { let bound: Vec<_> = self.lines.iter().map(|a| BoundLine(a, self)).collect(); bound.into_iter() // return self.lines.iter().map(|a| BoundLine(a, self)); } pub fn iter_sectors(&self) -> std::slice::Iter<Sector> { self.sectors.iter() } pub fn iter_things(&self) -> std::slice::Iter<Thing> { self.things.iter() } pub fn vertex(&self, handle: Handle<Vertex>) -> &Vertex { &self.vertices[handle.0] } pub fn side(&self, handle: Handle<Side>) -> &Side { &self.sides[handle.0] } pub fn sector(&self, handle: Handle<Sector>) -> &Sector { &self.sectors[handle.0] } pub fn bbox(&self) -> Rect { // TODO ah heck, should include Things too let points: Vec<_> = self.vertices.iter().map(|v| Point::new(v.x, v.y)).collect(); Rect::from_points(points.iter()) } pub fn find_player_start(&self) -> Option<Point> { for thing in &self.things { if thing.doomednum() == 1 { return Some(thing.point()); } } None } pub fn sector_to_polygons(&self, s: usize) -> Vec<Vec<Point>> { struct Edge<'a> { line: &'a Line, side: &'a Side, facing: Facing, v0: &'a Vertex, v1: &'a Vertex, done: bool, } // This is just to convince HashMap to hash on the actual reference, not the underlying // BareVertex value struct VertexRef<'a>(&'a Vertex); impl<'a> PartialEq for VertexRef<'a> { fn eq(&self, other: &VertexRef) -> bool { (self.0 as *const _) == (other.0 as *const _) } } impl<'a> Eq for VertexRef<'a> {} impl<'a> std::hash::Hash for VertexRef<'a> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { (self.0 as *const Vertex).hash(state) } } let mut edges = vec![]; let mut vertices_to_edges = HashMap::new(); // TODO linear scan -- would make more sense to turn the entire map into polygons in one go for line in &self.lines { let (frontid, backid) = line.side_indices(); // FIXME need to handle self-referencing sectors, but also if let Some(front) = line.front.map(|h| &self.sides[h.0]) { if let Some(back) = line.back.map(|h| &self.sides[h.0]) { if front.sector == back.sector { continue; } } } // TODO seems like a good case for a custom iterator for &(facing, sideid) in [(Facing::Front, frontid), (Facing::Back, backid)].iter() { if sideid.is_none() { continue; } // TODO this and the vertices lookups might be bogus and crash... let side = &self.sides[sideid.unwrap().0]; if side.sector.0 == s { let v0 = &self.vertices[line.start.0]; let v1 = &self.vertices[line.end.0]; let edge = Edge{ line, side, facing, // TODO should these be swapped depending on the line facing? v0, v1, done: false, }; edges.push(edge); vertices_to_edges.entry(VertexRef(v0)).or_insert_with(|| Vec::new()).push(edges.len() - 1); vertices_to_edges.entry(VertexRef(v1)).or_insert_with(|| Vec::new()).push(edges.len() - 1); } } } // Trace sectors by starting at the first side's first vertex and attempting to walk from // there let mut outlines = Vec::new(); let mut seen_vertices = HashMap::new(); while edges.len() > 0 { let mut next_vertices = vec![]; for edge in edges.iter() { // TODO having done-ness for both edges and vertices seems weird, idk if!seen_vertices.contains_key(&VertexRef(edge.v0)) { next_vertices.push(edge.v0); break; } if!seen_vertices.contains_key(&VertexRef(edge.v1)) { next_vertices.push(edge.v1); break; } } if next_vertices.is_empty() { break; } let mut outline = Vec::new(); while next_vertices.len() > 0 { let vertices = next_vertices; next_vertices = Vec::new(); for vertex in vertices.iter() { if seen_vertices.contains_key(&VertexRef(vertex)) { continue; } seen_vertices.insert(VertexRef(vertex), true); outline.push(Point::new(vertex.x, vertex.y)); // TODO so, problems occur here if: // - a vertex has more than two edges // - special case: double-sided edges are OK! but we have to eliminate // those, WITHOUT ruining entirely self-referencing sectors // - a vertex has one edge for e in vertices_to_edges.get(&VertexRef(vertex)).unwrap().iter() { let edge = &mut edges[*e]; if edge.done { // TODO actually this seems weird? why would this happen. continue; } edge.done = true; if!seen_vertices.contains_key(&VertexRef(edge.v0)) { next_vertices.push(edge.v0); } else if!seen_vertices.contains_key(&VertexRef(edge.v1)) { next_vertices.push(edge.v1); } // Only add EXACTLY ONE vertex at a time for now -- so, assuming simple // polygons! Figure out the rest, uh, later. break; } } } if outline.len() > 0 { outlines.push(outline); } } outlines } } #[derive(Copy, Clone, Debug)] pub enum Facing { Front, Back, } pub struct Handle<T>(usize, PhantomData<*const T>); // These traits are implemented by hand because #derive'd impls only apply when T implements the // same trait, but we don't actually own a T, so that bound is unnecessary. impl<T> Clone for Handle<T> { fn clone(&self) -> Self { Handle(self.0, PhantomData) } } impl<T> Copy for Handle<T> {} impl<T> PartialEq for Handle<T> { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl<T> Eq for Handle<T> {} impl<T> std::hash::Hash for Handle<T> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.0.hash(state) } } impl<T> From<usize> for Handle<T> { fn from(index: usize) -> Self { Handle(index, PhantomData) } } trait MapComponent {} pub struct Thing { point: Point, doomednum: u32, } impl Thing { pub fn point(&self) -> Point { self.point } pub fn doomednum(&self) -> u32 { self.doomednum } } pub struct Line { start: Handle<Vertex>, end: Handle<Vertex>, flags: u32, special: usize, //sector_tag -- oops, different in zdoom... front: Option<Handle<Side>>, back: Option<Handle<Side>>, } impl Line { pub fn vertex_indices(&self) -> (Handle<Vertex>, Handle<Vertex>) { (self.start, self.end) } pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) { (self.front, self.back) } pub fn has_special(&self) -> bool { self.special!= 0 } pub fn blocks_player(&self) -> bool { self.flags & 1!= 0 } pub fn is_one_sided(&self) -> bool { self.front.is_some()!= self.back.is_some() } pub fn is_two_sided(&self) -> bool { self.front.is_some() && self.back.is_some() } } // A Line that knows what map it came from, so it can look up its actual sides and vertices #[derive(Clone, Copy)] pub struct BoundLine<'a>(&'a Line, &'a Map); impl<'a> BoundLine<'a> { pub fn start(&self) -> &Vertex { self.1.vertex(self.0.start) } pub fn end(&self) -> &Vertex { self.1.vertex(self.0.end) } pub fn front(&self) -> Option<&Side> { self.0.front.map(|s| self.1.side(s)) } pub fn back(&self) -> Option<&Side> { self.0.back.map(|s| self.1.side(s)) } // TODO these are all delegates, eugh pub fn
(&self) -> (Handle<Vertex>, Handle<Vertex>) { self.0.vertex_indices() } pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) { self.0.side_indices() } pub fn has_special(&self) -> bool { self.0.has_special() } pub fn blocks_player(&self) -> bool { self.0.blocks_player() } pub fn is_one_sided(&self) -> bool { self.0.is_one_sided() } pub fn is_two_sided(&self) -> bool { self.0.is_two_sided() } } pub struct Sector { tag: u32, special: u32, floor_height: i32, ceiling_height: i32, } impl Sector { pub fn tag(&self) -> u32 { self.tag } pub fn special(&self) -> u32 { self.special } pub fn floor_height(&self) -> i32 { self.floor_height } pub fn ceiling_height(&self) -> i32 { self.ceiling_height } } pub struct Side { //map: Rc<Map>, pub id: u32, pub upper_texture: String, pub lower_texture: String, pub middle_texture: String, pub sector: Handle<Sector>, } #[derive(Clone, Copy)] pub struct BoundSide<'a>(&'a Side, &'a Map); impl<'a> BoundSide<'a> { //pub fn sector(&self) -> } pub struct Vertex { pub x: f64, pub y: f64, }
vertex_indices
identifier_name
map.rs
use super::BareDoomMap; use super::geom::{Coord, Point, Rect, Size}; use std::collections::HashMap; use std::marker::PhantomData; use std; // TODO // map diagnostics // - error: // - info: unused vertex // - info: unused side // - info: sector with no sides // - info: thing not in the map (polyobjs excluded) /// A fully-fledged map, independent (more or less) of any particular underlying format. // TODO actually i'm not so sure about that! should i, say, have different map impls that use // different types... pub struct Map { /* lines: Vec<Rc<RefCell<Line>>>, sides: Vec<Rc<RefCell<Side>>>, sectors: Vec<Rc<RefCell<Sector>>>, things: Vec<Rc<RefCell<Thing>>>, vertices: Vec<Rc<RefCell<Vertex>>>, */ lines: Vec<Line>, sides: Vec<Side>, sectors: Vec<Sector>, things: Vec<Thing>, vertices: Vec<Vertex>, bbox: Option<Rect>, } impl Map { pub fn new() -> Self { Map { lines: Vec::new(), sides: Vec::new(), sectors: Vec::new(), things: Vec::new(), vertices: Vec::new(), bbox: None, } } pub fn from_bare(bare_map: &BareDoomMap) -> Self { let mut map = Map::new(); for bare_sector in bare_map.sectors.iter() { let sectorh = map.add_sector(); let sector = &mut map.sectors[sectorh.0]; sector.tag = bare_sector.sector_tag as u32; sector.special = bare_sector.sector_type as u32; sector.floor_height = bare_sector.floor_height as i32; sector.ceiling_height = bare_sector.ceiling_height as i32; } for bare_vertex in bare_map.vertices.iter() { map.add_vertex(bare_vertex.x as f64, bare_vertex.y as f64); } for bare_side in bare_map.sides.iter() { let handle = map.add_side((bare_side.sector as usize).into()); let side = map.side_mut(handle); side.lower_texture = bare_side.lower_texture.into(); side.middle_texture = bare_side.middle_texture.into(); side.upper_texture = bare_side.upper_texture.into(); } for bare_line in bare_map.lines.iter() { let handle = map.add_line((bare_line.v0 as usize).into(), (bare_line.v1 as usize).into()); let line = map.line_mut(handle); line.flags = bare_line.flags as u32; // FIXME and here's where we start to go awry -- this should use a method. so should // new side w/ sector if bare_line.front_sidedef!= -1 { line.front = Some((bare_line.front_sidedef as usize).into()); } if bare_line.back_sidedef!= -1 { line.back = Some((bare_line.back_sidedef as usize).into()); } } for bare_thing in bare_map.things.iter() { map.things.push(Thing{ point: Point::new(bare_thing.x as Coord, bare_thing.y as Coord), doomednum: bare_thing.doomednum as u32, }); } map } fn side_mut(&mut self, handle: Handle<Side>) -> &mut Side { &mut self.sides[handle.0] } fn line_mut(&mut self, handle: Handle<Line>) -> &mut Line { &mut self.lines[handle.0] } fn add_sector(&mut self) -> Handle<Sector> { self.sectors.push(Sector{ special: 0, tag: 0, floor_height: 0, ceiling_height: 0 }); (self.sectors.len() - 1).into() } fn add_side(&mut self, sector: Handle<Sector>) -> Handle<Side> { self.sides.push(Side{ id: 0, lower_texture: "".into(), middle_texture: "".into(), upper_texture: "".into(), sector: sector, }); (self.sides.len() - 1).into() } fn add_vertex(&mut self, x: f64, y: f64) { self.vertices.push(Vertex{ x, y }); //self.vertices.push(vertex); //return vertex; } fn add_line(&mut self, start: Handle<Vertex>, end: Handle<Vertex>) -> Handle<Line> { self.lines.push(Line{ start, end, flags: 0, special: 0, front: None, back: None, }); (self.lines.len() - 1).into() } pub fn iter_lines(&self) -> <Vec<BoundLine> as IntoIterator>::IntoIter { let bound: Vec<_> = self.lines.iter().map(|a| BoundLine(a, self)).collect(); bound.into_iter() // return self.lines.iter().map(|a| BoundLine(a, self)); } pub fn iter_sectors(&self) -> std::slice::Iter<Sector> { self.sectors.iter() } pub fn iter_things(&self) -> std::slice::Iter<Thing> { self.things.iter() } pub fn vertex(&self, handle: Handle<Vertex>) -> &Vertex { &self.vertices[handle.0] } pub fn side(&self, handle: Handle<Side>) -> &Side { &self.sides[handle.0] } pub fn sector(&self, handle: Handle<Sector>) -> &Sector { &self.sectors[handle.0] } pub fn bbox(&self) -> Rect { // TODO ah heck, should include Things too let points: Vec<_> = self.vertices.iter().map(|v| Point::new(v.x, v.y)).collect(); Rect::from_points(points.iter()) } pub fn find_player_start(&self) -> Option<Point> { for thing in &self.things { if thing.doomednum() == 1 { return Some(thing.point()); } } None } pub fn sector_to_polygons(&self, s: usize) -> Vec<Vec<Point>> { struct Edge<'a> { line: &'a Line, side: &'a Side, facing: Facing, v0: &'a Vertex, v1: &'a Vertex, done: bool, } // This is just to convince HashMap to hash on the actual reference, not the underlying // BareVertex value struct VertexRef<'a>(&'a Vertex); impl<'a> PartialEq for VertexRef<'a> { fn eq(&self, other: &VertexRef) -> bool { (self.0 as *const _) == (other.0 as *const _) } } impl<'a> Eq for VertexRef<'a> {} impl<'a> std::hash::Hash for VertexRef<'a> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { (self.0 as *const Vertex).hash(state) } } let mut edges = vec![]; let mut vertices_to_edges = HashMap::new(); // TODO linear scan -- would make more sense to turn the entire map into polygons in one go for line in &self.lines { let (frontid, backid) = line.side_indices(); // FIXME need to handle self-referencing sectors, but also if let Some(front) = line.front.map(|h| &self.sides[h.0]) { if let Some(back) = line.back.map(|h| &self.sides[h.0]) { if front.sector == back.sector { continue; } } } // TODO seems like a good case for a custom iterator for &(facing, sideid) in [(Facing::Front, frontid), (Facing::Back, backid)].iter() { if sideid.is_none() { continue; } // TODO this and the vertices lookups might be bogus and crash... let side = &self.sides[sideid.unwrap().0]; if side.sector.0 == s { let v0 = &self.vertices[line.start.0]; let v1 = &self.vertices[line.end.0]; let edge = Edge{ line, side, facing, // TODO should these be swapped depending on the line facing? v0, v1, done: false, }; edges.push(edge); vertices_to_edges.entry(VertexRef(v0)).or_insert_with(|| Vec::new()).push(edges.len() - 1); vertices_to_edges.entry(VertexRef(v1)).or_insert_with(|| Vec::new()).push(edges.len() - 1); } } } // Trace sectors by starting at the first side's first vertex and attempting to walk from // there let mut outlines = Vec::new(); let mut seen_vertices = HashMap::new(); while edges.len() > 0 { let mut next_vertices = vec![]; for edge in edges.iter() { // TODO having done-ness for both edges and vertices seems weird, idk if!seen_vertices.contains_key(&VertexRef(edge.v0)) { next_vertices.push(edge.v0); break; } if!seen_vertices.contains_key(&VertexRef(edge.v1)) { next_vertices.push(edge.v1); break; } } if next_vertices.is_empty() { break; } let mut outline = Vec::new(); while next_vertices.len() > 0 { let vertices = next_vertices; next_vertices = Vec::new(); for vertex in vertices.iter() { if seen_vertices.contains_key(&VertexRef(vertex)) { continue; } seen_vertices.insert(VertexRef(vertex), true); outline.push(Point::new(vertex.x, vertex.y)); // TODO so, problems occur here if: // - a vertex has more than two edges // - special case: double-sided edges are OK! but we have to eliminate // those, WITHOUT ruining entirely self-referencing sectors // - a vertex has one edge for e in vertices_to_edges.get(&VertexRef(vertex)).unwrap().iter() { let edge = &mut edges[*e]; if edge.done { // TODO actually this seems weird? why would this happen. continue; } edge.done = true; if!seen_vertices.contains_key(&VertexRef(edge.v0)) { next_vertices.push(edge.v0); } else if!seen_vertices.contains_key(&VertexRef(edge.v1)) { next_vertices.push(edge.v1); } // Only add EXACTLY ONE vertex at a time for now -- so, assuming simple // polygons! Figure out the rest, uh, later. break; } } } if outline.len() > 0 { outlines.push(outline); } } outlines } } #[derive(Copy, Clone, Debug)] pub enum Facing { Front, Back, } pub struct Handle<T>(usize, PhantomData<*const T>); // These traits are implemented by hand because #derive'd impls only apply when T implements the // same trait, but we don't actually own a T, so that bound is unnecessary. impl<T> Clone for Handle<T> { fn clone(&self) -> Self { Handle(self.0, PhantomData) } } impl<T> Copy for Handle<T> {} impl<T> PartialEq for Handle<T> { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl<T> Eq for Handle<T> {} impl<T> std::hash::Hash for Handle<T> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.0.hash(state)
} } impl<T> From<usize> for Handle<T> { fn from(index: usize) -> Self { Handle(index, PhantomData) } } trait MapComponent {} pub struct Thing { point: Point, doomednum: u32, } impl Thing { pub fn point(&self) -> Point { self.point } pub fn doomednum(&self) -> u32 { self.doomednum } } pub struct Line { start: Handle<Vertex>, end: Handle<Vertex>, flags: u32, special: usize, //sector_tag -- oops, different in zdoom... front: Option<Handle<Side>>, back: Option<Handle<Side>>, } impl Line { pub fn vertex_indices(&self) -> (Handle<Vertex>, Handle<Vertex>) { (self.start, self.end) } pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) { (self.front, self.back) } pub fn has_special(&self) -> bool { self.special!= 0 } pub fn blocks_player(&self) -> bool { self.flags & 1!= 0 } pub fn is_one_sided(&self) -> bool { self.front.is_some()!= self.back.is_some() } pub fn is_two_sided(&self) -> bool { self.front.is_some() && self.back.is_some() } } // A Line that knows what map it came from, so it can look up its actual sides and vertices #[derive(Clone, Copy)] pub struct BoundLine<'a>(&'a Line, &'a Map); impl<'a> BoundLine<'a> { pub fn start(&self) -> &Vertex { self.1.vertex(self.0.start) } pub fn end(&self) -> &Vertex { self.1.vertex(self.0.end) } pub fn front(&self) -> Option<&Side> { self.0.front.map(|s| self.1.side(s)) } pub fn back(&self) -> Option<&Side> { self.0.back.map(|s| self.1.side(s)) } // TODO these are all delegates, eugh pub fn vertex_indices(&self) -> (Handle<Vertex>, Handle<Vertex>) { self.0.vertex_indices() } pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) { self.0.side_indices() } pub fn has_special(&self) -> bool { self.0.has_special() } pub fn blocks_player(&self) -> bool { self.0.blocks_player() } pub fn is_one_sided(&self) -> bool { self.0.is_one_sided() } pub fn is_two_sided(&self) -> bool { self.0.is_two_sided() } } pub struct Sector { tag: u32, special: u32, floor_height: i32, ceiling_height: i32, } impl Sector { pub fn tag(&self) -> u32 { self.tag } pub fn special(&self) -> u32 { self.special } pub fn floor_height(&self) -> i32 { self.floor_height } pub fn ceiling_height(&self) -> i32 { self.ceiling_height } } pub struct Side { //map: Rc<Map>, pub id: u32, pub upper_texture: String, pub lower_texture: String, pub middle_texture: String, pub sector: Handle<Sector>, } #[derive(Clone, Copy)] pub struct BoundSide<'a>(&'a Side, &'a Map); impl<'a> BoundSide<'a> { //pub fn sector(&self) -> } pub struct Vertex { pub x: f64, pub y: f64, }
random_line_split
map.rs
use super::BareDoomMap; use super::geom::{Coord, Point, Rect, Size}; use std::collections::HashMap; use std::marker::PhantomData; use std; // TODO // map diagnostics // - error: // - info: unused vertex // - info: unused side // - info: sector with no sides // - info: thing not in the map (polyobjs excluded) /// A fully-fledged map, independent (more or less) of any particular underlying format. // TODO actually i'm not so sure about that! should i, say, have different map impls that use // different types... pub struct Map { /* lines: Vec<Rc<RefCell<Line>>>, sides: Vec<Rc<RefCell<Side>>>, sectors: Vec<Rc<RefCell<Sector>>>, things: Vec<Rc<RefCell<Thing>>>, vertices: Vec<Rc<RefCell<Vertex>>>, */ lines: Vec<Line>, sides: Vec<Side>, sectors: Vec<Sector>, things: Vec<Thing>, vertices: Vec<Vertex>, bbox: Option<Rect>, } impl Map { pub fn new() -> Self { Map { lines: Vec::new(), sides: Vec::new(), sectors: Vec::new(), things: Vec::new(), vertices: Vec::new(), bbox: None, } } pub fn from_bare(bare_map: &BareDoomMap) -> Self { let mut map = Map::new(); for bare_sector in bare_map.sectors.iter() { let sectorh = map.add_sector(); let sector = &mut map.sectors[sectorh.0]; sector.tag = bare_sector.sector_tag as u32; sector.special = bare_sector.sector_type as u32; sector.floor_height = bare_sector.floor_height as i32; sector.ceiling_height = bare_sector.ceiling_height as i32; } for bare_vertex in bare_map.vertices.iter() { map.add_vertex(bare_vertex.x as f64, bare_vertex.y as f64); } for bare_side in bare_map.sides.iter() { let handle = map.add_side((bare_side.sector as usize).into()); let side = map.side_mut(handle); side.lower_texture = bare_side.lower_texture.into(); side.middle_texture = bare_side.middle_texture.into(); side.upper_texture = bare_side.upper_texture.into(); } for bare_line in bare_map.lines.iter() { let handle = map.add_line((bare_line.v0 as usize).into(), (bare_line.v1 as usize).into()); let line = map.line_mut(handle); line.flags = bare_line.flags as u32; // FIXME and here's where we start to go awry -- this should use a method. so should // new side w/ sector if bare_line.front_sidedef!= -1 { line.front = Some((bare_line.front_sidedef as usize).into()); } if bare_line.back_sidedef!= -1 { line.back = Some((bare_line.back_sidedef as usize).into()); } } for bare_thing in bare_map.things.iter() { map.things.push(Thing{ point: Point::new(bare_thing.x as Coord, bare_thing.y as Coord), doomednum: bare_thing.doomednum as u32, }); } map } fn side_mut(&mut self, handle: Handle<Side>) -> &mut Side { &mut self.sides[handle.0] } fn line_mut(&mut self, handle: Handle<Line>) -> &mut Line { &mut self.lines[handle.0] } fn add_sector(&mut self) -> Handle<Sector> { self.sectors.push(Sector{ special: 0, tag: 0, floor_height: 0, ceiling_height: 0 }); (self.sectors.len() - 1).into() } fn add_side(&mut self, sector: Handle<Sector>) -> Handle<Side> { self.sides.push(Side{ id: 0, lower_texture: "".into(), middle_texture: "".into(), upper_texture: "".into(), sector: sector, }); (self.sides.len() - 1).into() } fn add_vertex(&mut self, x: f64, y: f64) { self.vertices.push(Vertex{ x, y }); //self.vertices.push(vertex); //return vertex; } fn add_line(&mut self, start: Handle<Vertex>, end: Handle<Vertex>) -> Handle<Line> { self.lines.push(Line{ start, end, flags: 0, special: 0, front: None, back: None, }); (self.lines.len() - 1).into() } pub fn iter_lines(&self) -> <Vec<BoundLine> as IntoIterator>::IntoIter { let bound: Vec<_> = self.lines.iter().map(|a| BoundLine(a, self)).collect(); bound.into_iter() // return self.lines.iter().map(|a| BoundLine(a, self)); } pub fn iter_sectors(&self) -> std::slice::Iter<Sector>
pub fn iter_things(&self) -> std::slice::Iter<Thing> { self.things.iter() } pub fn vertex(&self, handle: Handle<Vertex>) -> &Vertex { &self.vertices[handle.0] } pub fn side(&self, handle: Handle<Side>) -> &Side { &self.sides[handle.0] } pub fn sector(&self, handle: Handle<Sector>) -> &Sector { &self.sectors[handle.0] } pub fn bbox(&self) -> Rect { // TODO ah heck, should include Things too let points: Vec<_> = self.vertices.iter().map(|v| Point::new(v.x, v.y)).collect(); Rect::from_points(points.iter()) } pub fn find_player_start(&self) -> Option<Point> { for thing in &self.things { if thing.doomednum() == 1 { return Some(thing.point()); } } None } pub fn sector_to_polygons(&self, s: usize) -> Vec<Vec<Point>> { struct Edge<'a> { line: &'a Line, side: &'a Side, facing: Facing, v0: &'a Vertex, v1: &'a Vertex, done: bool, } // This is just to convince HashMap to hash on the actual reference, not the underlying // BareVertex value struct VertexRef<'a>(&'a Vertex); impl<'a> PartialEq for VertexRef<'a> { fn eq(&self, other: &VertexRef) -> bool { (self.0 as *const _) == (other.0 as *const _) } } impl<'a> Eq for VertexRef<'a> {} impl<'a> std::hash::Hash for VertexRef<'a> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { (self.0 as *const Vertex).hash(state) } } let mut edges = vec![]; let mut vertices_to_edges = HashMap::new(); // TODO linear scan -- would make more sense to turn the entire map into polygons in one go for line in &self.lines { let (frontid, backid) = line.side_indices(); // FIXME need to handle self-referencing sectors, but also if let Some(front) = line.front.map(|h| &self.sides[h.0]) { if let Some(back) = line.back.map(|h| &self.sides[h.0]) { if front.sector == back.sector { continue; } } } // TODO seems like a good case for a custom iterator for &(facing, sideid) in [(Facing::Front, frontid), (Facing::Back, backid)].iter() { if sideid.is_none() { continue; } // TODO this and the vertices lookups might be bogus and crash... let side = &self.sides[sideid.unwrap().0]; if side.sector.0 == s { let v0 = &self.vertices[line.start.0]; let v1 = &self.vertices[line.end.0]; let edge = Edge{ line, side, facing, // TODO should these be swapped depending on the line facing? v0, v1, done: false, }; edges.push(edge); vertices_to_edges.entry(VertexRef(v0)).or_insert_with(|| Vec::new()).push(edges.len() - 1); vertices_to_edges.entry(VertexRef(v1)).or_insert_with(|| Vec::new()).push(edges.len() - 1); } } } // Trace sectors by starting at the first side's first vertex and attempting to walk from // there let mut outlines = Vec::new(); let mut seen_vertices = HashMap::new(); while edges.len() > 0 { let mut next_vertices = vec![]; for edge in edges.iter() { // TODO having done-ness for both edges and vertices seems weird, idk if!seen_vertices.contains_key(&VertexRef(edge.v0)) { next_vertices.push(edge.v0); break; } if!seen_vertices.contains_key(&VertexRef(edge.v1)) { next_vertices.push(edge.v1); break; } } if next_vertices.is_empty() { break; } let mut outline = Vec::new(); while next_vertices.len() > 0 { let vertices = next_vertices; next_vertices = Vec::new(); for vertex in vertices.iter() { if seen_vertices.contains_key(&VertexRef(vertex)) { continue; } seen_vertices.insert(VertexRef(vertex), true); outline.push(Point::new(vertex.x, vertex.y)); // TODO so, problems occur here if: // - a vertex has more than two edges // - special case: double-sided edges are OK! but we have to eliminate // those, WITHOUT ruining entirely self-referencing sectors // - a vertex has one edge for e in vertices_to_edges.get(&VertexRef(vertex)).unwrap().iter() { let edge = &mut edges[*e]; if edge.done { // TODO actually this seems weird? why would this happen. continue; } edge.done = true; if!seen_vertices.contains_key(&VertexRef(edge.v0)) { next_vertices.push(edge.v0); } else if!seen_vertices.contains_key(&VertexRef(edge.v1)) { next_vertices.push(edge.v1); } // Only add EXACTLY ONE vertex at a time for now -- so, assuming simple // polygons! Figure out the rest, uh, later. break; } } } if outline.len() > 0 { outlines.push(outline); } } outlines } } #[derive(Copy, Clone, Debug)] pub enum Facing { Front, Back, } pub struct Handle<T>(usize, PhantomData<*const T>); // These traits are implemented by hand because #derive'd impls only apply when T implements the // same trait, but we don't actually own a T, so that bound is unnecessary. impl<T> Clone for Handle<T> { fn clone(&self) -> Self { Handle(self.0, PhantomData) } } impl<T> Copy for Handle<T> {} impl<T> PartialEq for Handle<T> { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl<T> Eq for Handle<T> {} impl<T> std::hash::Hash for Handle<T> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.0.hash(state) } } impl<T> From<usize> for Handle<T> { fn from(index: usize) -> Self { Handle(index, PhantomData) } } trait MapComponent {} pub struct Thing { point: Point, doomednum: u32, } impl Thing { pub fn point(&self) -> Point { self.point } pub fn doomednum(&self) -> u32 { self.doomednum } } pub struct Line { start: Handle<Vertex>, end: Handle<Vertex>, flags: u32, special: usize, //sector_tag -- oops, different in zdoom... front: Option<Handle<Side>>, back: Option<Handle<Side>>, } impl Line { pub fn vertex_indices(&self) -> (Handle<Vertex>, Handle<Vertex>) { (self.start, self.end) } pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) { (self.front, self.back) } pub fn has_special(&self) -> bool { self.special!= 0 } pub fn blocks_player(&self) -> bool { self.flags & 1!= 0 } pub fn is_one_sided(&self) -> bool { self.front.is_some()!= self.back.is_some() } pub fn is_two_sided(&self) -> bool { self.front.is_some() && self.back.is_some() } } // A Line that knows what map it came from, so it can look up its actual sides and vertices #[derive(Clone, Copy)] pub struct BoundLine<'a>(&'a Line, &'a Map); impl<'a> BoundLine<'a> { pub fn start(&self) -> &Vertex { self.1.vertex(self.0.start) } pub fn end(&self) -> &Vertex { self.1.vertex(self.0.end) } pub fn front(&self) -> Option<&Side> { self.0.front.map(|s| self.1.side(s)) } pub fn back(&self) -> Option<&Side> { self.0.back.map(|s| self.1.side(s)) } // TODO these are all delegates, eugh pub fn vertex_indices(&self) -> (Handle<Vertex>, Handle<Vertex>) { self.0.vertex_indices() } pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) { self.0.side_indices() } pub fn has_special(&self) -> bool { self.0.has_special() } pub fn blocks_player(&self) -> bool { self.0.blocks_player() } pub fn is_one_sided(&self) -> bool { self.0.is_one_sided() } pub fn is_two_sided(&self) -> bool { self.0.is_two_sided() } } pub struct Sector { tag: u32, special: u32, floor_height: i32, ceiling_height: i32, } impl Sector { pub fn tag(&self) -> u32 { self.tag } pub fn special(&self) -> u32 { self.special } pub fn floor_height(&self) -> i32 { self.floor_height } pub fn ceiling_height(&self) -> i32 { self.ceiling_height } } pub struct Side { //map: Rc<Map>, pub id: u32, pub upper_texture: String, pub lower_texture: String, pub middle_texture: String, pub sector: Handle<Sector>, } #[derive(Clone, Copy)] pub struct BoundSide<'a>(&'a Side, &'a Map); impl<'a> BoundSide<'a> { //pub fn sector(&self) -> } pub struct Vertex { pub x: f64, pub y: f64, }
{ self.sectors.iter() }
identifier_body
syncmgr.rs
PeerId, BlockHash), /// Syncing headers. Syncing { /// Current block header height. current: Height, /// Best known block header height. best: Height, }, /// Synced up to the specified hash and height. Synced(BlockHash, Height), /// Potential stale tip detected on the active chain. StaleTip(LocalTime), /// Peer misbehaved. PeerMisbehaved(PeerId), /// Peer height updated. PeerHeightUpdated { /// Best height known. height: Height, }, } impl std::fmt::Display for Event { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Event::PeerMisbehaved(addr) => { write!(fmt, "{}: Peer misbehaved", addr) } Event::PeerHeightUpdated { height } => { write!(fmt, "Peer height updated to {}", height) } Event::Synced(hash, height) => { write!( fmt, "Headers synced up to height {} with hash {}", height, hash ) } Event::Syncing { current, best } => write!(fmt, "Syncing headers {}/{}", current, best), Event::BlockConnected { height, header } => { write!( fmt, "Block {} connected at height {}", header.block_hash(), height ) } Event::BlockDisconnected { height, header } => { write!( fmt, "Block {} disconnected at height {}", header.block_hash(), height ) } Event::BlockDiscovered(from, hash) => { write!(fmt, "{}: Discovered new block: {}", from, &hash) } Event::StaleTip(last_update) => { write!( fmt, "Potential stale tip detected (last update was {})", last_update ) } } } } /// A `getheaders` request sent to a peer. #[derive(Clone, Debug, PartialEq, Eq)] struct GetHeaders { /// Locators hashes. locators: Locators, /// Time at which the request was sent. sent_at: LocalTime, /// What to do if this request times out. on_timeout: OnTimeout, }
pub fn new(config: Config, rng: fastrand::Rng, upstream: U, clock: C) -> Self { let peers = AddressBook::new(rng.clone()); let last_tip_update = None; let last_peer_sample = None; let last_idle = None; let inflight = HashMap::with_hasher(rng.into()); Self { peers, config, last_tip_update, last_peer_sample, last_idle, inflight, upstream, clock, } } /// Initialize the sync manager. Should only be called once. pub fn initialize<T: BlockReader>(&mut self, tree: &T) { // TODO: `tip` should return the height. let (hash, _) = tree.tip(); let height = tree.height(); self.idle(tree); self.upstream.event(Event::Synced(hash, height)); } /// Called periodically. pub fn idle<T: BlockReader>(&mut self, tree: &T) { let now = self.clock.local_time(); // Nb. The idle timeout is very long: as long as the block interval. // This shouldn't be a problem, as the sync manager can make progress without it. if now - self.last_idle.unwrap_or_default() >= IDLE_TIMEOUT { if!self.sync(tree) { self.sample_peers(tree); } self.last_idle = Some(now); self.upstream.set_timer(IDLE_TIMEOUT); } } /// Called when a new peer was negotiated. pub fn peer_negotiated<T: BlockReader>( &mut self, socket: Socket, height: Height, services: ServiceFlags, preferred: bool, link: Link, tree: &T, ) { if link.is_outbound() &&!services.has(REQUIRED_SERVICES) { return; } if height > self.best_height().unwrap_or_else(|| tree.height()) { self.upstream.event(Event::PeerHeightUpdated { height }); } self.register(socket, height, preferred, link); self.sync(tree); } /// Called when a peer disconnected. pub fn peer_disconnected(&mut self, id: &PeerId) { self.unregister(id); } /// Called when we received a `getheaders` message from a peer. pub fn received_getheaders<T: BlockReader>( &mut self, addr: &PeerId, (locator_hashes, stop_hash): Locators, tree: &T, ) { let max = self.config.max_message_headers; if self.is_syncing() || max == 0 { return; } let headers = tree.locate_headers(&locator_hashes, stop_hash, max); if headers.is_empty() { return; } self.upstream.headers(*addr, headers); } /// Import blocks into our block tree. pub fn import_blocks<T: BlockTree, I: Iterator<Item = BlockHeader>>( &mut self, blocks: I, tree: &mut T, ) -> Result<ImportResult, Error> { match tree.import_blocks(blocks, &self.clock) { Ok(ImportResult::TipChanged(header, tip, height, reverted, connected)) => { let result = ImportResult::TipChanged( header, tip, height, reverted.clone(), connected.clone(), ); for (height, header) in reverted { self.upstream .event(Event::BlockDisconnected { height, header }); } for (height, header) in connected { self.upstream .event(Event::BlockConnected { height, header }); } self.upstream.event(Event::Synced(tip, height)); self.broadcast_tip(&tip, tree); Ok(result) } Ok(result @ ImportResult::TipUnchanged) => Ok(result), Err(err) => Err(err), } } /// Called when we receive headers from a peer. pub fn received_headers<T: BlockTree>( &mut self, from: &PeerId, headers: Vec<BlockHeader>, clock: &impl Clock, tree: &mut T, ) -> Result<ImportResult, store::Error> { let request = self.inflight.remove(from); let headers = if let Some(headers) = NonEmpty::from_vec(headers) { headers } else { return Ok(ImportResult::TipUnchanged); }; let length = headers.len(); if length > MAX_MESSAGE_HEADERS { log::debug!("Received more than maximum headers allowed from {}", from); self.record_misbehavior(from); self.upstream .disconnect(*from, DisconnectReason::PeerMisbehaving("too many headers")); return Ok(ImportResult::TipUnchanged); } // When unsolicited, we don't want to process too many headers in case of a DoS. if length > MAX_UNSOLICITED_HEADERS && request.is_none() { log::debug!("Received {} unsolicited headers from {}", length, from); return Ok(ImportResult::TipUnchanged); } if let Some(peer) = self.peers.get_mut(from) { peer.last_active = Some(clock.local_time()); } else { return Ok(ImportResult::TipUnchanged); } log::debug!("[sync] Received {} block header(s) from {}", length, from); let root = headers.first().block_hash(); let best = headers.last().block_hash(); if tree.contains(&best) { return Ok(ImportResult::TipUnchanged); } match self.import_blocks(headers.into_iter(), tree) { Ok(ImportResult::TipUnchanged) => { // Try to find a common ancestor that leads up to the first header in // the list we received. let locators = (tree.locator_hashes(tree.height()), root); let timeout = self.config.request_timeout; self.request(*from, locators, timeout, OnTimeout::Ignore); Ok(ImportResult::TipUnchanged) } Ok(ImportResult::TipChanged(header, tip, height, reverted, connected)) => { // Update peer height. if let Some(peer) = self.peers.get_mut(from) { if height > peer.height { peer.tip = tip; peer.height = height; } } // Keep track of when we last updated our tip. This is useful to check // whether our tip is stale. self.last_tip_update = Some(clock.local_time()); // If we received less than the maximum number of headers, we must be in sync. // Otherwise, ask for the next batch of headers. if length < MAX_MESSAGE_HEADERS { // If these headers were unsolicited, we may already be ready/synced. // Otherwise, we're finally in sync. self.broadcast_tip(&tip, tree); self.sync(tree); } else { let locators = (vec![tip], BlockHash::all_zeros()); let timeout = self.config.request_timeout; self.request(*from, locators, timeout, OnTimeout::Disconnect); } Ok(ImportResult::TipChanged( header, tip, height, reverted, connected, )) } Err(err) => self .handle_error(from, err) .map(|()| ImportResult::TipUnchanged), } } fn request( &mut self, addr: PeerId, locators: Locators, timeout: LocalDuration, on_timeout: OnTimeout, ) { // Don't request more than once from the same peer. if self.inflight.contains_key(&addr) { return; } if let Some(peer) = self.peers.get_mut(&addr) { debug_assert!(peer.last_asked.as_ref()!= Some(&locators)); peer.last_asked = Some(locators.clone()); let sent_at = self.clock.local_time(); let req = GetHeaders { locators, sent_at, on_timeout, }; self.inflight.insert(addr, req.clone()); self.upstream.get_headers(addr, req.locators); self.upstream.set_timer(timeout); } } /// Called when we received an `inv` message. This will happen if we are out of sync with a /// peer, and blocks are being announced. Otherwise, we expect to receive a `headers` message. pub fn received_inv<T: BlockReader>(&mut self, addr: PeerId, inv: Vec<Inventory>, tree: &T) { // Don't try to fetch headers from `inv` message while syncing. It's not helpful. if self.is_syncing() { return; } // Ignore and disconnect peers misbehaving. if inv.len() > MAX_MESSAGE_INVS { return; } let peer = if let Some(peer) = self.peers.get_mut(&addr) { peer } else { return; }; let mut best_block = None; for i in &inv { if let Inventory::Block(hash) = i { peer.tip = *hash; // "Headers-first is the primary method of announcement on the network. If a node // fell back to sending blocks by inv, it's probably for a re-org. The final block // hash provided should be the highest." if!tree.is_known(hash) { self.upstream.event(Event::BlockDiscovered(addr, *hash)); best_block = Some(hash); } } } if let Some(stop_hash) = best_block { let locators = (tree.locator_hashes(tree.height()), *stop_hash); let timeout = self.config.request_timeout; // Try to find headers leading up to the `inv` entry. self.request(addr, locators, timeout, OnTimeout::Retry(3)); } } /// Called when we received a tick. pub fn received_wake<T: BlockReader>(&mut self, tree: &T) { let local_time = self.clock.local_time(); let timeout = self.config.request_timeout; let timed_out = self .inflight .iter() .filter_map(|(peer, req)| { if local_time - req.sent_at >= timeout { Some((*peer, req.on_timeout, req.clone())) } else { None } }) .collect::<Vec<_>>(); let mut sync = false; for (peer, on_timeout, req) in timed_out { self.inflight.remove(&peer); match on_timeout { OnTimeout::Ignore => { // It's likely that the peer just didn't have the requested header. } OnTimeout::Retry(0) | OnTimeout::Disconnect => { self.upstream .disconnect(peer, DisconnectReason::PeerTimeout("getheaders")); sync = true; } OnTimeout::Retry(n) => { if let Some((addr, _)) = self.peers.sample_with(|a, p| { *a!= peer && self.is_request_candidate(a, p, &req.locators.0) }) { let addr = *addr; self.request(addr, req.locators, timeout, OnTimeout::Retry(n - 1)); } } } } // If some of the requests timed out, force a sync, otherwise just idle. if sync { self.sync(tree); } else { self.idle(tree); } } /// Get the best known height out of all our peers. pub fn best_height(&self) -> Option<Height> { self.peers.iter().map(|(_, p)| p.height).max() } /// Are we currently syncing? pub fn is_syncing(&self) -> bool { !self.inflight.is_empty() } /////////////////////////////////////////////////////////////////////////// fn handle_error(&mut self, from: &PeerId, err: Error) -> Result<(), store::Error> { match err { // If this is an error with the underlying store, we have to propagate // this up, because we can't handle it here. Error::Store(e) => Err(e), // If we got a bad block from the peer, we can handle it here. Error::InvalidBlockPoW | Error::InvalidBlockTarget(_, _) | Error::InvalidBlockHash(_, _) | Error::InvalidBlockHeight(_) | Error::InvalidBlockTime(_, _) => { log::debug!("{}: Received invalid headers: {}", from, err); self.record_misbehavior(from); self.upstream .disconnect(*from, DisconnectReason::PeerMisbehaving("invalid headers")); Ok(()) } // Harmless errors can be ignored. Error::DuplicateBlock(_) | Error::BlockMissing(_) => Ok(()), // TODO: This will be removed. Error::BlockImportAborted(_, _, _) => Ok(()), // These shouldn't happen here. // TODO: Perhaps there's a better way to have this error not show up here. Error::Interrupted | Error::GenesisMismatch => Ok(()), } } fn record_misbehavior(&mut self, peer: &PeerId) { self.upstream.event(Event::PeerMisbehaved(*peer)); } /// Check whether our current tip is stale. /// /// *Nb. This doesn't check whether we've already requested new blocks.* fn stale_tip<T: BlockReader>(&self, tree: &T) -> Option<LocalTime> { let now = self.clock.local_time(); if let Some(last_update) = self.last_tip_update { if last_update < now - LocalDuration::from_secs(self.config.params.pow_target_spacing * 3) { return Some(last_update); } } // If we don't have the time of the last update, it's probably because we // are fresh, or restarted our node. In that case we check the last block time // instead. let (_, tip) = tree.tip(); let time = LocalTime::from_block_time(tip.time); if time <= now - TIP_STALE_DURATION { return Some(time); } None }
impl<U: SetTimer + Disconnect + Wire<Event>, C: Clock> SyncManager<U, C> { /// Create a new sync manager.
random_line_split
syncmgr.rs
{ /// A block was added to the main chain. BlockConnected { /// Block height. height: Height, /// Block header. header: BlockHeader, }, /// A block was removed from the main chain. BlockDisconnected { /// Block height. height: Height, /// Block header. header: BlockHeader, }, /// A new block was discovered via a peer. BlockDiscovered(PeerId, BlockHash), /// Syncing headers. Syncing { /// Current block header height. current: Height, /// Best known block header height. best: Height, }, /// Synced up to the specified hash and height. Synced(BlockHash, Height), /// Potential stale tip detected on the active chain. StaleTip(LocalTime), /// Peer misbehaved. PeerMisbehaved(PeerId), /// Peer height updated. PeerHeightUpdated { /// Best height known. height: Height, }, } impl std::fmt::Display for Event { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Event::PeerMisbehaved(addr) => { write!(fmt, "{}: Peer misbehaved", addr) } Event::PeerHeightUpdated { height } => { write!(fmt, "Peer height updated to {}", height) } Event::Synced(hash, height) => { write!( fmt, "Headers synced up to height {} with hash {}", height, hash ) } Event::Syncing { current, best } => write!(fmt, "Syncing headers {}/{}", current, best), Event::BlockConnected { height, header } => { write!( fmt, "Block {} connected at height {}", header.block_hash(), height ) } Event::BlockDisconnected { height, header } => { write!( fmt, "Block {} disconnected at height {}", header.block_hash(), height ) } Event::BlockDiscovered(from, hash) => { write!(fmt, "{}: Discovered new block: {}", from, &hash) } Event::StaleTip(last_update) => { write!( fmt, "Potential stale tip detected (last update was {})", last_update ) } } } } /// A `getheaders` request sent to a peer. #[derive(Clone, Debug, PartialEq, Eq)] struct GetHeaders { /// Locators hashes. locators: Locators, /// Time at which the request was sent. sent_at: LocalTime, /// What to do if this request times out. on_timeout: OnTimeout, } impl<U: SetTimer + Disconnect + Wire<Event>, C: Clock> SyncManager<U, C> { /// Create a new sync manager. pub fn new(config: Config, rng: fastrand::Rng, upstream: U, clock: C) -> Self { let peers = AddressBook::new(rng.clone()); let last_tip_update = None; let last_peer_sample = None; let last_idle = None; let inflight = HashMap::with_hasher(rng.into()); Self { peers, config, last_tip_update, last_peer_sample, last_idle, inflight, upstream, clock, } } /// Initialize the sync manager. Should only be called once. pub fn initialize<T: BlockReader>(&mut self, tree: &T) { // TODO: `tip` should return the height. let (hash, _) = tree.tip(); let height = tree.height(); self.idle(tree); self.upstream.event(Event::Synced(hash, height)); } /// Called periodically. pub fn idle<T: BlockReader>(&mut self, tree: &T) { let now = self.clock.local_time(); // Nb. The idle timeout is very long: as long as the block interval. // This shouldn't be a problem, as the sync manager can make progress without it. if now - self.last_idle.unwrap_or_default() >= IDLE_TIMEOUT { if!self.sync(tree) { self.sample_peers(tree); } self.last_idle = Some(now); self.upstream.set_timer(IDLE_TIMEOUT); } } /// Called when a new peer was negotiated. pub fn peer_negotiated<T: BlockReader>( &mut self, socket: Socket, height: Height, services: ServiceFlags, preferred: bool, link: Link, tree: &T, ) { if link.is_outbound() &&!services.has(REQUIRED_SERVICES) { return; } if height > self.best_height().unwrap_or_else(|| tree.height()) { self.upstream.event(Event::PeerHeightUpdated { height }); } self.register(socket, height, preferred, link); self.sync(tree); } /// Called when a peer disconnected. pub fn peer_disconnected(&mut self, id: &PeerId) { self.unregister(id); } /// Called when we received a `getheaders` message from a peer. pub fn received_getheaders<T: BlockReader>( &mut self, addr: &PeerId, (locator_hashes, stop_hash): Locators, tree: &T, ) { let max = self.config.max_message_headers; if self.is_syncing() || max == 0 { return; } let headers = tree.locate_headers(&locator_hashes, stop_hash, max); if headers.is_empty() { return; } self.upstream.headers(*addr, headers); } /// Import blocks into our block tree. pub fn import_blocks<T: BlockTree, I: Iterator<Item = BlockHeader>>( &mut self, blocks: I, tree: &mut T, ) -> Result<ImportResult, Error> { match tree.import_blocks(blocks, &self.clock) { Ok(ImportResult::TipChanged(header, tip, height, reverted, connected)) => { let result = ImportResult::TipChanged( header, tip, height, reverted.clone(), connected.clone(), ); for (height, header) in reverted { self.upstream .event(Event::BlockDisconnected { height, header }); } for (height, header) in connected { self.upstream .event(Event::BlockConnected { height, header }); } self.upstream.event(Event::Synced(tip, height)); self.broadcast_tip(&tip, tree); Ok(result) } Ok(result @ ImportResult::TipUnchanged) => Ok(result), Err(err) => Err(err), } } /// Called when we receive headers from a peer. pub fn received_headers<T: BlockTree>( &mut self, from: &PeerId, headers: Vec<BlockHeader>, clock: &impl Clock, tree: &mut T, ) -> Result<ImportResult, store::Error> { let request = self.inflight.remove(from); let headers = if let Some(headers) = NonEmpty::from_vec(headers) { headers } else { return Ok(ImportResult::TipUnchanged); }; let length = headers.len(); if length > MAX_MESSAGE_HEADERS { log::debug!("Received more than maximum headers allowed from {}", from); self.record_misbehavior(from); self.upstream .disconnect(*from, DisconnectReason::PeerMisbehaving("too many headers")); return Ok(ImportResult::TipUnchanged); } // When unsolicited, we don't want to process too many headers in case of a DoS. if length > MAX_UNSOLICITED_HEADERS && request.is_none() { log::debug!("Received {} unsolicited headers from {}", length, from); return Ok(ImportResult::TipUnchanged); } if let Some(peer) = self.peers.get_mut(from) { peer.last_active = Some(clock.local_time()); } else { return Ok(ImportResult::TipUnchanged); } log::debug!("[sync] Received {} block header(s) from {}", length, from); let root = headers.first().block_hash(); let best = headers.last().block_hash(); if tree.contains(&best) { return Ok(ImportResult::TipUnchanged); } match self.import_blocks(headers.into_iter(), tree) { Ok(ImportResult::TipUnchanged) => { // Try to find a common ancestor that leads up to the first header in // the list we received. let locators = (tree.locator_hashes(tree.height()), root); let timeout = self.config.request_timeout; self.request(*from, locators, timeout, OnTimeout::Ignore); Ok(ImportResult::TipUnchanged) } Ok(ImportResult::TipChanged(header, tip, height, reverted, connected)) => { // Update peer height. if let Some(peer) = self.peers.get_mut(from) { if height > peer.height { peer.tip = tip; peer.height = height; } } // Keep track of when we last updated our tip. This is useful to check // whether our tip is stale. self.last_tip_update = Some(clock.local_time()); // If we received less than the maximum number of headers, we must be in sync. // Otherwise, ask for the next batch of headers. if length < MAX_MESSAGE_HEADERS { // If these headers were unsolicited, we may already be ready/synced. // Otherwise, we're finally in sync. self.broadcast_tip(&tip, tree); self.sync(tree); } else { let locators = (vec![tip], BlockHash::all_zeros()); let timeout = self.config.request_timeout; self.request(*from, locators, timeout, OnTimeout::Disconnect); } Ok(ImportResult::TipChanged( header, tip, height, reverted, connected, )) } Err(err) => self .handle_error(from, err) .map(|()| ImportResult::TipUnchanged), } } fn request( &mut self, addr: PeerId, locators: Locators, timeout: LocalDuration, on_timeout: OnTimeout, ) { // Don't request more than once from the same peer. if self.inflight.contains_key(&addr) { return; } if let Some(peer) = self.peers.get_mut(&addr) { debug_assert!(peer.last_asked.as_ref()!= Some(&locators)); peer.last_asked = Some(locators.clone()); let sent_at = self.clock.local_time(); let req = GetHeaders { locators, sent_at, on_timeout, }; self.inflight.insert(addr, req.clone()); self.upstream.get_headers(addr, req.locators); self.upstream.set_timer(timeout); } } /// Called when we received an `inv` message. This will happen if we are out of sync with a /// peer, and blocks are being announced. Otherwise, we expect to receive a `headers` message. pub fn received_inv<T: BlockReader>(&mut self, addr: PeerId, inv: Vec<Inventory>, tree: &T) { // Don't try to fetch headers from `inv` message while syncing. It's not helpful. if self.is_syncing() { return; } // Ignore and disconnect peers misbehaving. if inv.len() > MAX_MESSAGE_INVS { return; } let peer = if let Some(peer) = self.peers.get_mut(&addr) { peer } else { return; }; let mut best_block = None; for i in &inv { if let Inventory::Block(hash) = i { peer.tip = *hash; // "Headers-first is the primary method of announcement on the network. If a node // fell back to sending blocks by inv, it's probably for a re-org. The final block // hash provided should be the highest." if!tree.is_known(hash) { self.upstream.event(Event::BlockDiscovered(addr, *hash)); best_block = Some(hash); } } } if let Some(stop_hash) = best_block { let locators = (tree.locator_hashes(tree.height()), *stop_hash); let timeout = self.config.request_timeout; // Try to find headers leading up to the `inv` entry. self.request(addr, locators, timeout, OnTimeout::Retry(3)); } } /// Called when we received a tick. pub fn received_wake<T: BlockReader>(&mut self, tree: &T) { let local_time = self.clock.local_time(); let timeout = self.config.request_timeout; let timed_out = self .inflight .iter() .filter_map(|(peer, req)| { if local_time - req.sent_at >= timeout { Some((*peer, req.on_timeout, req.clone())) } else { None } }) .collect::<Vec<_>>(); let mut sync = false; for (peer, on_timeout, req) in timed_out { self.inflight.remove(&peer); match on_timeout { OnTimeout::Ignore => { // It's likely that the peer just didn't have the requested header. } OnTimeout::Retry(0) | OnTimeout::Disconnect => { self.upstream .disconnect(peer, DisconnectReason::PeerTimeout("getheaders")); sync = true; } OnTimeout::Retry(n) => { if let Some((addr, _)) = self.peers.sample_with(|a, p| { *a!= peer && self.is_request_candidate(a, p, &req.locators.0) }) { let addr = *addr; self.request(addr, req.locators, timeout, OnTimeout::Retry(n - 1)); } } } } // If some of the requests timed out, force a sync, otherwise just idle. if sync { self.sync(tree); } else { self.idle(tree); } } /// Get the best known height out of all our peers. pub fn best_height(&self) -> Option<Height> { self.peers.iter().map(|(_, p)| p.height).max() } /// Are we currently syncing? pub fn is_syncing(&self) -> bool { !self.inflight.is_empty() } /////////////////////////////////////////////////////////////////////////// fn handle_error(&mut self, from: &PeerId, err: Error) -> Result<(), store::Error> { match err { // If this is an error with the underlying store, we have to propagate // this up, because we can't handle it here. Error::Store(e) => Err(e), // If we got a bad block from the peer, we can handle it here. Error::InvalidBlockPoW | Error::InvalidBlockTarget(_, _) | Error::InvalidBlockHash(_, _) | Error::InvalidBlockHeight(_) | Error::InvalidBlockTime(_, _) => { log::debug!("{}: Received invalid headers: {}", from, err); self.record_misbehavior(from); self.upstream .disconnect(*from, DisconnectReason::PeerMisbehaving("invalid headers")); Ok(()) } // Harmless errors can be ignored. Error::DuplicateBlock(_) | Error::BlockMissing(_) => Ok(()), // TODO: This will be removed. Error::BlockImportAborted(_, _, _) => Ok(()), // These shouldn't happen here. // TODO: Perhaps there's a better way to have this error not show up here. Error::Interrupted | Error::GenesisMismatch => Ok(()), } } fn record_misbehavior(&mut self, peer: &PeerId) { self.upstream.event(Event::PeerMisbehaved(*peer)); } /// Check whether our current tip is stale. /// /// *Nb. This doesn't check whether we've already requested new blocks.* fn stale_tip<T: BlockReader>(&self, tree: &T) -> Option<LocalTime> { let now = self.clock.local_time(); if let Some(last_update) = self.last_tip_update { if last_update < now - LocalDuration::from_secs(self.config.params.pow_target_spacing * 3) { return Some(last_update); }
Event
identifier_name
syncmgr.rs
, BlockHash), /// Syncing headers. Syncing { /// Current block header height. current: Height, /// Best known block header height. best: Height, }, /// Synced up to the specified hash and height. Synced(BlockHash, Height), /// Potential stale tip detected on the active chain. StaleTip(LocalTime), /// Peer misbehaved. PeerMisbehaved(PeerId), /// Peer height updated. PeerHeightUpdated { /// Best height known. height: Height, }, } impl std::fmt::Display for Event { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Event::PeerMisbehaved(addr) => { write!(fmt, "{}: Peer misbehaved", addr) } Event::PeerHeightUpdated { height } => { write!(fmt, "Peer height updated to {}", height) } Event::Synced(hash, height) => { write!( fmt, "Headers synced up to height {} with hash {}", height, hash ) } Event::Syncing { current, best } => write!(fmt, "Syncing headers {}/{}", current, best), Event::BlockConnected { height, header } => { write!( fmt, "Block {} connected at height {}", header.block_hash(), height ) } Event::BlockDisconnected { height, header } => { write!( fmt, "Block {} disconnected at height {}", header.block_hash(), height ) } Event::BlockDiscovered(from, hash) => { write!(fmt, "{}: Discovered new block: {}", from, &hash) } Event::StaleTip(last_update) => { write!( fmt, "Potential stale tip detected (last update was {})", last_update ) } } } } /// A `getheaders` request sent to a peer. #[derive(Clone, Debug, PartialEq, Eq)] struct GetHeaders { /// Locators hashes. locators: Locators, /// Time at which the request was sent. sent_at: LocalTime, /// What to do if this request times out. on_timeout: OnTimeout, } impl<U: SetTimer + Disconnect + Wire<Event>, C: Clock> SyncManager<U, C> { /// Create a new sync manager. pub fn new(config: Config, rng: fastrand::Rng, upstream: U, clock: C) -> Self { let peers = AddressBook::new(rng.clone()); let last_tip_update = None; let last_peer_sample = None; let last_idle = None; let inflight = HashMap::with_hasher(rng.into()); Self { peers, config, last_tip_update, last_peer_sample, last_idle, inflight, upstream, clock, } } /// Initialize the sync manager. Should only be called once. pub fn initialize<T: BlockReader>(&mut self, tree: &T) { // TODO: `tip` should return the height. let (hash, _) = tree.tip(); let height = tree.height(); self.idle(tree); self.upstream.event(Event::Synced(hash, height)); } /// Called periodically. pub fn idle<T: BlockReader>(&mut self, tree: &T) { let now = self.clock.local_time(); // Nb. The idle timeout is very long: as long as the block interval. // This shouldn't be a problem, as the sync manager can make progress without it. if now - self.last_idle.unwrap_or_default() >= IDLE_TIMEOUT { if!self.sync(tree) { self.sample_peers(tree); } self.last_idle = Some(now); self.upstream.set_timer(IDLE_TIMEOUT); } } /// Called when a new peer was negotiated. pub fn peer_negotiated<T: BlockReader>( &mut self, socket: Socket, height: Height, services: ServiceFlags, preferred: bool, link: Link, tree: &T, )
/// Called when a peer disconnected. pub fn peer_disconnected(&mut self, id: &PeerId) { self.unregister(id); } /// Called when we received a `getheaders` message from a peer. pub fn received_getheaders<T: BlockReader>( &mut self, addr: &PeerId, (locator_hashes, stop_hash): Locators, tree: &T, ) { let max = self.config.max_message_headers; if self.is_syncing() || max == 0 { return; } let headers = tree.locate_headers(&locator_hashes, stop_hash, max); if headers.is_empty() { return; } self.upstream.headers(*addr, headers); } /// Import blocks into our block tree. pub fn import_blocks<T: BlockTree, I: Iterator<Item = BlockHeader>>( &mut self, blocks: I, tree: &mut T, ) -> Result<ImportResult, Error> { match tree.import_blocks(blocks, &self.clock) { Ok(ImportResult::TipChanged(header, tip, height, reverted, connected)) => { let result = ImportResult::TipChanged( header, tip, height, reverted.clone(), connected.clone(), ); for (height, header) in reverted { self.upstream .event(Event::BlockDisconnected { height, header }); } for (height, header) in connected { self.upstream .event(Event::BlockConnected { height, header }); } self.upstream.event(Event::Synced(tip, height)); self.broadcast_tip(&tip, tree); Ok(result) } Ok(result @ ImportResult::TipUnchanged) => Ok(result), Err(err) => Err(err), } } /// Called when we receive headers from a peer. pub fn received_headers<T: BlockTree>( &mut self, from: &PeerId, headers: Vec<BlockHeader>, clock: &impl Clock, tree: &mut T, ) -> Result<ImportResult, store::Error> { let request = self.inflight.remove(from); let headers = if let Some(headers) = NonEmpty::from_vec(headers) { headers } else { return Ok(ImportResult::TipUnchanged); }; let length = headers.len(); if length > MAX_MESSAGE_HEADERS { log::debug!("Received more than maximum headers allowed from {}", from); self.record_misbehavior(from); self.upstream .disconnect(*from, DisconnectReason::PeerMisbehaving("too many headers")); return Ok(ImportResult::TipUnchanged); } // When unsolicited, we don't want to process too many headers in case of a DoS. if length > MAX_UNSOLICITED_HEADERS && request.is_none() { log::debug!("Received {} unsolicited headers from {}", length, from); return Ok(ImportResult::TipUnchanged); } if let Some(peer) = self.peers.get_mut(from) { peer.last_active = Some(clock.local_time()); } else { return Ok(ImportResult::TipUnchanged); } log::debug!("[sync] Received {} block header(s) from {}", length, from); let root = headers.first().block_hash(); let best = headers.last().block_hash(); if tree.contains(&best) { return Ok(ImportResult::TipUnchanged); } match self.import_blocks(headers.into_iter(), tree) { Ok(ImportResult::TipUnchanged) => { // Try to find a common ancestor that leads up to the first header in // the list we received. let locators = (tree.locator_hashes(tree.height()), root); let timeout = self.config.request_timeout; self.request(*from, locators, timeout, OnTimeout::Ignore); Ok(ImportResult::TipUnchanged) } Ok(ImportResult::TipChanged(header, tip, height, reverted, connected)) => { // Update peer height. if let Some(peer) = self.peers.get_mut(from) { if height > peer.height { peer.tip = tip; peer.height = height; } } // Keep track of when we last updated our tip. This is useful to check // whether our tip is stale. self.last_tip_update = Some(clock.local_time()); // If we received less than the maximum number of headers, we must be in sync. // Otherwise, ask for the next batch of headers. if length < MAX_MESSAGE_HEADERS { // If these headers were unsolicited, we may already be ready/synced. // Otherwise, we're finally in sync. self.broadcast_tip(&tip, tree); self.sync(tree); } else { let locators = (vec![tip], BlockHash::all_zeros()); let timeout = self.config.request_timeout; self.request(*from, locators, timeout, OnTimeout::Disconnect); } Ok(ImportResult::TipChanged( header, tip, height, reverted, connected, )) } Err(err) => self .handle_error(from, err) .map(|()| ImportResult::TipUnchanged), } } fn request( &mut self, addr: PeerId, locators: Locators, timeout: LocalDuration, on_timeout: OnTimeout, ) { // Don't request more than once from the same peer. if self.inflight.contains_key(&addr) { return; } if let Some(peer) = self.peers.get_mut(&addr) { debug_assert!(peer.last_asked.as_ref()!= Some(&locators)); peer.last_asked = Some(locators.clone()); let sent_at = self.clock.local_time(); let req = GetHeaders { locators, sent_at, on_timeout, }; self.inflight.insert(addr, req.clone()); self.upstream.get_headers(addr, req.locators); self.upstream.set_timer(timeout); } } /// Called when we received an `inv` message. This will happen if we are out of sync with a /// peer, and blocks are being announced. Otherwise, we expect to receive a `headers` message. pub fn received_inv<T: BlockReader>(&mut self, addr: PeerId, inv: Vec<Inventory>, tree: &T) { // Don't try to fetch headers from `inv` message while syncing. It's not helpful. if self.is_syncing() { return; } // Ignore and disconnect peers misbehaving. if inv.len() > MAX_MESSAGE_INVS { return; } let peer = if let Some(peer) = self.peers.get_mut(&addr) { peer } else { return; }; let mut best_block = None; for i in &inv { if let Inventory::Block(hash) = i { peer.tip = *hash; // "Headers-first is the primary method of announcement on the network. If a node // fell back to sending blocks by inv, it's probably for a re-org. The final block // hash provided should be the highest." if!tree.is_known(hash) { self.upstream.event(Event::BlockDiscovered(addr, *hash)); best_block = Some(hash); } } } if let Some(stop_hash) = best_block { let locators = (tree.locator_hashes(tree.height()), *stop_hash); let timeout = self.config.request_timeout; // Try to find headers leading up to the `inv` entry. self.request(addr, locators, timeout, OnTimeout::Retry(3)); } } /// Called when we received a tick. pub fn received_wake<T: BlockReader>(&mut self, tree: &T) { let local_time = self.clock.local_time(); let timeout = self.config.request_timeout; let timed_out = self .inflight .iter() .filter_map(|(peer, req)| { if local_time - req.sent_at >= timeout { Some((*peer, req.on_timeout, req.clone())) } else { None } }) .collect::<Vec<_>>(); let mut sync = false; for (peer, on_timeout, req) in timed_out { self.inflight.remove(&peer); match on_timeout { OnTimeout::Ignore => { // It's likely that the peer just didn't have the requested header. } OnTimeout::Retry(0) | OnTimeout::Disconnect => { self.upstream .disconnect(peer, DisconnectReason::PeerTimeout("getheaders")); sync = true; } OnTimeout::Retry(n) => { if let Some((addr, _)) = self.peers.sample_with(|a, p| { *a!= peer && self.is_request_candidate(a, p, &req.locators.0) }) { let addr = *addr; self.request(addr, req.locators, timeout, OnTimeout::Retry(n - 1)); } } } } // If some of the requests timed out, force a sync, otherwise just idle. if sync { self.sync(tree); } else { self.idle(tree); } } /// Get the best known height out of all our peers. pub fn best_height(&self) -> Option<Height> { self.peers.iter().map(|(_, p)| p.height).max() } /// Are we currently syncing? pub fn is_syncing(&self) -> bool { !self.inflight.is_empty() } /////////////////////////////////////////////////////////////////////////// fn handle_error(&mut self, from: &PeerId, err: Error) -> Result<(), store::Error> { match err { // If this is an error with the underlying store, we have to propagate // this up, because we can't handle it here. Error::Store(e) => Err(e), // If we got a bad block from the peer, we can handle it here. Error::InvalidBlockPoW | Error::InvalidBlockTarget(_, _) | Error::InvalidBlockHash(_, _) | Error::InvalidBlockHeight(_) | Error::InvalidBlockTime(_, _) => { log::debug!("{}: Received invalid headers: {}", from, err); self.record_misbehavior(from); self.upstream .disconnect(*from, DisconnectReason::PeerMisbehaving("invalid headers")); Ok(()) } // Harmless errors can be ignored. Error::DuplicateBlock(_) | Error::BlockMissing(_) => Ok(()), // TODO: This will be removed. Error::BlockImportAborted(_, _, _) => Ok(()), // These shouldn't happen here. // TODO: Perhaps there's a better way to have this error not show up here. Error::Interrupted | Error::GenesisMismatch => Ok(()), } } fn record_misbehavior(&mut self, peer: &PeerId) { self.upstream.event(Event::PeerMisbehaved(*peer)); } /// Check whether our current tip is stale. /// /// *Nb. This doesn't check whether we've already requested new blocks.* fn stale_tip<T: BlockReader>(&self, tree: &T) -> Option<LocalTime> { let now = self.clock.local_time(); if let Some(last_update) = self.last_tip_update { if last_update < now - LocalDuration::from_secs(self.config.params.pow_target_spacing * 3) { return Some(last_update); } } // If we don't have the time of the last update, it's probably because we // are fresh, or restarted our node. In that case we check the last block time // instead. let (_, tip) = tree.tip(); let time = LocalTime::from_block_time(tip.time); if time <= now - TIP_STALE_DURATION { return Some(time); } None
{ if link.is_outbound() && !services.has(REQUIRED_SERVICES) { return; } if height > self.best_height().unwrap_or_else(|| tree.height()) { self.upstream.event(Event::PeerHeightUpdated { height }); } self.register(socket, height, preferred, link); self.sync(tree); }
identifier_body
syncmgr.rs
, BlockHash), /// Syncing headers. Syncing { /// Current block header height. current: Height, /// Best known block header height. best: Height, }, /// Synced up to the specified hash and height. Synced(BlockHash, Height), /// Potential stale tip detected on the active chain. StaleTip(LocalTime), /// Peer misbehaved. PeerMisbehaved(PeerId), /// Peer height updated. PeerHeightUpdated { /// Best height known. height: Height, }, } impl std::fmt::Display for Event { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Event::PeerMisbehaved(addr) => { write!(fmt, "{}: Peer misbehaved", addr) } Event::PeerHeightUpdated { height } => { write!(fmt, "Peer height updated to {}", height) } Event::Synced(hash, height) => { write!( fmt, "Headers synced up to height {} with hash {}", height, hash ) } Event::Syncing { current, best } => write!(fmt, "Syncing headers {}/{}", current, best), Event::BlockConnected { height, header } => { write!( fmt, "Block {} connected at height {}", header.block_hash(), height ) } Event::BlockDisconnected { height, header } => { write!( fmt, "Block {} disconnected at height {}", header.block_hash(), height ) } Event::BlockDiscovered(from, hash) => { write!(fmt, "{}: Discovered new block: {}", from, &hash) } Event::StaleTip(last_update) => { write!( fmt, "Potential stale tip detected (last update was {})", last_update ) } } } } /// A `getheaders` request sent to a peer. #[derive(Clone, Debug, PartialEq, Eq)] struct GetHeaders { /// Locators hashes. locators: Locators, /// Time at which the request was sent. sent_at: LocalTime, /// What to do if this request times out. on_timeout: OnTimeout, } impl<U: SetTimer + Disconnect + Wire<Event>, C: Clock> SyncManager<U, C> { /// Create a new sync manager. pub fn new(config: Config, rng: fastrand::Rng, upstream: U, clock: C) -> Self { let peers = AddressBook::new(rng.clone()); let last_tip_update = None; let last_peer_sample = None; let last_idle = None; let inflight = HashMap::with_hasher(rng.into()); Self { peers, config, last_tip_update, last_peer_sample, last_idle, inflight, upstream, clock, } } /// Initialize the sync manager. Should only be called once. pub fn initialize<T: BlockReader>(&mut self, tree: &T) { // TODO: `tip` should return the height. let (hash, _) = tree.tip(); let height = tree.height(); self.idle(tree); self.upstream.event(Event::Synced(hash, height)); } /// Called periodically. pub fn idle<T: BlockReader>(&mut self, tree: &T) { let now = self.clock.local_time(); // Nb. The idle timeout is very long: as long as the block interval. // This shouldn't be a problem, as the sync manager can make progress without it. if now - self.last_idle.unwrap_or_default() >= IDLE_TIMEOUT { if!self.sync(tree) { self.sample_peers(tree); } self.last_idle = Some(now); self.upstream.set_timer(IDLE_TIMEOUT); } } /// Called when a new peer was negotiated. pub fn peer_negotiated<T: BlockReader>( &mut self, socket: Socket, height: Height, services: ServiceFlags, preferred: bool, link: Link, tree: &T, ) { if link.is_outbound() &&!services.has(REQUIRED_SERVICES) { return; } if height > self.best_height().unwrap_or_else(|| tree.height()) { self.upstream.event(Event::PeerHeightUpdated { height }); } self.register(socket, height, preferred, link); self.sync(tree); } /// Called when a peer disconnected. pub fn peer_disconnected(&mut self, id: &PeerId) { self.unregister(id); } /// Called when we received a `getheaders` message from a peer. pub fn received_getheaders<T: BlockReader>( &mut self, addr: &PeerId, (locator_hashes, stop_hash): Locators, tree: &T, ) { let max = self.config.max_message_headers; if self.is_syncing() || max == 0 { return; } let headers = tree.locate_headers(&locator_hashes, stop_hash, max); if headers.is_empty() { return; } self.upstream.headers(*addr, headers); } /// Import blocks into our block tree. pub fn import_blocks<T: BlockTree, I: Iterator<Item = BlockHeader>>( &mut self, blocks: I, tree: &mut T, ) -> Result<ImportResult, Error> { match tree.import_blocks(blocks, &self.clock) { Ok(ImportResult::TipChanged(header, tip, height, reverted, connected)) => { let result = ImportResult::TipChanged( header, tip, height, reverted.clone(), connected.clone(), ); for (height, header) in reverted { self.upstream .event(Event::BlockDisconnected { height, header }); } for (height, header) in connected { self.upstream .event(Event::BlockConnected { height, header }); } self.upstream.event(Event::Synced(tip, height)); self.broadcast_tip(&tip, tree); Ok(result) } Ok(result @ ImportResult::TipUnchanged) => Ok(result), Err(err) => Err(err), } } /// Called when we receive headers from a peer. pub fn received_headers<T: BlockTree>( &mut self, from: &PeerId, headers: Vec<BlockHeader>, clock: &impl Clock, tree: &mut T, ) -> Result<ImportResult, store::Error> { let request = self.inflight.remove(from); let headers = if let Some(headers) = NonEmpty::from_vec(headers) { headers } else { return Ok(ImportResult::TipUnchanged); }; let length = headers.len(); if length > MAX_MESSAGE_HEADERS { log::debug!("Received more than maximum headers allowed from {}", from); self.record_misbehavior(from); self.upstream .disconnect(*from, DisconnectReason::PeerMisbehaving("too many headers")); return Ok(ImportResult::TipUnchanged); } // When unsolicited, we don't want to process too many headers in case of a DoS. if length > MAX_UNSOLICITED_HEADERS && request.is_none() { log::debug!("Received {} unsolicited headers from {}", length, from); return Ok(ImportResult::TipUnchanged); } if let Some(peer) = self.peers.get_mut(from) { peer.last_active = Some(clock.local_time()); } else { return Ok(ImportResult::TipUnchanged); } log::debug!("[sync] Received {} block header(s) from {}", length, from); let root = headers.first().block_hash(); let best = headers.last().block_hash(); if tree.contains(&best) { return Ok(ImportResult::TipUnchanged); } match self.import_blocks(headers.into_iter(), tree) { Ok(ImportResult::TipUnchanged) => { // Try to find a common ancestor that leads up to the first header in // the list we received. let locators = (tree.locator_hashes(tree.height()), root); let timeout = self.config.request_timeout; self.request(*from, locators, timeout, OnTimeout::Ignore); Ok(ImportResult::TipUnchanged) } Ok(ImportResult::TipChanged(header, tip, height, reverted, connected)) => { // Update peer height. if let Some(peer) = self.peers.get_mut(from) { if height > peer.height { peer.tip = tip; peer.height = height; } } // Keep track of when we last updated our tip. This is useful to check // whether our tip is stale. self.last_tip_update = Some(clock.local_time()); // If we received less than the maximum number of headers, we must be in sync. // Otherwise, ask for the next batch of headers. if length < MAX_MESSAGE_HEADERS { // If these headers were unsolicited, we may already be ready/synced. // Otherwise, we're finally in sync. self.broadcast_tip(&tip, tree); self.sync(tree); } else { let locators = (vec![tip], BlockHash::all_zeros()); let timeout = self.config.request_timeout; self.request(*from, locators, timeout, OnTimeout::Disconnect); } Ok(ImportResult::TipChanged( header, tip, height, reverted, connected, )) } Err(err) => self .handle_error(from, err) .map(|()| ImportResult::TipUnchanged), } } fn request( &mut self, addr: PeerId, locators: Locators, timeout: LocalDuration, on_timeout: OnTimeout, ) { // Don't request more than once from the same peer. if self.inflight.contains_key(&addr) { return; } if let Some(peer) = self.peers.get_mut(&addr) { debug_assert!(peer.last_asked.as_ref()!= Some(&locators)); peer.last_asked = Some(locators.clone()); let sent_at = self.clock.local_time(); let req = GetHeaders { locators, sent_at, on_timeout, }; self.inflight.insert(addr, req.clone()); self.upstream.get_headers(addr, req.locators); self.upstream.set_timer(timeout); } } /// Called when we received an `inv` message. This will happen if we are out of sync with a /// peer, and blocks are being announced. Otherwise, we expect to receive a `headers` message. pub fn received_inv<T: BlockReader>(&mut self, addr: PeerId, inv: Vec<Inventory>, tree: &T) { // Don't try to fetch headers from `inv` message while syncing. It's not helpful. if self.is_syncing() { return; } // Ignore and disconnect peers misbehaving. if inv.len() > MAX_MESSAGE_INVS { return; } let peer = if let Some(peer) = self.peers.get_mut(&addr) { peer } else { return; }; let mut best_block = None; for i in &inv { if let Inventory::Block(hash) = i { peer.tip = *hash; // "Headers-first is the primary method of announcement on the network. If a node // fell back to sending blocks by inv, it's probably for a re-org. The final block // hash provided should be the highest." if!tree.is_known(hash) { self.upstream.event(Event::BlockDiscovered(addr, *hash)); best_block = Some(hash); } } } if let Some(stop_hash) = best_block { let locators = (tree.locator_hashes(tree.height()), *stop_hash); let timeout = self.config.request_timeout; // Try to find headers leading up to the `inv` entry. self.request(addr, locators, timeout, OnTimeout::Retry(3)); } } /// Called when we received a tick. pub fn received_wake<T: BlockReader>(&mut self, tree: &T) { let local_time = self.clock.local_time(); let timeout = self.config.request_timeout; let timed_out = self .inflight .iter() .filter_map(|(peer, req)| { if local_time - req.sent_at >= timeout { Some((*peer, req.on_timeout, req.clone())) } else { None } }) .collect::<Vec<_>>(); let mut sync = false; for (peer, on_timeout, req) in timed_out { self.inflight.remove(&peer); match on_timeout { OnTimeout::Ignore => { // It's likely that the peer just didn't have the requested header. } OnTimeout::Retry(0) | OnTimeout::Disconnect => { self.upstream .disconnect(peer, DisconnectReason::PeerTimeout("getheaders")); sync = true; } OnTimeout::Retry(n) => { if let Some((addr, _)) = self.peers.sample_with(|a, p| { *a!= peer && self.is_request_candidate(a, p, &req.locators.0) }) { let addr = *addr; self.request(addr, req.locators, timeout, OnTimeout::Retry(n - 1)); } } } } // If some of the requests timed out, force a sync, otherwise just idle. if sync { self.sync(tree); } else { self.idle(tree); } } /// Get the best known height out of all our peers. pub fn best_height(&self) -> Option<Height> { self.peers.iter().map(|(_, p)| p.height).max() } /// Are we currently syncing? pub fn is_syncing(&self) -> bool { !self.inflight.is_empty() } /////////////////////////////////////////////////////////////////////////// fn handle_error(&mut self, from: &PeerId, err: Error) -> Result<(), store::Error> { match err { // If this is an error with the underlying store, we have to propagate // this up, because we can't handle it here. Error::Store(e) => Err(e), // If we got a bad block from the peer, we can handle it here. Error::InvalidBlockPoW | Error::InvalidBlockTarget(_, _) | Error::InvalidBlockHash(_, _) | Error::InvalidBlockHeight(_) | Error::InvalidBlockTime(_, _) => { log::debug!("{}: Received invalid headers: {}", from, err); self.record_misbehavior(from); self.upstream .disconnect(*from, DisconnectReason::PeerMisbehaving("invalid headers")); Ok(()) } // Harmless errors can be ignored. Error::DuplicateBlock(_) | Error::BlockMissing(_) => Ok(()), // TODO: This will be removed. Error::BlockImportAborted(_, _, _) => Ok(()), // These shouldn't happen here. // TODO: Perhaps there's a better way to have this error not show up here. Error::Interrupted | Error::GenesisMismatch => Ok(()), } } fn record_misbehavior(&mut self, peer: &PeerId) { self.upstream.event(Event::PeerMisbehaved(*peer)); } /// Check whether our current tip is stale. /// /// *Nb. This doesn't check whether we've already requested new blocks.* fn stale_tip<T: BlockReader>(&self, tree: &T) -> Option<LocalTime> { let now = self.clock.local_time(); if let Some(last_update) = self.last_tip_update { if last_update < now - LocalDuration::from_secs(self.config.params.pow_target_spacing * 3) { return Some(last_update); } } // If we don't have the time of the last update, it's probably because we // are fresh, or restarted our node. In that case we check the last block time // instead. let (_, tip) = tree.tip(); let time = LocalTime::from_block_time(tip.time); if time <= now - TIP_STALE_DURATION
None
{ return Some(time); }
conditional_block
smt.rs
use std::sync::Arc; use anyhow::Result; use criterion::{criterion_group, BenchmarkId, Criterion, Throughput}; use gw_builtin_binaries::{file_checksum, Resource}; use gw_common::{ blake2b::new_blake2b, builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID}, registry_address::RegistryAddress, state::State, }; use gw_config::{BackendConfig, BackendForkConfig, GenesisConfig, StoreConfig}; use gw_generator::{ account_lock_manage::{always_success::AlwaysSuccess, AccountLockManage}, backend_manage::BackendManage, genesis::build_genesis_from_store, traits::StateExt, Generator, }; use gw_store::{ mem_pool_state::MemPoolState, schema::COLUMNS, state::{ history::history_state::{HistoryState, RWConfig}, state_db::StateDB, traits::JournalDB, MemStateDB, }, traits::chain_store::ChainStore, Store, }; use gw_traits::{ChainView, CodeStore}; use gw_types::{ bytes::Bytes, core::{AllowedEoaType, ScriptHashType, Status}, h256::*, packed::{ AccountMerkleState, AllowedTypeHash, BlockInfo, BlockMerkleState, Fee, GlobalState, L2Block, RawL2Block, RawL2Transaction, RollupConfig, SUDTArgs, SUDTTransfer, Script, SubmitTransactions, }, prelude::*, U256, }; use gw_utils::RollupContext; use pprof::criterion::{Output, PProfProfiler}; // meta contract const META_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/meta-contract-generator"; const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32]; // sudt contract const SUDT_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/sudt-generator"; const SUDT_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [2u8; 32]; // always success lock const ALWAYS_SUCCESS_LOCK_HASH: [u8; 32] = [3u8; 32]; // rollup type hash const ROLLUP_TYPE_HASH: [u8; 32] = [4u8; 32]; const CKB_BALANCE: u128 = 100_000_000; criterion_group! { name = smt; config = Criterion::default() .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); targets = bench_ckb_transfer } pub fn
(c: &mut Criterion) { let config = StoreConfig { path: "./smt_data/db".parse().unwrap(), options_file: Some("./smt_data/db.toml".parse().unwrap()), cache_size: Some(1073741824), }; let store = Store::open(&config, COLUMNS).unwrap(); let ee = BenchExecutionEnvironment::new_with_accounts(store, 7000); let mut group = c.benchmark_group("ckb_transfer"); for txs in (500..=5000).step_by(500) { group.sample_size(10); group.throughput(Throughput::Elements(txs)); group.bench_with_input(BenchmarkId::from_parameter(txs), &txs, |b, txs| { b.iter(|| { ee.accounts_transfer(7000, *txs as usize); }); }); } group.finish(); } #[allow(dead_code)] struct Account { id: u32, } impl Account { fn build_script(n: u32) -> (Script, RegistryAddress) { let mut addr = [0u8; 20]; addr[..4].copy_from_slice(&n.to_le_bytes()); let mut args = vec![42u8; 32]; args.extend(&addr); let script = Script::new_builder() .code_hash(ALWAYS_SUCCESS_LOCK_HASH.pack()) .hash_type(ScriptHashType::Type.into()) .args(args.pack()) .build(); let addr = RegistryAddress::new(ETH_REGISTRY_ACCOUNT_ID, addr.to_vec()); (script, addr) } } struct BenchChain; impl ChainView for BenchChain { fn get_block_hash_by_number(&self, _: u64) -> Result<Option<H256>> { unreachable!("bench chain store") } } struct BenchExecutionEnvironment { generator: Generator, chain: BenchChain, mem_pool_state: MemPoolState, } impl BenchExecutionEnvironment { fn new_with_accounts(store: Store, accounts: u32) -> Self { let genesis_config = GenesisConfig { meta_contract_validator_type_hash: META_VALIDATOR_SCRIPT_TYPE_HASH.into(), rollup_type_hash: ROLLUP_TYPE_HASH.into(), rollup_config: RollupConfig::new_builder() .l2_sudt_validator_script_type_hash(SUDT_VALIDATOR_SCRIPT_TYPE_HASH.pack()) .allowed_eoa_type_hashes( vec![AllowedTypeHash::new_builder() .hash(ALWAYS_SUCCESS_LOCK_HASH.pack()) .type_(AllowedEoaType::Eth.into()) .build()] .pack(), ) .build() .into(), ..Default::default() }; let rollup_context = RollupContext { rollup_config: genesis_config.rollup_config.clone().into(), rollup_script_hash: ROLLUP_TYPE_HASH, ..Default::default() }; let backend_manage = { let configs = vec![ BackendConfig { generator: Resource::file_system(META_GENERATOR_PATH.into()), generator_checksum: file_checksum(&META_GENERATOR_PATH).unwrap().into(), validator_script_type_hash: META_VALIDATOR_SCRIPT_TYPE_HASH.into(), backend_type: gw_config::BackendType::Meta, }, BackendConfig { generator: Resource::file_system(SUDT_GENERATOR_PATH.into()), generator_checksum: file_checksum(&SUDT_GENERATOR_PATH).unwrap().into(), validator_script_type_hash: SUDT_VALIDATOR_SCRIPT_TYPE_HASH.into(), backend_type: gw_config::BackendType::Sudt, }, ]; BackendManage::from_config(vec![BackendForkConfig { sudt_proxy: Default::default(), fork_height: 0, backends: configs, }]) .expect("bench backend") }; let account_lock_manage = { let mut manage = AccountLockManage::default(); manage.register_lock_algorithm(ALWAYS_SUCCESS_LOCK_HASH, Arc::new(AlwaysSuccess)); manage }; let generator = Generator::new( backend_manage, account_lock_manage, rollup_context, Default::default(), ); Self::init_genesis(&store, &genesis_config, accounts); let mem_pool_state = MemPoolState::new( MemStateDB::from_store(store.get_snapshot()).expect("mem state db"), true, ); BenchExecutionEnvironment { generator, chain: BenchChain, mem_pool_state, } } fn accounts_transfer(&self, accounts: u32, count: usize) { let mut state = self.mem_pool_state.load_state_db(); let (block_producer_script, block_producer) = Account::build_script(0); let block_info = BlockInfo::new_builder() .block_producer(Bytes::from(block_producer.to_bytes()).pack()) .number(1.pack()) .timestamp(1.pack()) .build(); let block_producer_balance = state .get_sudt_balance(CKB_SUDT_ACCOUNT_ID, &block_producer) .unwrap(); let addrs: Vec<_> = (0..=accounts) .map(Account::build_script) .map(|(_s, addr)| addr) .collect(); let address_offset = state .get_account_id_by_script_hash(&block_producer_script.hash()) .unwrap() .unwrap(); // start from block producer let start_account_id = address_offset + 1; let end_account_id = address_offset + accounts; // Loop transfer from id to id + 1, until we reach target count let mut from_id = start_account_id; let mut transfer_count = count; while transfer_count > 0 { let to_address = { let mut to_id = from_id + 1; if to_id > end_account_id { to_id = start_account_id; } addrs.get((to_id - address_offset) as usize).unwrap() }; let args = SUDTArgs::new_builder() .set( SUDTTransfer::new_builder() .to_address(Bytes::from(to_address.to_bytes()).pack()) .amount(U256::one().pack()) .fee( Fee::new_builder() .registry_id(ETH_REGISTRY_ACCOUNT_ID.pack()) .amount(1u128.pack()) .build(), ) .build(), ) .build(); let raw_tx = RawL2Transaction::new_builder() .from_id(from_id.pack()) .to_id(1u32.pack()) .args(args.as_bytes().pack()) .build(); self.generator .execute_transaction( &self.chain, &mut state, &block_info, &raw_tx, Some(u64::MAX), None, ) .unwrap(); state.finalise().unwrap(); from_id += 1; if from_id > end_account_id { from_id = start_account_id; } transfer_count -= 1; } self.mem_pool_state.store_state_db(state); let state = self.mem_pool_state.load_state_db(); let post_block_producer_balance = state .get_sudt_balance(CKB_SUDT_ACCOUNT_ID, &block_producer) .unwrap(); assert_eq!( post_block_producer_balance, block_producer_balance + count as u128 ); } fn generate_accounts( state: &mut (impl State + StateExt + CodeStore), accounts: u32, ) -> Vec<Account> { let build_account = |idx: u32| -> Account { let (account_script, addr) = Account::build_script(idx); let account_script_hash: H256 = account_script.hash(); let account_id = state.create_account(account_script_hash).unwrap(); state.insert_script(account_script_hash, account_script); state .mapping_registry_address_to_script_hash(addr.clone(), account_script_hash) .unwrap(); state .mint_sudt(CKB_SUDT_ACCOUNT_ID, &addr, CKB_BALANCE.into()) .unwrap(); Account { id: account_id } }; (0..accounts).map(build_account).collect() } fn init_genesis(store: &Store, config: &GenesisConfig, accounts: u32) { if store.has_genesis().unwrap() { let chain_id = store.get_chain_id().unwrap(); if chain_id == ROLLUP_TYPE_HASH { return; } else { panic!("store genesis already initialized"); } } let mut db = store.begin_transaction(); db.setup_chain_id(ROLLUP_TYPE_HASH).unwrap(); let (mut db, genesis_state) = build_genesis_from_store(db, config, Default::default()).unwrap(); let smt = db .state_smt_with_merkle_state(genesis_state.genesis.raw().post_account()) .unwrap(); let account_count = genesis_state.genesis.raw().post_account().count().unpack(); let mut state = { let history_state = HistoryState::new(smt, account_count, RWConfig::attach_block(0)); StateDB::new(history_state) }; Self::generate_accounts(&mut state, accounts + 1); // Plus block producer state.finalise().unwrap(); let (genesis, global_state) = { let prev_state_checkpoint: [u8; 32] = state.calculate_state_checkpoint().unwrap(); let submit_txs = SubmitTransactions::new_builder() .prev_state_checkpoint(prev_state_checkpoint.pack()) .build(); // calculate post state let post_account = { let root = state.calculate_root().unwrap(); let count = state.get_account_count().unwrap(); AccountMerkleState::new_builder() .merkle_root(root.pack()) .count(count.pack()) .build() }; let raw_genesis = RawL2Block::new_builder() .number(0u64.pack()) .parent_block_hash([0u8; 32].pack()) .timestamp(1.pack()) .post_account(post_account.clone()) .submit_transactions(submit_txs) .build(); // generate block proof let genesis_hash = raw_genesis.hash(); let (block_root, block_proof) = { let block_key = RawL2Block::compute_smt_key(0); let mut smt = db.block_smt().unwrap(); smt.update(block_key.into(), genesis_hash.into()).unwrap(); let block_proof = smt .merkle_proof(vec![block_key.into()]) .unwrap() .compile(vec![block_key.into()]) .unwrap(); let block_root = *smt.root(); (block_root, block_proof) }; // build genesis let genesis = L2Block::new_builder() .raw(raw_genesis) .block_proof(block_proof.0.pack()) .build(); let global_state = { let post_block = BlockMerkleState::new_builder() .merkle_root({ let root: [u8; 32] = block_root.into(); root.pack() }) .count(1u64.pack()) .build(); let rollup_config_hash = { let mut hasher = new_blake2b(); hasher.update( Into::<RollupConfig>::into(config.rollup_config.clone()).as_slice(), ); let mut hash = [0u8; 32]; hasher.finalize(&mut hash); hash }; GlobalState::new_builder() .account(post_account) .block(post_block) .status((Status::Running as u8).into()) .rollup_config_hash(rollup_config_hash.pack()) .tip_block_hash(genesis.hash().pack()) .build() }; db.set_block_smt_root(global_state.block().merkle_root().unpack()) .unwrap(); (genesis, global_state) }; let prev_txs_state = genesis.as_reader().raw().post_account().to_entity(); db.insert_block( genesis.clone(), global_state, prev_txs_state, Vec::new(), Default::default(), Vec::new(), ) .unwrap(); db.attach_block(genesis).unwrap(); db.commit().unwrap(); } }
bench_ckb_transfer
identifier_name
smt.rs
use std::sync::Arc; use anyhow::Result; use criterion::{criterion_group, BenchmarkId, Criterion, Throughput}; use gw_builtin_binaries::{file_checksum, Resource}; use gw_common::{ blake2b::new_blake2b, builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID}, registry_address::RegistryAddress, state::State, }; use gw_config::{BackendConfig, BackendForkConfig, GenesisConfig, StoreConfig}; use gw_generator::{ account_lock_manage::{always_success::AlwaysSuccess, AccountLockManage}, backend_manage::BackendManage, genesis::build_genesis_from_store, traits::StateExt, Generator, }; use gw_store::{ mem_pool_state::MemPoolState, schema::COLUMNS, state::{ history::history_state::{HistoryState, RWConfig}, state_db::StateDB, traits::JournalDB, MemStateDB, }, traits::chain_store::ChainStore, Store, }; use gw_traits::{ChainView, CodeStore}; use gw_types::{ bytes::Bytes, core::{AllowedEoaType, ScriptHashType, Status}, h256::*, packed::{ AccountMerkleState, AllowedTypeHash, BlockInfo, BlockMerkleState, Fee, GlobalState, L2Block, RawL2Block, RawL2Transaction, RollupConfig, SUDTArgs, SUDTTransfer, Script, SubmitTransactions, }, prelude::*, U256, }; use gw_utils::RollupContext; use pprof::criterion::{Output, PProfProfiler};
// meta contract const META_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/meta-contract-generator"; const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32]; // sudt contract const SUDT_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/sudt-generator"; const SUDT_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [2u8; 32]; // always success lock const ALWAYS_SUCCESS_LOCK_HASH: [u8; 32] = [3u8; 32]; // rollup type hash const ROLLUP_TYPE_HASH: [u8; 32] = [4u8; 32]; const CKB_BALANCE: u128 = 100_000_000; criterion_group! { name = smt; config = Criterion::default() .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); targets = bench_ckb_transfer } pub fn bench_ckb_transfer(c: &mut Criterion) { let config = StoreConfig { path: "./smt_data/db".parse().unwrap(), options_file: Some("./smt_data/db.toml".parse().unwrap()), cache_size: Some(1073741824), }; let store = Store::open(&config, COLUMNS).unwrap(); let ee = BenchExecutionEnvironment::new_with_accounts(store, 7000); let mut group = c.benchmark_group("ckb_transfer"); for txs in (500..=5000).step_by(500) { group.sample_size(10); group.throughput(Throughput::Elements(txs)); group.bench_with_input(BenchmarkId::from_parameter(txs), &txs, |b, txs| { b.iter(|| { ee.accounts_transfer(7000, *txs as usize); }); }); } group.finish(); } #[allow(dead_code)] struct Account { id: u32, } impl Account { fn build_script(n: u32) -> (Script, RegistryAddress) { let mut addr = [0u8; 20]; addr[..4].copy_from_slice(&n.to_le_bytes()); let mut args = vec![42u8; 32]; args.extend(&addr); let script = Script::new_builder() .code_hash(ALWAYS_SUCCESS_LOCK_HASH.pack()) .hash_type(ScriptHashType::Type.into()) .args(args.pack()) .build(); let addr = RegistryAddress::new(ETH_REGISTRY_ACCOUNT_ID, addr.to_vec()); (script, addr) } } struct BenchChain; impl ChainView for BenchChain { fn get_block_hash_by_number(&self, _: u64) -> Result<Option<H256>> { unreachable!("bench chain store") } } struct BenchExecutionEnvironment { generator: Generator, chain: BenchChain, mem_pool_state: MemPoolState, } impl BenchExecutionEnvironment { fn new_with_accounts(store: Store, accounts: u32) -> Self { let genesis_config = GenesisConfig { meta_contract_validator_type_hash: META_VALIDATOR_SCRIPT_TYPE_HASH.into(), rollup_type_hash: ROLLUP_TYPE_HASH.into(), rollup_config: RollupConfig::new_builder() .l2_sudt_validator_script_type_hash(SUDT_VALIDATOR_SCRIPT_TYPE_HASH.pack()) .allowed_eoa_type_hashes( vec![AllowedTypeHash::new_builder() .hash(ALWAYS_SUCCESS_LOCK_HASH.pack()) .type_(AllowedEoaType::Eth.into()) .build()] .pack(), ) .build() .into(), ..Default::default() }; let rollup_context = RollupContext { rollup_config: genesis_config.rollup_config.clone().into(), rollup_script_hash: ROLLUP_TYPE_HASH, ..Default::default() }; let backend_manage = { let configs = vec![ BackendConfig { generator: Resource::file_system(META_GENERATOR_PATH.into()), generator_checksum: file_checksum(&META_GENERATOR_PATH).unwrap().into(), validator_script_type_hash: META_VALIDATOR_SCRIPT_TYPE_HASH.into(), backend_type: gw_config::BackendType::Meta, }, BackendConfig { generator: Resource::file_system(SUDT_GENERATOR_PATH.into()), generator_checksum: file_checksum(&SUDT_GENERATOR_PATH).unwrap().into(), validator_script_type_hash: SUDT_VALIDATOR_SCRIPT_TYPE_HASH.into(), backend_type: gw_config::BackendType::Sudt, }, ]; BackendManage::from_config(vec![BackendForkConfig { sudt_proxy: Default::default(), fork_height: 0, backends: configs, }]) .expect("bench backend") }; let account_lock_manage = { let mut manage = AccountLockManage::default(); manage.register_lock_algorithm(ALWAYS_SUCCESS_LOCK_HASH, Arc::new(AlwaysSuccess)); manage }; let generator = Generator::new( backend_manage, account_lock_manage, rollup_context, Default::default(), ); Self::init_genesis(&store, &genesis_config, accounts); let mem_pool_state = MemPoolState::new( MemStateDB::from_store(store.get_snapshot()).expect("mem state db"), true, ); BenchExecutionEnvironment { generator, chain: BenchChain, mem_pool_state, } } fn accounts_transfer(&self, accounts: u32, count: usize) { let mut state = self.mem_pool_state.load_state_db(); let (block_producer_script, block_producer) = Account::build_script(0); let block_info = BlockInfo::new_builder() .block_producer(Bytes::from(block_producer.to_bytes()).pack()) .number(1.pack()) .timestamp(1.pack()) .build(); let block_producer_balance = state .get_sudt_balance(CKB_SUDT_ACCOUNT_ID, &block_producer) .unwrap(); let addrs: Vec<_> = (0..=accounts) .map(Account::build_script) .map(|(_s, addr)| addr) .collect(); let address_offset = state .get_account_id_by_script_hash(&block_producer_script.hash()) .unwrap() .unwrap(); // start from block producer let start_account_id = address_offset + 1; let end_account_id = address_offset + accounts; // Loop transfer from id to id + 1, until we reach target count let mut from_id = start_account_id; let mut transfer_count = count; while transfer_count > 0 { let to_address = { let mut to_id = from_id + 1; if to_id > end_account_id { to_id = start_account_id; } addrs.get((to_id - address_offset) as usize).unwrap() }; let args = SUDTArgs::new_builder() .set( SUDTTransfer::new_builder() .to_address(Bytes::from(to_address.to_bytes()).pack()) .amount(U256::one().pack()) .fee( Fee::new_builder() .registry_id(ETH_REGISTRY_ACCOUNT_ID.pack()) .amount(1u128.pack()) .build(), ) .build(), ) .build(); let raw_tx = RawL2Transaction::new_builder() .from_id(from_id.pack()) .to_id(1u32.pack()) .args(args.as_bytes().pack()) .build(); self.generator .execute_transaction( &self.chain, &mut state, &block_info, &raw_tx, Some(u64::MAX), None, ) .unwrap(); state.finalise().unwrap(); from_id += 1; if from_id > end_account_id { from_id = start_account_id; } transfer_count -= 1; } self.mem_pool_state.store_state_db(state); let state = self.mem_pool_state.load_state_db(); let post_block_producer_balance = state .get_sudt_balance(CKB_SUDT_ACCOUNT_ID, &block_producer) .unwrap(); assert_eq!( post_block_producer_balance, block_producer_balance + count as u128 ); } fn generate_accounts( state: &mut (impl State + StateExt + CodeStore), accounts: u32, ) -> Vec<Account> { let build_account = |idx: u32| -> Account { let (account_script, addr) = Account::build_script(idx); let account_script_hash: H256 = account_script.hash(); let account_id = state.create_account(account_script_hash).unwrap(); state.insert_script(account_script_hash, account_script); state .mapping_registry_address_to_script_hash(addr.clone(), account_script_hash) .unwrap(); state .mint_sudt(CKB_SUDT_ACCOUNT_ID, &addr, CKB_BALANCE.into()) .unwrap(); Account { id: account_id } }; (0..accounts).map(build_account).collect() } fn init_genesis(store: &Store, config: &GenesisConfig, accounts: u32) { if store.has_genesis().unwrap() { let chain_id = store.get_chain_id().unwrap(); if chain_id == ROLLUP_TYPE_HASH { return; } else { panic!("store genesis already initialized"); } } let mut db = store.begin_transaction(); db.setup_chain_id(ROLLUP_TYPE_HASH).unwrap(); let (mut db, genesis_state) = build_genesis_from_store(db, config, Default::default()).unwrap(); let smt = db .state_smt_with_merkle_state(genesis_state.genesis.raw().post_account()) .unwrap(); let account_count = genesis_state.genesis.raw().post_account().count().unpack(); let mut state = { let history_state = HistoryState::new(smt, account_count, RWConfig::attach_block(0)); StateDB::new(history_state) }; Self::generate_accounts(&mut state, accounts + 1); // Plus block producer state.finalise().unwrap(); let (genesis, global_state) = { let prev_state_checkpoint: [u8; 32] = state.calculate_state_checkpoint().unwrap(); let submit_txs = SubmitTransactions::new_builder() .prev_state_checkpoint(prev_state_checkpoint.pack()) .build(); // calculate post state let post_account = { let root = state.calculate_root().unwrap(); let count = state.get_account_count().unwrap(); AccountMerkleState::new_builder() .merkle_root(root.pack()) .count(count.pack()) .build() }; let raw_genesis = RawL2Block::new_builder() .number(0u64.pack()) .parent_block_hash([0u8; 32].pack()) .timestamp(1.pack()) .post_account(post_account.clone()) .submit_transactions(submit_txs) .build(); // generate block proof let genesis_hash = raw_genesis.hash(); let (block_root, block_proof) = { let block_key = RawL2Block::compute_smt_key(0); let mut smt = db.block_smt().unwrap(); smt.update(block_key.into(), genesis_hash.into()).unwrap(); let block_proof = smt .merkle_proof(vec![block_key.into()]) .unwrap() .compile(vec![block_key.into()]) .unwrap(); let block_root = *smt.root(); (block_root, block_proof) }; // build genesis let genesis = L2Block::new_builder() .raw(raw_genesis) .block_proof(block_proof.0.pack()) .build(); let global_state = { let post_block = BlockMerkleState::new_builder() .merkle_root({ let root: [u8; 32] = block_root.into(); root.pack() }) .count(1u64.pack()) .build(); let rollup_config_hash = { let mut hasher = new_blake2b(); hasher.update( Into::<RollupConfig>::into(config.rollup_config.clone()).as_slice(), ); let mut hash = [0u8; 32]; hasher.finalize(&mut hash); hash }; GlobalState::new_builder() .account(post_account) .block(post_block) .status((Status::Running as u8).into()) .rollup_config_hash(rollup_config_hash.pack()) .tip_block_hash(genesis.hash().pack()) .build() }; db.set_block_smt_root(global_state.block().merkle_root().unpack()) .unwrap(); (genesis, global_state) }; let prev_txs_state = genesis.as_reader().raw().post_account().to_entity(); db.insert_block( genesis.clone(), global_state, prev_txs_state, Vec::new(), Default::default(), Vec::new(), ) .unwrap(); db.attach_block(genesis).unwrap(); db.commit().unwrap(); } }
random_line_split
smt.rs
use std::sync::Arc; use anyhow::Result; use criterion::{criterion_group, BenchmarkId, Criterion, Throughput}; use gw_builtin_binaries::{file_checksum, Resource}; use gw_common::{ blake2b::new_blake2b, builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID}, registry_address::RegistryAddress, state::State, }; use gw_config::{BackendConfig, BackendForkConfig, GenesisConfig, StoreConfig}; use gw_generator::{ account_lock_manage::{always_success::AlwaysSuccess, AccountLockManage}, backend_manage::BackendManage, genesis::build_genesis_from_store, traits::StateExt, Generator, }; use gw_store::{ mem_pool_state::MemPoolState, schema::COLUMNS, state::{ history::history_state::{HistoryState, RWConfig}, state_db::StateDB, traits::JournalDB, MemStateDB, }, traits::chain_store::ChainStore, Store, }; use gw_traits::{ChainView, CodeStore}; use gw_types::{ bytes::Bytes, core::{AllowedEoaType, ScriptHashType, Status}, h256::*, packed::{ AccountMerkleState, AllowedTypeHash, BlockInfo, BlockMerkleState, Fee, GlobalState, L2Block, RawL2Block, RawL2Transaction, RollupConfig, SUDTArgs, SUDTTransfer, Script, SubmitTransactions, }, prelude::*, U256, }; use gw_utils::RollupContext; use pprof::criterion::{Output, PProfProfiler}; // meta contract const META_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/meta-contract-generator"; const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32]; // sudt contract const SUDT_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/sudt-generator"; const SUDT_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [2u8; 32]; // always success lock const ALWAYS_SUCCESS_LOCK_HASH: [u8; 32] = [3u8; 32]; // rollup type hash const ROLLUP_TYPE_HASH: [u8; 32] = [4u8; 32]; const CKB_BALANCE: u128 = 100_000_000; criterion_group! { name = smt; config = Criterion::default() .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); targets = bench_ckb_transfer } pub fn bench_ckb_transfer(c: &mut Criterion) { let config = StoreConfig { path: "./smt_data/db".parse().unwrap(), options_file: Some("./smt_data/db.toml".parse().unwrap()), cache_size: Some(1073741824), }; let store = Store::open(&config, COLUMNS).unwrap(); let ee = BenchExecutionEnvironment::new_with_accounts(store, 7000); let mut group = c.benchmark_group("ckb_transfer"); for txs in (500..=5000).step_by(500) { group.sample_size(10); group.throughput(Throughput::Elements(txs)); group.bench_with_input(BenchmarkId::from_parameter(txs), &txs, |b, txs| { b.iter(|| { ee.accounts_transfer(7000, *txs as usize); }); }); } group.finish(); } #[allow(dead_code)] struct Account { id: u32, } impl Account { fn build_script(n: u32) -> (Script, RegistryAddress) { let mut addr = [0u8; 20]; addr[..4].copy_from_slice(&n.to_le_bytes()); let mut args = vec![42u8; 32]; args.extend(&addr); let script = Script::new_builder() .code_hash(ALWAYS_SUCCESS_LOCK_HASH.pack()) .hash_type(ScriptHashType::Type.into()) .args(args.pack()) .build(); let addr = RegistryAddress::new(ETH_REGISTRY_ACCOUNT_ID, addr.to_vec()); (script, addr) } } struct BenchChain; impl ChainView for BenchChain { fn get_block_hash_by_number(&self, _: u64) -> Result<Option<H256>>
} struct BenchExecutionEnvironment { generator: Generator, chain: BenchChain, mem_pool_state: MemPoolState, } impl BenchExecutionEnvironment { fn new_with_accounts(store: Store, accounts: u32) -> Self { let genesis_config = GenesisConfig { meta_contract_validator_type_hash: META_VALIDATOR_SCRIPT_TYPE_HASH.into(), rollup_type_hash: ROLLUP_TYPE_HASH.into(), rollup_config: RollupConfig::new_builder() .l2_sudt_validator_script_type_hash(SUDT_VALIDATOR_SCRIPT_TYPE_HASH.pack()) .allowed_eoa_type_hashes( vec![AllowedTypeHash::new_builder() .hash(ALWAYS_SUCCESS_LOCK_HASH.pack()) .type_(AllowedEoaType::Eth.into()) .build()] .pack(), ) .build() .into(), ..Default::default() }; let rollup_context = RollupContext { rollup_config: genesis_config.rollup_config.clone().into(), rollup_script_hash: ROLLUP_TYPE_HASH, ..Default::default() }; let backend_manage = { let configs = vec![ BackendConfig { generator: Resource::file_system(META_GENERATOR_PATH.into()), generator_checksum: file_checksum(&META_GENERATOR_PATH).unwrap().into(), validator_script_type_hash: META_VALIDATOR_SCRIPT_TYPE_HASH.into(), backend_type: gw_config::BackendType::Meta, }, BackendConfig { generator: Resource::file_system(SUDT_GENERATOR_PATH.into()), generator_checksum: file_checksum(&SUDT_GENERATOR_PATH).unwrap().into(), validator_script_type_hash: SUDT_VALIDATOR_SCRIPT_TYPE_HASH.into(), backend_type: gw_config::BackendType::Sudt, }, ]; BackendManage::from_config(vec![BackendForkConfig { sudt_proxy: Default::default(), fork_height: 0, backends: configs, }]) .expect("bench backend") }; let account_lock_manage = { let mut manage = AccountLockManage::default(); manage.register_lock_algorithm(ALWAYS_SUCCESS_LOCK_HASH, Arc::new(AlwaysSuccess)); manage }; let generator = Generator::new( backend_manage, account_lock_manage, rollup_context, Default::default(), ); Self::init_genesis(&store, &genesis_config, accounts); let mem_pool_state = MemPoolState::new( MemStateDB::from_store(store.get_snapshot()).expect("mem state db"), true, ); BenchExecutionEnvironment { generator, chain: BenchChain, mem_pool_state, } } fn accounts_transfer(&self, accounts: u32, count: usize) { let mut state = self.mem_pool_state.load_state_db(); let (block_producer_script, block_producer) = Account::build_script(0); let block_info = BlockInfo::new_builder() .block_producer(Bytes::from(block_producer.to_bytes()).pack()) .number(1.pack()) .timestamp(1.pack()) .build(); let block_producer_balance = state .get_sudt_balance(CKB_SUDT_ACCOUNT_ID, &block_producer) .unwrap(); let addrs: Vec<_> = (0..=accounts) .map(Account::build_script) .map(|(_s, addr)| addr) .collect(); let address_offset = state .get_account_id_by_script_hash(&block_producer_script.hash()) .unwrap() .unwrap(); // start from block producer let start_account_id = address_offset + 1; let end_account_id = address_offset + accounts; // Loop transfer from id to id + 1, until we reach target count let mut from_id = start_account_id; let mut transfer_count = count; while transfer_count > 0 { let to_address = { let mut to_id = from_id + 1; if to_id > end_account_id { to_id = start_account_id; } addrs.get((to_id - address_offset) as usize).unwrap() }; let args = SUDTArgs::new_builder() .set( SUDTTransfer::new_builder() .to_address(Bytes::from(to_address.to_bytes()).pack()) .amount(U256::one().pack()) .fee( Fee::new_builder() .registry_id(ETH_REGISTRY_ACCOUNT_ID.pack()) .amount(1u128.pack()) .build(), ) .build(), ) .build(); let raw_tx = RawL2Transaction::new_builder() .from_id(from_id.pack()) .to_id(1u32.pack()) .args(args.as_bytes().pack()) .build(); self.generator .execute_transaction( &self.chain, &mut state, &block_info, &raw_tx, Some(u64::MAX), None, ) .unwrap(); state.finalise().unwrap(); from_id += 1; if from_id > end_account_id { from_id = start_account_id; } transfer_count -= 1; } self.mem_pool_state.store_state_db(state); let state = self.mem_pool_state.load_state_db(); let post_block_producer_balance = state .get_sudt_balance(CKB_SUDT_ACCOUNT_ID, &block_producer) .unwrap(); assert_eq!( post_block_producer_balance, block_producer_balance + count as u128 ); } fn generate_accounts( state: &mut (impl State + StateExt + CodeStore), accounts: u32, ) -> Vec<Account> { let build_account = |idx: u32| -> Account { let (account_script, addr) = Account::build_script(idx); let account_script_hash: H256 = account_script.hash(); let account_id = state.create_account(account_script_hash).unwrap(); state.insert_script(account_script_hash, account_script); state .mapping_registry_address_to_script_hash(addr.clone(), account_script_hash) .unwrap(); state .mint_sudt(CKB_SUDT_ACCOUNT_ID, &addr, CKB_BALANCE.into()) .unwrap(); Account { id: account_id } }; (0..accounts).map(build_account).collect() } fn init_genesis(store: &Store, config: &GenesisConfig, accounts: u32) { if store.has_genesis().unwrap() { let chain_id = store.get_chain_id().unwrap(); if chain_id == ROLLUP_TYPE_HASH { return; } else { panic!("store genesis already initialized"); } } let mut db = store.begin_transaction(); db.setup_chain_id(ROLLUP_TYPE_HASH).unwrap(); let (mut db, genesis_state) = build_genesis_from_store(db, config, Default::default()).unwrap(); let smt = db .state_smt_with_merkle_state(genesis_state.genesis.raw().post_account()) .unwrap(); let account_count = genesis_state.genesis.raw().post_account().count().unpack(); let mut state = { let history_state = HistoryState::new(smt, account_count, RWConfig::attach_block(0)); StateDB::new(history_state) }; Self::generate_accounts(&mut state, accounts + 1); // Plus block producer state.finalise().unwrap(); let (genesis, global_state) = { let prev_state_checkpoint: [u8; 32] = state.calculate_state_checkpoint().unwrap(); let submit_txs = SubmitTransactions::new_builder() .prev_state_checkpoint(prev_state_checkpoint.pack()) .build(); // calculate post state let post_account = { let root = state.calculate_root().unwrap(); let count = state.get_account_count().unwrap(); AccountMerkleState::new_builder() .merkle_root(root.pack()) .count(count.pack()) .build() }; let raw_genesis = RawL2Block::new_builder() .number(0u64.pack()) .parent_block_hash([0u8; 32].pack()) .timestamp(1.pack()) .post_account(post_account.clone()) .submit_transactions(submit_txs) .build(); // generate block proof let genesis_hash = raw_genesis.hash(); let (block_root, block_proof) = { let block_key = RawL2Block::compute_smt_key(0); let mut smt = db.block_smt().unwrap(); smt.update(block_key.into(), genesis_hash.into()).unwrap(); let block_proof = smt .merkle_proof(vec![block_key.into()]) .unwrap() .compile(vec![block_key.into()]) .unwrap(); let block_root = *smt.root(); (block_root, block_proof) }; // build genesis let genesis = L2Block::new_builder() .raw(raw_genesis) .block_proof(block_proof.0.pack()) .build(); let global_state = { let post_block = BlockMerkleState::new_builder() .merkle_root({ let root: [u8; 32] = block_root.into(); root.pack() }) .count(1u64.pack()) .build(); let rollup_config_hash = { let mut hasher = new_blake2b(); hasher.update( Into::<RollupConfig>::into(config.rollup_config.clone()).as_slice(), ); let mut hash = [0u8; 32]; hasher.finalize(&mut hash); hash }; GlobalState::new_builder() .account(post_account) .block(post_block) .status((Status::Running as u8).into()) .rollup_config_hash(rollup_config_hash.pack()) .tip_block_hash(genesis.hash().pack()) .build() }; db.set_block_smt_root(global_state.block().merkle_root().unpack()) .unwrap(); (genesis, global_state) }; let prev_txs_state = genesis.as_reader().raw().post_account().to_entity(); db.insert_block( genesis.clone(), global_state, prev_txs_state, Vec::new(), Default::default(), Vec::new(), ) .unwrap(); db.attach_block(genesis).unwrap(); db.commit().unwrap(); } }
{ unreachable!("bench chain store") }
identifier_body
smt.rs
use std::sync::Arc; use anyhow::Result; use criterion::{criterion_group, BenchmarkId, Criterion, Throughput}; use gw_builtin_binaries::{file_checksum, Resource}; use gw_common::{ blake2b::new_blake2b, builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID}, registry_address::RegistryAddress, state::State, }; use gw_config::{BackendConfig, BackendForkConfig, GenesisConfig, StoreConfig}; use gw_generator::{ account_lock_manage::{always_success::AlwaysSuccess, AccountLockManage}, backend_manage::BackendManage, genesis::build_genesis_from_store, traits::StateExt, Generator, }; use gw_store::{ mem_pool_state::MemPoolState, schema::COLUMNS, state::{ history::history_state::{HistoryState, RWConfig}, state_db::StateDB, traits::JournalDB, MemStateDB, }, traits::chain_store::ChainStore, Store, }; use gw_traits::{ChainView, CodeStore}; use gw_types::{ bytes::Bytes, core::{AllowedEoaType, ScriptHashType, Status}, h256::*, packed::{ AccountMerkleState, AllowedTypeHash, BlockInfo, BlockMerkleState, Fee, GlobalState, L2Block, RawL2Block, RawL2Transaction, RollupConfig, SUDTArgs, SUDTTransfer, Script, SubmitTransactions, }, prelude::*, U256, }; use gw_utils::RollupContext; use pprof::criterion::{Output, PProfProfiler}; // meta contract const META_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/meta-contract-generator"; const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32]; // sudt contract const SUDT_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/sudt-generator"; const SUDT_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [2u8; 32]; // always success lock const ALWAYS_SUCCESS_LOCK_HASH: [u8; 32] = [3u8; 32]; // rollup type hash const ROLLUP_TYPE_HASH: [u8; 32] = [4u8; 32]; const CKB_BALANCE: u128 = 100_000_000; criterion_group! { name = smt; config = Criterion::default() .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); targets = bench_ckb_transfer } pub fn bench_ckb_transfer(c: &mut Criterion) { let config = StoreConfig { path: "./smt_data/db".parse().unwrap(), options_file: Some("./smt_data/db.toml".parse().unwrap()), cache_size: Some(1073741824), }; let store = Store::open(&config, COLUMNS).unwrap(); let ee = BenchExecutionEnvironment::new_with_accounts(store, 7000); let mut group = c.benchmark_group("ckb_transfer"); for txs in (500..=5000).step_by(500) { group.sample_size(10); group.throughput(Throughput::Elements(txs)); group.bench_with_input(BenchmarkId::from_parameter(txs), &txs, |b, txs| { b.iter(|| { ee.accounts_transfer(7000, *txs as usize); }); }); } group.finish(); } #[allow(dead_code)] struct Account { id: u32, } impl Account { fn build_script(n: u32) -> (Script, RegistryAddress) { let mut addr = [0u8; 20]; addr[..4].copy_from_slice(&n.to_le_bytes()); let mut args = vec![42u8; 32]; args.extend(&addr); let script = Script::new_builder() .code_hash(ALWAYS_SUCCESS_LOCK_HASH.pack()) .hash_type(ScriptHashType::Type.into()) .args(args.pack()) .build(); let addr = RegistryAddress::new(ETH_REGISTRY_ACCOUNT_ID, addr.to_vec()); (script, addr) } } struct BenchChain; impl ChainView for BenchChain { fn get_block_hash_by_number(&self, _: u64) -> Result<Option<H256>> { unreachable!("bench chain store") } } struct BenchExecutionEnvironment { generator: Generator, chain: BenchChain, mem_pool_state: MemPoolState, } impl BenchExecutionEnvironment { fn new_with_accounts(store: Store, accounts: u32) -> Self { let genesis_config = GenesisConfig { meta_contract_validator_type_hash: META_VALIDATOR_SCRIPT_TYPE_HASH.into(), rollup_type_hash: ROLLUP_TYPE_HASH.into(), rollup_config: RollupConfig::new_builder() .l2_sudt_validator_script_type_hash(SUDT_VALIDATOR_SCRIPT_TYPE_HASH.pack()) .allowed_eoa_type_hashes( vec![AllowedTypeHash::new_builder() .hash(ALWAYS_SUCCESS_LOCK_HASH.pack()) .type_(AllowedEoaType::Eth.into()) .build()] .pack(), ) .build() .into(), ..Default::default() }; let rollup_context = RollupContext { rollup_config: genesis_config.rollup_config.clone().into(), rollup_script_hash: ROLLUP_TYPE_HASH, ..Default::default() }; let backend_manage = { let configs = vec![ BackendConfig { generator: Resource::file_system(META_GENERATOR_PATH.into()), generator_checksum: file_checksum(&META_GENERATOR_PATH).unwrap().into(), validator_script_type_hash: META_VALIDATOR_SCRIPT_TYPE_HASH.into(), backend_type: gw_config::BackendType::Meta, }, BackendConfig { generator: Resource::file_system(SUDT_GENERATOR_PATH.into()), generator_checksum: file_checksum(&SUDT_GENERATOR_PATH).unwrap().into(), validator_script_type_hash: SUDT_VALIDATOR_SCRIPT_TYPE_HASH.into(), backend_type: gw_config::BackendType::Sudt, }, ]; BackendManage::from_config(vec![BackendForkConfig { sudt_proxy: Default::default(), fork_height: 0, backends: configs, }]) .expect("bench backend") }; let account_lock_manage = { let mut manage = AccountLockManage::default(); manage.register_lock_algorithm(ALWAYS_SUCCESS_LOCK_HASH, Arc::new(AlwaysSuccess)); manage }; let generator = Generator::new( backend_manage, account_lock_manage, rollup_context, Default::default(), ); Self::init_genesis(&store, &genesis_config, accounts); let mem_pool_state = MemPoolState::new( MemStateDB::from_store(store.get_snapshot()).expect("mem state db"), true, ); BenchExecutionEnvironment { generator, chain: BenchChain, mem_pool_state, } } fn accounts_transfer(&self, accounts: u32, count: usize) { let mut state = self.mem_pool_state.load_state_db(); let (block_producer_script, block_producer) = Account::build_script(0); let block_info = BlockInfo::new_builder() .block_producer(Bytes::from(block_producer.to_bytes()).pack()) .number(1.pack()) .timestamp(1.pack()) .build(); let block_producer_balance = state .get_sudt_balance(CKB_SUDT_ACCOUNT_ID, &block_producer) .unwrap(); let addrs: Vec<_> = (0..=accounts) .map(Account::build_script) .map(|(_s, addr)| addr) .collect(); let address_offset = state .get_account_id_by_script_hash(&block_producer_script.hash()) .unwrap() .unwrap(); // start from block producer let start_account_id = address_offset + 1; let end_account_id = address_offset + accounts; // Loop transfer from id to id + 1, until we reach target count let mut from_id = start_account_id; let mut transfer_count = count; while transfer_count > 0 { let to_address = { let mut to_id = from_id + 1; if to_id > end_account_id { to_id = start_account_id; } addrs.get((to_id - address_offset) as usize).unwrap() }; let args = SUDTArgs::new_builder() .set( SUDTTransfer::new_builder() .to_address(Bytes::from(to_address.to_bytes()).pack()) .amount(U256::one().pack()) .fee( Fee::new_builder() .registry_id(ETH_REGISTRY_ACCOUNT_ID.pack()) .amount(1u128.pack()) .build(), ) .build(), ) .build(); let raw_tx = RawL2Transaction::new_builder() .from_id(from_id.pack()) .to_id(1u32.pack()) .args(args.as_bytes().pack()) .build(); self.generator .execute_transaction( &self.chain, &mut state, &block_info, &raw_tx, Some(u64::MAX), None, ) .unwrap(); state.finalise().unwrap(); from_id += 1; if from_id > end_account_id { from_id = start_account_id; } transfer_count -= 1; } self.mem_pool_state.store_state_db(state); let state = self.mem_pool_state.load_state_db(); let post_block_producer_balance = state .get_sudt_balance(CKB_SUDT_ACCOUNT_ID, &block_producer) .unwrap(); assert_eq!( post_block_producer_balance, block_producer_balance + count as u128 ); } fn generate_accounts( state: &mut (impl State + StateExt + CodeStore), accounts: u32, ) -> Vec<Account> { let build_account = |idx: u32| -> Account { let (account_script, addr) = Account::build_script(idx); let account_script_hash: H256 = account_script.hash(); let account_id = state.create_account(account_script_hash).unwrap(); state.insert_script(account_script_hash, account_script); state .mapping_registry_address_to_script_hash(addr.clone(), account_script_hash) .unwrap(); state .mint_sudt(CKB_SUDT_ACCOUNT_ID, &addr, CKB_BALANCE.into()) .unwrap(); Account { id: account_id } }; (0..accounts).map(build_account).collect() } fn init_genesis(store: &Store, config: &GenesisConfig, accounts: u32) { if store.has_genesis().unwrap() { let chain_id = store.get_chain_id().unwrap(); if chain_id == ROLLUP_TYPE_HASH { return; } else
} let mut db = store.begin_transaction(); db.setup_chain_id(ROLLUP_TYPE_HASH).unwrap(); let (mut db, genesis_state) = build_genesis_from_store(db, config, Default::default()).unwrap(); let smt = db .state_smt_with_merkle_state(genesis_state.genesis.raw().post_account()) .unwrap(); let account_count = genesis_state.genesis.raw().post_account().count().unpack(); let mut state = { let history_state = HistoryState::new(smt, account_count, RWConfig::attach_block(0)); StateDB::new(history_state) }; Self::generate_accounts(&mut state, accounts + 1); // Plus block producer state.finalise().unwrap(); let (genesis, global_state) = { let prev_state_checkpoint: [u8; 32] = state.calculate_state_checkpoint().unwrap(); let submit_txs = SubmitTransactions::new_builder() .prev_state_checkpoint(prev_state_checkpoint.pack()) .build(); // calculate post state let post_account = { let root = state.calculate_root().unwrap(); let count = state.get_account_count().unwrap(); AccountMerkleState::new_builder() .merkle_root(root.pack()) .count(count.pack()) .build() }; let raw_genesis = RawL2Block::new_builder() .number(0u64.pack()) .parent_block_hash([0u8; 32].pack()) .timestamp(1.pack()) .post_account(post_account.clone()) .submit_transactions(submit_txs) .build(); // generate block proof let genesis_hash = raw_genesis.hash(); let (block_root, block_proof) = { let block_key = RawL2Block::compute_smt_key(0); let mut smt = db.block_smt().unwrap(); smt.update(block_key.into(), genesis_hash.into()).unwrap(); let block_proof = smt .merkle_proof(vec![block_key.into()]) .unwrap() .compile(vec![block_key.into()]) .unwrap(); let block_root = *smt.root(); (block_root, block_proof) }; // build genesis let genesis = L2Block::new_builder() .raw(raw_genesis) .block_proof(block_proof.0.pack()) .build(); let global_state = { let post_block = BlockMerkleState::new_builder() .merkle_root({ let root: [u8; 32] = block_root.into(); root.pack() }) .count(1u64.pack()) .build(); let rollup_config_hash = { let mut hasher = new_blake2b(); hasher.update( Into::<RollupConfig>::into(config.rollup_config.clone()).as_slice(), ); let mut hash = [0u8; 32]; hasher.finalize(&mut hash); hash }; GlobalState::new_builder() .account(post_account) .block(post_block) .status((Status::Running as u8).into()) .rollup_config_hash(rollup_config_hash.pack()) .tip_block_hash(genesis.hash().pack()) .build() }; db.set_block_smt_root(global_state.block().merkle_root().unpack()) .unwrap(); (genesis, global_state) }; let prev_txs_state = genesis.as_reader().raw().post_account().to_entity(); db.insert_block( genesis.clone(), global_state, prev_txs_state, Vec::new(), Default::default(), Vec::new(), ) .unwrap(); db.attach_block(genesis).unwrap(); db.commit().unwrap(); } }
{ panic!("store genesis already initialized"); }
conditional_block
stream.rs
// Copyright 2016 Jeffrey Burdges. //! Sphinx header symmetric cryptographic routines //! //!... use std::fmt; use std::ops::Range; use std::marker::PhantomData; // use clear_on_drop::ClearOnDrop; use crypto::mac::Mac; use crypto::poly1305::Poly1305; use chacha::ChaCha as ChaCha20; use keystream::{KeyStream,SeekableKeyStream}; use keystream::Error as KeystreamError; impl<'a> From<KeystreamError> for SphinxError { fn from(ke: KeystreamError) -> SphinxError { match ke { KeystreamError::EndReached => { // We verify the maximum key stream length is not // exceeded inside `SphinxParams::stream_chunks`. // panic!("Failed to unwrap ChaCha call!"); SphinxError::InternalError("XChaCha20 stream exceeded!") }, } } } use super::layout::{Params}; use super::body::{BodyCipher,BODY_CIPHER_KEY_SIZE}; use super::replay::*; use super::error::*; use super::*; // /// Sphinx onion encrypted routing information // pub type BetaBytes = [u8]; pub const GAMMA_LENGTH : usize = 16; /// Unwrapped Sphinx poly1305 MAC pub type GammaBytes = [u8; GAMMA_LENGTH]; /// Wrapped Sphinx poly1305 MAC #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] pub struct Gamma(pub GammaBytes); /// Sphinx poly1305 MAC key #[derive(Debug,Clone,Copy,Default)] struct GammaKey(pub [u8; 32]); /// IETF Chacha20 stream cipher key and nonce. #[derive(Clone)] pub struct ChaChaKnN { /// IETF ChaCha20 32 byte key pub key: [u8; 32], /// IETF ChaCha20 12 byte nonce pub nonce: [u8; 12], } impl ChaChaKnN { /// Initalize an IETF ChaCha20 stream cipher with our key material /// and use it to generate the poly1305 key for our MAC gamma, and /// the packet's name for SURB unwinding. /// /// Notes: We could improve performance by using the curve25519 point /// derived in the key exchagne directly as the key for an XChaCha20 /// instance, which includes some mixing, and using chacha for the /// replay code and gamma key. We descided to use SHA3's SHAKE256 /// mode so that we have more and different mixing. pub fn header_cipher<P: Params>(&self) -> SphinxResult<HeaderCipher<P>> { let mut chacha = ChaCha20::new_ietf(&self.key, &self.nonce); let r = &mut [0u8; HOP_EATS]; chacha.xor_read(r).unwrap(); // No KeystreamError::EndReached here. let (packet_name,replay_code,gamma_key) = array_refs![r,16,16,32]; Ok( HeaderCipher { params: PhantomData, chunks: StreamChunks::make::<P>()?, packet_name: PacketName(*packet_name), replay_code: ReplayCode(*replay_code), gamma_key: GammaKey(*gamma_key), stream: chacha, } ) } } /// Results of our KDF consisting of the nonce and key for our /// IETF Chacha20 stream cipher, which produces everything else /// in the Sphinx header. #[derive(Clone)] pub struct SphinxKey<P: Params> { pub params: PhantomData<P>, /// IETF Chacha20 stream cipher key and nonce. pub chacha: ChaChaKnN, } /* impl<P> Clone for SphinxKey<P> where P: Params { fn clone(&self) -> SphinxKey<P> { SphinxKey { params: PhantomData, chacha: chacha.clone(), } } } */ impl<P: Params> SphinxKey<P> { /// Derive the key material for our IETF Chacha20 stream cipher, /// incorporating both `P::PROTOCOL_NAME` and our `RoutingName` /// as seed material. pub fn new_kdf(ss: &SphinxSecret, rn: &::keys::RoutingName) -> SphinxKey<P> { use crypto::digest::Digest; use crypto::sha3::Sha3; let r = &mut [0u8; 32+16]; // ClearOnDrop let mut sha = Sha3::shake_256(); sha.input(&ss.0); sha.input_str( "Sphinx" ); sha.input(&rn.0); sha.input_str( P::PROTOCOL_NAME ); sha.input(&ss.0); sha.result(r); sha.reset(); let (nonce,_,key) = array_refs![r,12,4,32]; SphinxKey { params: PhantomData, chacha: ChaChaKnN { nonce: *nonce, key: *key }, } } /// Initalize our IETF ChaCha20 stream cipher by invoking /// `ChaChaKnN::header_cipher` with our paramaters `P: Params`. pub fn header_cipher(&self) -> SphinxResult<HeaderCipher<P>> { self.chacha.header_cipher::<P>() } } /// Amount of key stream consumed by `hop()` itself const HOP_EATS : usize = 64; /// Allocation of cipher ranges for the IETF ChaCha20 inside /// `HeaderCipher` to various keys and stream cipher roles needed /// to process a header. struct StreamChunks { beta: Range<usize>, beta_tail: Range<usize>, surb_log: Range<usize>, lioness_key: Range<usize>, blinding: Range<usize>, delay: Range<usize>, } impl StreamChunks { #[inline] fn make<P: Params>() -> SphinxResult<StreamChunks> { let mut offset = HOP_EATS; // let chunks = { let mut reserve = |l: usize, block: bool| -> Range<usize> { if block { offset += 64 - offset % 64; } let previous = offset; offset += l; let r = previous..offset; debug_assert_eq!(r.len(), l); r }; StreamChunks { beta: reserve(P::BETA_LENGTH as usize,true), beta_tail: reserve(P::MAX_BETA_TAIL_LENGTH as usize,false), surb_log: reserve(P::SURB_LOG_LENGTH as usize,true), lioness_key: reserve(BODY_CIPHER_KEY_SIZE,true), blinding: reserve(64,true), delay: reserve(64,true), // Actually 32 } }; // let chunks // We check that the maximum key stream length is not exceeded // here so that calls to both `seek_to` and `xor_read` can // safetly be `.unwrap()`ed, thereby avoiding `-> SphinxResult<_>` // everywhere. if offset > 2^38 { Err( SphinxError::InternalError("Paramaters exceed IETF ChaCha20 stream!") ) } else { Ok(chunks) } } } /// Semetric cryptography for a single Sphinx sub-hop, usually /// meaning the whole hop. /// pub struct HeaderCipher<P: Params> { params: PhantomData<P>, /// XChaCha20 Stream cipher used when processing the header stream: ChaCha20, /// Stream cipher ranges determined by `params` chunks: StreamChunks, /// Replay code for replay protection replay_code: ReplayCode, /// The packet's name for SURB unwinding packet_name: PacketName, /// Sphinx poly1305 MAC key gamma_key: GammaKey, } // Declare a `HeaderCipher` initalized after `ClearOnDrop` zeros it so // that it may be dropped normally. Requirs that `Drop::drop` does // nothing interesting. impl<P: Params> ::clear_on_drop::clear::InitializableFromZeroed for HeaderCipher<P> { unsafe fn initialize(_: *mut HeaderCipher<P>) { } } // We implement `Drop::drop` so that `HeaderCipher` cannot be copy. // `InitializableFromZeroed::initialize` leaves it invalid, so // `Drop::drop` must not do anything interesting. impl<P: Params> Drop for HeaderCipher<P> { fn drop(&mut self) { } } impl<P: Params> fmt::Debug for HeaderCipher<P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "HeaderCipher {{ {:?},.. }}", self.replay_code.error_packet_id()) } } impl<P: Params> HeaderCipher<P> { // TODO: Can we abstract the lengths checks? Operate on a pair // `(LayoutRefs,HeaderCipher)` perhaps? /// Compute the poly1305 MAC `Gamma` using the key found in a Sphinx key exchange. /// /// Does not verify the lengths of Beta or the SURB. pub fn
(&self, beta: &[u8]) -> SphinxResult<Gamma> { if beta.len()!= P::BETA_LENGTH as usize { return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") ); } // According to the current API gamma_out lies in a buffer supplied // by our caller, so no need for games to zero it here. let mut gamma_out: Gamma = Default::default(); let mut poly = Poly1305::new(&self.gamma_key.0); // let mut poly = ClearOnDrop::new(&mut poly); poly.input(beta); poly.raw_result(&mut gamma_out.0); poly.reset(); Ok(gamma_out) } /// Verify the poly1305 MAC `Gamma` given in a Sphinx packet. /// /// Returns an InvalidMac error if the check fails. Does not /// verify the lengths of Beta or the SURB. pub fn verify_gamma(&self, beta: &[u8], gamma_given: &Gamma) -> SphinxResult<()> { let gamma_found = self.create_gamma(beta)?; // InternalError // TODO: let gamma_found = ClearOnDrop::new(&gamma_found); if! ::consistenttime::ct_u8_slice_eq(&gamma_given.0, &gamma_found.0) { Err( SphinxError::InvalidMac(self.replay_code.error_packet_id()) ) } else { Ok(()) } } /// Checks for packet replays using the suplied `ReplayChecker`. /// /// Replay protection requires that `ReplayChecker::replay_check` /// returns `Err( SphinxError::Replay(hop.replay_code) )` when a /// replay occurs. /// /// You may however use `IgnoreReplay` as the `ReplayChecker` for /// ratchet sub-hops and for all subhops in packet creation. pub fn replay_check<RC: ReplayChecker>(&self, replayer: RC) -> SphinxResult<()> { replayer.replay_check(&self.replay_code) } /// Returns full key schedule for the lioness cipher for the body. pub fn lioness_key(&mut self) -> [u8; BODY_CIPHER_KEY_SIZE] { let lioness_key = &mut [0u8; BODY_CIPHER_KEY_SIZE]; self.stream.seek_to(self.chunks.lioness_key.start as u64).unwrap(); self.stream.xor_read(lioness_key).unwrap(); *lioness_key } pub fn body_cipher(&mut self) -> BodyCipher<P> { BodyCipher { params: PhantomData, cipher: ::lioness::LionessDefault::new_raw(& self.lioness_key()) } } /// Returns the curve25519 scalar for blinding alpha in Sphinx. pub fn blinding(&mut self) -> ::curve::Scalar { let b = &mut [0u8; 64]; self.stream.seek_to(self.chunks.blinding.start as u64).unwrap(); self.stream.xor_read(b).unwrap(); ::curve::Scalar::make(b) } /// Returns our name for the packet for insertion into the SURB log /// if the packet gets reforwarded. pub fn packet_name(&mut self) -> &PacketName { &self.packet_name } pub fn xor_beta(&mut self, beta: &mut [u8], offset: usize, tail: usize) -> SphinxResult<()> { let len = P::BETA_LENGTH as usize - offset; if beta.len() < len { return Err( SphinxError::InternalError("Beta too short to encrypt!") ); } if tail > P::MAX_BETA_TAIL_LENGTH as usize { return Err( SphinxError::InternalError("Excessive tail length requested!") ); } if beta.len() > len+tail { return Err( SphinxError::InternalError("Beta too long to encrypt!") ); } self.stream.seek_to((self.chunks.beta.start + offset) as u64).unwrap(); self.stream.xor_read(beta).unwrap(); Ok(()) } pub fn set_beta_tail(&mut self, beta_tail: &mut [u8]) -> SphinxResult<()> { if beta_tail.len() > P::MAX_BETA_TAIL_LENGTH as usize { return Err( SphinxError::InternalError("Beta's tail is too long!") ); } for i in beta_tail.iter_mut() { *i = 0; } self.stream.seek_to(self.chunks.beta_tail.start as u64).unwrap(); self.stream.xor_read(beta_tail).unwrap(); Ok(()) } pub fn xor_surb_log(&mut self, surb_log: &mut [u8]) -> SphinxResult<()> { if surb_log.len() > P::SURB_LOG_LENGTH as usize { return Err( SphinxError::InternalError("SURB log too long!") ); } self.stream.seek_to(self.chunks.surb_log.start as u64).unwrap(); self.stream.xor_read(surb_log).unwrap(); Ok(()) } /// Sender's sugested delay for this packet. pub fn delay(&mut self) -> ::std::time::Duration { use rand::{ChaChaRng, SeedableRng}; // Rng, Rand let mut rng = { let mut seed = [0u32; 8]; fn as_bytes_mut(t: &mut [u32; 8]) -> &mut [u8; 32] { unsafe { ::std::mem::transmute(t) } } self.stream.seek_to(self.chunks.delay.start as u64).unwrap(); self.stream.xor_read(as_bytes_mut(&mut seed)).unwrap(); for i in seed.iter_mut() { *i = u32::from_le(*i); } ChaChaRng::from_seed(&seed) }; use rand::distributions::{Exp, IndependentSample}; let exp = Exp::new(P::DELAY_LAMBDA); let delay = exp.ind_sample(&mut rng); debug_assert!( delay.is_finite() && delay.is_sign_positive() ); ::std::time::Duration::from_secs( delay.round() as u64 ) // ::std::time::Duration::new( // delay.trunc() as u64, // (1000*delay.fract()).round() as u32 // ) } // /// Approximate time when mix node should forward this packet // pub fn time(&mut self) -> ::std::time::SystemTime { // ::std::time::SystemTime::now() + self.delay() // } }
create_gamma
identifier_name
stream.rs
// Copyright 2016 Jeffrey Burdges. //! Sphinx header symmetric cryptographic routines //! //!... use std::fmt; use std::ops::Range; use std::marker::PhantomData; // use clear_on_drop::ClearOnDrop; use crypto::mac::Mac; use crypto::poly1305::Poly1305; use chacha::ChaCha as ChaCha20; use keystream::{KeyStream,SeekableKeyStream}; use keystream::Error as KeystreamError; impl<'a> From<KeystreamError> for SphinxError { fn from(ke: KeystreamError) -> SphinxError { match ke { KeystreamError::EndReached => { // We verify the maximum key stream length is not // exceeded inside `SphinxParams::stream_chunks`. // panic!("Failed to unwrap ChaCha call!"); SphinxError::InternalError("XChaCha20 stream exceeded!") }, } } } use super::layout::{Params}; use super::body::{BodyCipher,BODY_CIPHER_KEY_SIZE}; use super::replay::*; use super::error::*; use super::*; // /// Sphinx onion encrypted routing information // pub type BetaBytes = [u8]; pub const GAMMA_LENGTH : usize = 16; /// Unwrapped Sphinx poly1305 MAC pub type GammaBytes = [u8; GAMMA_LENGTH]; /// Wrapped Sphinx poly1305 MAC #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] pub struct Gamma(pub GammaBytes); /// Sphinx poly1305 MAC key #[derive(Debug,Clone,Copy,Default)] struct GammaKey(pub [u8; 32]); /// IETF Chacha20 stream cipher key and nonce. #[derive(Clone)] pub struct ChaChaKnN { /// IETF ChaCha20 32 byte key pub key: [u8; 32], /// IETF ChaCha20 12 byte nonce pub nonce: [u8; 12], } impl ChaChaKnN { /// Initalize an IETF ChaCha20 stream cipher with our key material /// and use it to generate the poly1305 key for our MAC gamma, and /// the packet's name for SURB unwinding. /// /// Notes: We could improve performance by using the curve25519 point /// derived in the key exchagne directly as the key for an XChaCha20 /// instance, which includes some mixing, and using chacha for the /// replay code and gamma key. We descided to use SHA3's SHAKE256 /// mode so that we have more and different mixing. pub fn header_cipher<P: Params>(&self) -> SphinxResult<HeaderCipher<P>> { let mut chacha = ChaCha20::new_ietf(&self.key, &self.nonce); let r = &mut [0u8; HOP_EATS]; chacha.xor_read(r).unwrap(); // No KeystreamError::EndReached here. let (packet_name,replay_code,gamma_key) = array_refs![r,16,16,32]; Ok( HeaderCipher { params: PhantomData, chunks: StreamChunks::make::<P>()?, packet_name: PacketName(*packet_name), replay_code: ReplayCode(*replay_code), gamma_key: GammaKey(*gamma_key), stream: chacha, } ) } } /// Results of our KDF consisting of the nonce and key for our /// IETF Chacha20 stream cipher, which produces everything else /// in the Sphinx header. #[derive(Clone)] pub struct SphinxKey<P: Params> { pub params: PhantomData<P>, /// IETF Chacha20 stream cipher key and nonce. pub chacha: ChaChaKnN, } /* impl<P> Clone for SphinxKey<P> where P: Params { fn clone(&self) -> SphinxKey<P> { SphinxKey { params: PhantomData, chacha: chacha.clone(), } } } */ impl<P: Params> SphinxKey<P> { /// Derive the key material for our IETF Chacha20 stream cipher, /// incorporating both `P::PROTOCOL_NAME` and our `RoutingName` /// as seed material. pub fn new_kdf(ss: &SphinxSecret, rn: &::keys::RoutingName) -> SphinxKey<P> { use crypto::digest::Digest; use crypto::sha3::Sha3; let r = &mut [0u8; 32+16]; // ClearOnDrop let mut sha = Sha3::shake_256(); sha.input(&ss.0); sha.input_str( "Sphinx" ); sha.input(&rn.0); sha.input_str( P::PROTOCOL_NAME ); sha.input(&ss.0); sha.result(r); sha.reset(); let (nonce,_,key) = array_refs![r,12,4,32]; SphinxKey { params: PhantomData, chacha: ChaChaKnN { nonce: *nonce, key: *key }, } } /// Initalize our IETF ChaCha20 stream cipher by invoking /// `ChaChaKnN::header_cipher` with our paramaters `P: Params`. pub fn header_cipher(&self) -> SphinxResult<HeaderCipher<P>> { self.chacha.header_cipher::<P>() } } /// Amount of key stream consumed by `hop()` itself const HOP_EATS : usize = 64; /// Allocation of cipher ranges for the IETF ChaCha20 inside /// `HeaderCipher` to various keys and stream cipher roles needed /// to process a header. struct StreamChunks { beta: Range<usize>, beta_tail: Range<usize>, surb_log: Range<usize>, lioness_key: Range<usize>, blinding: Range<usize>, delay: Range<usize>, } impl StreamChunks { #[inline] fn make<P: Params>() -> SphinxResult<StreamChunks> { let mut offset = HOP_EATS; // let chunks = { let mut reserve = |l: usize, block: bool| -> Range<usize> { if block { offset += 64 - offset % 64; } let previous = offset; offset += l; let r = previous..offset; debug_assert_eq!(r.len(), l); r }; StreamChunks { beta: reserve(P::BETA_LENGTH as usize,true), beta_tail: reserve(P::MAX_BETA_TAIL_LENGTH as usize,false), surb_log: reserve(P::SURB_LOG_LENGTH as usize,true), lioness_key: reserve(BODY_CIPHER_KEY_SIZE,true), blinding: reserve(64,true), delay: reserve(64,true), // Actually 32 } }; // let chunks // We check that the maximum key stream length is not exceeded // here so that calls to both `seek_to` and `xor_read` can // safetly be `.unwrap()`ed, thereby avoiding `-> SphinxResult<_>` // everywhere. if offset > 2^38 { Err( SphinxError::InternalError("Paramaters exceed IETF ChaCha20 stream!") ) } else { Ok(chunks) } } } /// Semetric cryptography for a single Sphinx sub-hop, usually /// meaning the whole hop. /// pub struct HeaderCipher<P: Params> { params: PhantomData<P>, /// XChaCha20 Stream cipher used when processing the header stream: ChaCha20, /// Stream cipher ranges determined by `params` chunks: StreamChunks, /// Replay code for replay protection replay_code: ReplayCode, /// The packet's name for SURB unwinding packet_name: PacketName, /// Sphinx poly1305 MAC key gamma_key: GammaKey, } // Declare a `HeaderCipher` initalized after `ClearOnDrop` zeros it so // that it may be dropped normally. Requirs that `Drop::drop` does // nothing interesting. impl<P: Params> ::clear_on_drop::clear::InitializableFromZeroed for HeaderCipher<P> { unsafe fn initialize(_: *mut HeaderCipher<P>) { } } // We implement `Drop::drop` so that `HeaderCipher` cannot be copy. // `InitializableFromZeroed::initialize` leaves it invalid, so // `Drop::drop` must not do anything interesting. impl<P: Params> Drop for HeaderCipher<P> { fn drop(&mut self) { } } impl<P: Params> fmt::Debug for HeaderCipher<P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "HeaderCipher {{ {:?},.. }}", self.replay_code.error_packet_id()) } } impl<P: Params> HeaderCipher<P> { // TODO: Can we abstract the lengths checks? Operate on a pair // `(LayoutRefs,HeaderCipher)` perhaps? /// Compute the poly1305 MAC `Gamma` using the key found in a Sphinx key exchange. /// /// Does not verify the lengths of Beta or the SURB. pub fn create_gamma(&self, beta: &[u8]) -> SphinxResult<Gamma> { if beta.len()!= P::BETA_LENGTH as usize { return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") ); } // According to the current API gamma_out lies in a buffer supplied // by our caller, so no need for games to zero it here. let mut gamma_out: Gamma = Default::default(); let mut poly = Poly1305::new(&self.gamma_key.0); // let mut poly = ClearOnDrop::new(&mut poly); poly.input(beta); poly.raw_result(&mut gamma_out.0); poly.reset(); Ok(gamma_out) } /// Verify the poly1305 MAC `Gamma` given in a Sphinx packet. /// /// Returns an InvalidMac error if the check fails. Does not /// verify the lengths of Beta or the SURB. pub fn verify_gamma(&self, beta: &[u8], gamma_given: &Gamma) -> SphinxResult<()> { let gamma_found = self.create_gamma(beta)?; // InternalError // TODO: let gamma_found = ClearOnDrop::new(&gamma_found); if! ::consistenttime::ct_u8_slice_eq(&gamma_given.0, &gamma_found.0) { Err( SphinxError::InvalidMac(self.replay_code.error_packet_id()) ) } else { Ok(()) } } /// Checks for packet replays using the suplied `ReplayChecker`. /// /// Replay protection requires that `ReplayChecker::replay_check` /// returns `Err( SphinxError::Replay(hop.replay_code) )` when a /// replay occurs. /// /// You may however use `IgnoreReplay` as the `ReplayChecker` for /// ratchet sub-hops and for all subhops in packet creation. pub fn replay_check<RC: ReplayChecker>(&self, replayer: RC) -> SphinxResult<()> { replayer.replay_check(&self.replay_code) } /// Returns full key schedule for the lioness cipher for the body. pub fn lioness_key(&mut self) -> [u8; BODY_CIPHER_KEY_SIZE] { let lioness_key = &mut [0u8; BODY_CIPHER_KEY_SIZE]; self.stream.seek_to(self.chunks.lioness_key.start as u64).unwrap(); self.stream.xor_read(lioness_key).unwrap(); *lioness_key } pub fn body_cipher(&mut self) -> BodyCipher<P> { BodyCipher { params: PhantomData, cipher: ::lioness::LionessDefault::new_raw(& self.lioness_key()) } } /// Returns the curve25519 scalar for blinding alpha in Sphinx. pub fn blinding(&mut self) -> ::curve::Scalar { let b = &mut [0u8; 64]; self.stream.seek_to(self.chunks.blinding.start as u64).unwrap(); self.stream.xor_read(b).unwrap(); ::curve::Scalar::make(b) } /// Returns our name for the packet for insertion into the SURB log /// if the packet gets reforwarded. pub fn packet_name(&mut self) -> &PacketName { &self.packet_name } pub fn xor_beta(&mut self, beta: &mut [u8], offset: usize, tail: usize) -> SphinxResult<()> { let len = P::BETA_LENGTH as usize - offset; if beta.len() < len { return Err( SphinxError::InternalError("Beta too short to encrypt!") ); } if tail > P::MAX_BETA_TAIL_LENGTH as usize { return Err( SphinxError::InternalError("Excessive tail length requested!") ); } if beta.len() > len+tail { return Err( SphinxError::InternalError("Beta too long to encrypt!") ); } self.stream.seek_to((self.chunks.beta.start + offset) as u64).unwrap(); self.stream.xor_read(beta).unwrap(); Ok(()) } pub fn set_beta_tail(&mut self, beta_tail: &mut [u8]) -> SphinxResult<()> { if beta_tail.len() > P::MAX_BETA_TAIL_LENGTH as usize { return Err( SphinxError::InternalError("Beta's tail is too long!") ); } for i in beta_tail.iter_mut() { *i = 0; } self.stream.seek_to(self.chunks.beta_tail.start as u64).unwrap(); self.stream.xor_read(beta_tail).unwrap(); Ok(()) } pub fn xor_surb_log(&mut self, surb_log: &mut [u8]) -> SphinxResult<()> { if surb_log.len() > P::SURB_LOG_LENGTH as usize
self.stream.seek_to(self.chunks.surb_log.start as u64).unwrap(); self.stream.xor_read(surb_log).unwrap(); Ok(()) } /// Sender's sugested delay for this packet. pub fn delay(&mut self) -> ::std::time::Duration { use rand::{ChaChaRng, SeedableRng}; // Rng, Rand let mut rng = { let mut seed = [0u32; 8]; fn as_bytes_mut(t: &mut [u32; 8]) -> &mut [u8; 32] { unsafe { ::std::mem::transmute(t) } } self.stream.seek_to(self.chunks.delay.start as u64).unwrap(); self.stream.xor_read(as_bytes_mut(&mut seed)).unwrap(); for i in seed.iter_mut() { *i = u32::from_le(*i); } ChaChaRng::from_seed(&seed) }; use rand::distributions::{Exp, IndependentSample}; let exp = Exp::new(P::DELAY_LAMBDA); let delay = exp.ind_sample(&mut rng); debug_assert!( delay.is_finite() && delay.is_sign_positive() ); ::std::time::Duration::from_secs( delay.round() as u64 ) // ::std::time::Duration::new( // delay.trunc() as u64, // (1000*delay.fract()).round() as u32 // ) } // /// Approximate time when mix node should forward this packet // pub fn time(&mut self) -> ::std::time::SystemTime { // ::std::time::SystemTime::now() + self.delay() // } }
{ return Err( SphinxError::InternalError("SURB log too long!") ); }
conditional_block
stream.rs
// Copyright 2016 Jeffrey Burdges. //! Sphinx header symmetric cryptographic routines //! //!... use std::fmt; use std::ops::Range; use std::marker::PhantomData; // use clear_on_drop::ClearOnDrop; use crypto::mac::Mac; use crypto::poly1305::Poly1305; use chacha::ChaCha as ChaCha20; use keystream::{KeyStream,SeekableKeyStream}; use keystream::Error as KeystreamError; impl<'a> From<KeystreamError> for SphinxError { fn from(ke: KeystreamError) -> SphinxError { match ke { KeystreamError::EndReached => { // We verify the maximum key stream length is not // exceeded inside `SphinxParams::stream_chunks`. // panic!("Failed to unwrap ChaCha call!"); SphinxError::InternalError("XChaCha20 stream exceeded!") }, } } } use super::layout::{Params}; use super::body::{BodyCipher,BODY_CIPHER_KEY_SIZE}; use super::replay::*; use super::error::*; use super::*; // /// Sphinx onion encrypted routing information // pub type BetaBytes = [u8]; pub const GAMMA_LENGTH : usize = 16; /// Unwrapped Sphinx poly1305 MAC pub type GammaBytes = [u8; GAMMA_LENGTH]; /// Wrapped Sphinx poly1305 MAC #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] pub struct Gamma(pub GammaBytes); /// Sphinx poly1305 MAC key #[derive(Debug,Clone,Copy,Default)] struct GammaKey(pub [u8; 32]); /// IETF Chacha20 stream cipher key and nonce. #[derive(Clone)] pub struct ChaChaKnN { /// IETF ChaCha20 32 byte key pub key: [u8; 32], /// IETF ChaCha20 12 byte nonce pub nonce: [u8; 12], } impl ChaChaKnN { /// Initalize an IETF ChaCha20 stream cipher with our key material /// and use it to generate the poly1305 key for our MAC gamma, and /// the packet's name for SURB unwinding. /// /// Notes: We could improve performance by using the curve25519 point /// derived in the key exchagne directly as the key for an XChaCha20 /// instance, which includes some mixing, and using chacha for the /// replay code and gamma key. We descided to use SHA3's SHAKE256 /// mode so that we have more and different mixing. pub fn header_cipher<P: Params>(&self) -> SphinxResult<HeaderCipher<P>> { let mut chacha = ChaCha20::new_ietf(&self.key, &self.nonce); let r = &mut [0u8; HOP_EATS]; chacha.xor_read(r).unwrap(); // No KeystreamError::EndReached here. let (packet_name,replay_code,gamma_key) = array_refs![r,16,16,32]; Ok( HeaderCipher { params: PhantomData, chunks: StreamChunks::make::<P>()?, packet_name: PacketName(*packet_name), replay_code: ReplayCode(*replay_code), gamma_key: GammaKey(*gamma_key), stream: chacha, } ) } } /// Results of our KDF consisting of the nonce and key for our /// IETF Chacha20 stream cipher, which produces everything else /// in the Sphinx header. #[derive(Clone)] pub struct SphinxKey<P: Params> { pub params: PhantomData<P>, /// IETF Chacha20 stream cipher key and nonce. pub chacha: ChaChaKnN, } /* impl<P> Clone for SphinxKey<P> where P: Params { fn clone(&self) -> SphinxKey<P> { SphinxKey { params: PhantomData, chacha: chacha.clone(), } } } */ impl<P: Params> SphinxKey<P> { /// Derive the key material for our IETF Chacha20 stream cipher, /// incorporating both `P::PROTOCOL_NAME` and our `RoutingName` /// as seed material. pub fn new_kdf(ss: &SphinxSecret, rn: &::keys::RoutingName) -> SphinxKey<P> { use crypto::digest::Digest; use crypto::sha3::Sha3; let r = &mut [0u8; 32+16]; // ClearOnDrop let mut sha = Sha3::shake_256(); sha.input(&ss.0); sha.input_str( "Sphinx" ); sha.input(&rn.0); sha.input_str( P::PROTOCOL_NAME ); sha.input(&ss.0); sha.result(r); sha.reset(); let (nonce,_,key) = array_refs![r,12,4,32]; SphinxKey { params: PhantomData, chacha: ChaChaKnN { nonce: *nonce, key: *key }, } } /// Initalize our IETF ChaCha20 stream cipher by invoking /// `ChaChaKnN::header_cipher` with our paramaters `P: Params`. pub fn header_cipher(&self) -> SphinxResult<HeaderCipher<P>> { self.chacha.header_cipher::<P>() } } /// Amount of key stream consumed by `hop()` itself const HOP_EATS : usize = 64; /// Allocation of cipher ranges for the IETF ChaCha20 inside /// `HeaderCipher` to various keys and stream cipher roles needed /// to process a header. struct StreamChunks { beta: Range<usize>, beta_tail: Range<usize>, surb_log: Range<usize>, lioness_key: Range<usize>, blinding: Range<usize>, delay: Range<usize>, } impl StreamChunks { #[inline] fn make<P: Params>() -> SphinxResult<StreamChunks> { let mut offset = HOP_EATS; // let chunks = { let mut reserve = |l: usize, block: bool| -> Range<usize> { if block { offset += 64 - offset % 64; } let previous = offset; offset += l; let r = previous..offset; debug_assert_eq!(r.len(), l); r }; StreamChunks { beta: reserve(P::BETA_LENGTH as usize,true), beta_tail: reserve(P::MAX_BETA_TAIL_LENGTH as usize,false), surb_log: reserve(P::SURB_LOG_LENGTH as usize,true), lioness_key: reserve(BODY_CIPHER_KEY_SIZE,true), blinding: reserve(64,true), delay: reserve(64,true), // Actually 32 } }; // let chunks // We check that the maximum key stream length is not exceeded // here so that calls to both `seek_to` and `xor_read` can // safetly be `.unwrap()`ed, thereby avoiding `-> SphinxResult<_>` // everywhere. if offset > 2^38 { Err( SphinxError::InternalError("Paramaters exceed IETF ChaCha20 stream!") ) } else { Ok(chunks) } } } /// Semetric cryptography for a single Sphinx sub-hop, usually /// meaning the whole hop. /// pub struct HeaderCipher<P: Params> { params: PhantomData<P>, /// XChaCha20 Stream cipher used when processing the header stream: ChaCha20, /// Stream cipher ranges determined by `params` chunks: StreamChunks, /// Replay code for replay protection replay_code: ReplayCode, /// The packet's name for SURB unwinding packet_name: PacketName, /// Sphinx poly1305 MAC key gamma_key: GammaKey, } // Declare a `HeaderCipher` initalized after `ClearOnDrop` zeros it so // that it may be dropped normally. Requirs that `Drop::drop` does // nothing interesting. impl<P: Params> ::clear_on_drop::clear::InitializableFromZeroed for HeaderCipher<P> { unsafe fn initialize(_: *mut HeaderCipher<P>) { } } // We implement `Drop::drop` so that `HeaderCipher` cannot be copy. // `InitializableFromZeroed::initialize` leaves it invalid, so // `Drop::drop` must not do anything interesting. impl<P: Params> Drop for HeaderCipher<P> { fn drop(&mut self) { } } impl<P: Params> fmt::Debug for HeaderCipher<P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "HeaderCipher {{ {:?},.. }}", self.replay_code.error_packet_id()) } } impl<P: Params> HeaderCipher<P> { // TODO: Can we abstract the lengths checks? Operate on a pair // `(LayoutRefs,HeaderCipher)` perhaps? /// Compute the poly1305 MAC `Gamma` using the key found in a Sphinx key exchange. /// /// Does not verify the lengths of Beta or the SURB. pub fn create_gamma(&self, beta: &[u8]) -> SphinxResult<Gamma>
/// Verify the poly1305 MAC `Gamma` given in a Sphinx packet. /// /// Returns an InvalidMac error if the check fails. Does not /// verify the lengths of Beta or the SURB. pub fn verify_gamma(&self, beta: &[u8], gamma_given: &Gamma) -> SphinxResult<()> { let gamma_found = self.create_gamma(beta)?; // InternalError // TODO: let gamma_found = ClearOnDrop::new(&gamma_found); if! ::consistenttime::ct_u8_slice_eq(&gamma_given.0, &gamma_found.0) { Err( SphinxError::InvalidMac(self.replay_code.error_packet_id()) ) } else { Ok(()) } } /// Checks for packet replays using the suplied `ReplayChecker`. /// /// Replay protection requires that `ReplayChecker::replay_check` /// returns `Err( SphinxError::Replay(hop.replay_code) )` when a /// replay occurs. /// /// You may however use `IgnoreReplay` as the `ReplayChecker` for /// ratchet sub-hops and for all subhops in packet creation. pub fn replay_check<RC: ReplayChecker>(&self, replayer: RC) -> SphinxResult<()> { replayer.replay_check(&self.replay_code) } /// Returns full key schedule for the lioness cipher for the body. pub fn lioness_key(&mut self) -> [u8; BODY_CIPHER_KEY_SIZE] { let lioness_key = &mut [0u8; BODY_CIPHER_KEY_SIZE]; self.stream.seek_to(self.chunks.lioness_key.start as u64).unwrap(); self.stream.xor_read(lioness_key).unwrap(); *lioness_key } pub fn body_cipher(&mut self) -> BodyCipher<P> { BodyCipher { params: PhantomData, cipher: ::lioness::LionessDefault::new_raw(& self.lioness_key()) } } /// Returns the curve25519 scalar for blinding alpha in Sphinx. pub fn blinding(&mut self) -> ::curve::Scalar { let b = &mut [0u8; 64]; self.stream.seek_to(self.chunks.blinding.start as u64).unwrap(); self.stream.xor_read(b).unwrap(); ::curve::Scalar::make(b) } /// Returns our name for the packet for insertion into the SURB log /// if the packet gets reforwarded. pub fn packet_name(&mut self) -> &PacketName { &self.packet_name } pub fn xor_beta(&mut self, beta: &mut [u8], offset: usize, tail: usize) -> SphinxResult<()> { let len = P::BETA_LENGTH as usize - offset; if beta.len() < len { return Err( SphinxError::InternalError("Beta too short to encrypt!") ); } if tail > P::MAX_BETA_TAIL_LENGTH as usize { return Err( SphinxError::InternalError("Excessive tail length requested!") ); } if beta.len() > len+tail { return Err( SphinxError::InternalError("Beta too long to encrypt!") ); } self.stream.seek_to((self.chunks.beta.start + offset) as u64).unwrap(); self.stream.xor_read(beta).unwrap(); Ok(()) } pub fn set_beta_tail(&mut self, beta_tail: &mut [u8]) -> SphinxResult<()> { if beta_tail.len() > P::MAX_BETA_TAIL_LENGTH as usize { return Err( SphinxError::InternalError("Beta's tail is too long!") ); } for i in beta_tail.iter_mut() { *i = 0; } self.stream.seek_to(self.chunks.beta_tail.start as u64).unwrap(); self.stream.xor_read(beta_tail).unwrap(); Ok(()) } pub fn xor_surb_log(&mut self, surb_log: &mut [u8]) -> SphinxResult<()> { if surb_log.len() > P::SURB_LOG_LENGTH as usize { return Err( SphinxError::InternalError("SURB log too long!") ); } self.stream.seek_to(self.chunks.surb_log.start as u64).unwrap(); self.stream.xor_read(surb_log).unwrap(); Ok(()) } /// Sender's sugested delay for this packet. pub fn delay(&mut self) -> ::std::time::Duration { use rand::{ChaChaRng, SeedableRng}; // Rng, Rand let mut rng = { let mut seed = [0u32; 8]; fn as_bytes_mut(t: &mut [u32; 8]) -> &mut [u8; 32] { unsafe { ::std::mem::transmute(t) } } self.stream.seek_to(self.chunks.delay.start as u64).unwrap(); self.stream.xor_read(as_bytes_mut(&mut seed)).unwrap(); for i in seed.iter_mut() { *i = u32::from_le(*i); } ChaChaRng::from_seed(&seed) }; use rand::distributions::{Exp, IndependentSample}; let exp = Exp::new(P::DELAY_LAMBDA); let delay = exp.ind_sample(&mut rng); debug_assert!( delay.is_finite() && delay.is_sign_positive() ); ::std::time::Duration::from_secs( delay.round() as u64 ) // ::std::time::Duration::new( // delay.trunc() as u64, // (1000*delay.fract()).round() as u32 // ) } // /// Approximate time when mix node should forward this packet // pub fn time(&mut self) -> ::std::time::SystemTime { // ::std::time::SystemTime::now() + self.delay() // } }
{ if beta.len() != P::BETA_LENGTH as usize { return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") ); } // According to the current API gamma_out lies in a buffer supplied // by our caller, so no need for games to zero it here. let mut gamma_out: Gamma = Default::default(); let mut poly = Poly1305::new(&self.gamma_key.0); // let mut poly = ClearOnDrop::new(&mut poly); poly.input(beta); poly.raw_result(&mut gamma_out.0); poly.reset(); Ok(gamma_out) }
identifier_body
stream.rs
// Copyright 2016 Jeffrey Burdges. //! Sphinx header symmetric cryptographic routines //! //!... use std::fmt; use std::ops::Range; use std::marker::PhantomData; // use clear_on_drop::ClearOnDrop; use crypto::mac::Mac; use crypto::poly1305::Poly1305; use chacha::ChaCha as ChaCha20; use keystream::{KeyStream,SeekableKeyStream}; use keystream::Error as KeystreamError; impl<'a> From<KeystreamError> for SphinxError { fn from(ke: KeystreamError) -> SphinxError { match ke { KeystreamError::EndReached => { // We verify the maximum key stream length is not // exceeded inside `SphinxParams::stream_chunks`. // panic!("Failed to unwrap ChaCha call!"); SphinxError::InternalError("XChaCha20 stream exceeded!") }, } } } use super::layout::{Params}; use super::body::{BodyCipher,BODY_CIPHER_KEY_SIZE}; use super::replay::*; use super::error::*; use super::*; // /// Sphinx onion encrypted routing information // pub type BetaBytes = [u8]; pub const GAMMA_LENGTH : usize = 16; /// Unwrapped Sphinx poly1305 MAC pub type GammaBytes = [u8; GAMMA_LENGTH]; /// Wrapped Sphinx poly1305 MAC #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] pub struct Gamma(pub GammaBytes); /// Sphinx poly1305 MAC key #[derive(Debug,Clone,Copy,Default)] struct GammaKey(pub [u8; 32]); /// IETF Chacha20 stream cipher key and nonce. #[derive(Clone)] pub struct ChaChaKnN { /// IETF ChaCha20 32 byte key pub key: [u8; 32], /// IETF ChaCha20 12 byte nonce pub nonce: [u8; 12], } impl ChaChaKnN { /// Initalize an IETF ChaCha20 stream cipher with our key material /// and use it to generate the poly1305 key for our MAC gamma, and /// the packet's name for SURB unwinding. /// /// Notes: We could improve performance by using the curve25519 point /// derived in the key exchagne directly as the key for an XChaCha20 /// instance, which includes some mixing, and using chacha for the /// replay code and gamma key. We descided to use SHA3's SHAKE256 /// mode so that we have more and different mixing. pub fn header_cipher<P: Params>(&self) -> SphinxResult<HeaderCipher<P>> { let mut chacha = ChaCha20::new_ietf(&self.key, &self.nonce); let r = &mut [0u8; HOP_EATS]; chacha.xor_read(r).unwrap(); // No KeystreamError::EndReached here. let (packet_name,replay_code,gamma_key) = array_refs![r,16,16,32]; Ok( HeaderCipher { params: PhantomData, chunks: StreamChunks::make::<P>()?, packet_name: PacketName(*packet_name), replay_code: ReplayCode(*replay_code), gamma_key: GammaKey(*gamma_key), stream: chacha, } ) } } /// Results of our KDF consisting of the nonce and key for our /// IETF Chacha20 stream cipher, which produces everything else /// in the Sphinx header. #[derive(Clone)] pub struct SphinxKey<P: Params> { pub params: PhantomData<P>, /// IETF Chacha20 stream cipher key and nonce. pub chacha: ChaChaKnN, } /* impl<P> Clone for SphinxKey<P> where P: Params { fn clone(&self) -> SphinxKey<P> { SphinxKey { params: PhantomData, chacha: chacha.clone(), } } } */ impl<P: Params> SphinxKey<P> { /// Derive the key material for our IETF Chacha20 stream cipher, /// incorporating both `P::PROTOCOL_NAME` and our `RoutingName` /// as seed material. pub fn new_kdf(ss: &SphinxSecret, rn: &::keys::RoutingName) -> SphinxKey<P> { use crypto::digest::Digest; use crypto::sha3::Sha3; let r = &mut [0u8; 32+16]; // ClearOnDrop let mut sha = Sha3::shake_256(); sha.input(&ss.0); sha.input_str( "Sphinx" ); sha.input(&rn.0); sha.input_str( P::PROTOCOL_NAME ); sha.input(&ss.0); sha.result(r); sha.reset(); let (nonce,_,key) = array_refs![r,12,4,32]; SphinxKey { params: PhantomData, chacha: ChaChaKnN { nonce: *nonce, key: *key },
/// Initalize our IETF ChaCha20 stream cipher by invoking /// `ChaChaKnN::header_cipher` with our paramaters `P: Params`. pub fn header_cipher(&self) -> SphinxResult<HeaderCipher<P>> { self.chacha.header_cipher::<P>() } } /// Amount of key stream consumed by `hop()` itself const HOP_EATS : usize = 64; /// Allocation of cipher ranges for the IETF ChaCha20 inside /// `HeaderCipher` to various keys and stream cipher roles needed /// to process a header. struct StreamChunks { beta: Range<usize>, beta_tail: Range<usize>, surb_log: Range<usize>, lioness_key: Range<usize>, blinding: Range<usize>, delay: Range<usize>, } impl StreamChunks { #[inline] fn make<P: Params>() -> SphinxResult<StreamChunks> { let mut offset = HOP_EATS; // let chunks = { let mut reserve = |l: usize, block: bool| -> Range<usize> { if block { offset += 64 - offset % 64; } let previous = offset; offset += l; let r = previous..offset; debug_assert_eq!(r.len(), l); r }; StreamChunks { beta: reserve(P::BETA_LENGTH as usize,true), beta_tail: reserve(P::MAX_BETA_TAIL_LENGTH as usize,false), surb_log: reserve(P::SURB_LOG_LENGTH as usize,true), lioness_key: reserve(BODY_CIPHER_KEY_SIZE,true), blinding: reserve(64,true), delay: reserve(64,true), // Actually 32 } }; // let chunks // We check that the maximum key stream length is not exceeded // here so that calls to both `seek_to` and `xor_read` can // safetly be `.unwrap()`ed, thereby avoiding `-> SphinxResult<_>` // everywhere. if offset > 2^38 { Err( SphinxError::InternalError("Paramaters exceed IETF ChaCha20 stream!") ) } else { Ok(chunks) } } } /// Semetric cryptography for a single Sphinx sub-hop, usually /// meaning the whole hop. /// pub struct HeaderCipher<P: Params> { params: PhantomData<P>, /// XChaCha20 Stream cipher used when processing the header stream: ChaCha20, /// Stream cipher ranges determined by `params` chunks: StreamChunks, /// Replay code for replay protection replay_code: ReplayCode, /// The packet's name for SURB unwinding packet_name: PacketName, /// Sphinx poly1305 MAC key gamma_key: GammaKey, } // Declare a `HeaderCipher` initalized after `ClearOnDrop` zeros it so // that it may be dropped normally. Requirs that `Drop::drop` does // nothing interesting. impl<P: Params> ::clear_on_drop::clear::InitializableFromZeroed for HeaderCipher<P> { unsafe fn initialize(_: *mut HeaderCipher<P>) { } } // We implement `Drop::drop` so that `HeaderCipher` cannot be copy. // `InitializableFromZeroed::initialize` leaves it invalid, so // `Drop::drop` must not do anything interesting. impl<P: Params> Drop for HeaderCipher<P> { fn drop(&mut self) { } } impl<P: Params> fmt::Debug for HeaderCipher<P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "HeaderCipher {{ {:?},.. }}", self.replay_code.error_packet_id()) } } impl<P: Params> HeaderCipher<P> { // TODO: Can we abstract the lengths checks? Operate on a pair // `(LayoutRefs,HeaderCipher)` perhaps? /// Compute the poly1305 MAC `Gamma` using the key found in a Sphinx key exchange. /// /// Does not verify the lengths of Beta or the SURB. pub fn create_gamma(&self, beta: &[u8]) -> SphinxResult<Gamma> { if beta.len()!= P::BETA_LENGTH as usize { return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") ); } // According to the current API gamma_out lies in a buffer supplied // by our caller, so no need for games to zero it here. let mut gamma_out: Gamma = Default::default(); let mut poly = Poly1305::new(&self.gamma_key.0); // let mut poly = ClearOnDrop::new(&mut poly); poly.input(beta); poly.raw_result(&mut gamma_out.0); poly.reset(); Ok(gamma_out) } /// Verify the poly1305 MAC `Gamma` given in a Sphinx packet. /// /// Returns an InvalidMac error if the check fails. Does not /// verify the lengths of Beta or the SURB. pub fn verify_gamma(&self, beta: &[u8], gamma_given: &Gamma) -> SphinxResult<()> { let gamma_found = self.create_gamma(beta)?; // InternalError // TODO: let gamma_found = ClearOnDrop::new(&gamma_found); if! ::consistenttime::ct_u8_slice_eq(&gamma_given.0, &gamma_found.0) { Err( SphinxError::InvalidMac(self.replay_code.error_packet_id()) ) } else { Ok(()) } } /// Checks for packet replays using the suplied `ReplayChecker`. /// /// Replay protection requires that `ReplayChecker::replay_check` /// returns `Err( SphinxError::Replay(hop.replay_code) )` when a /// replay occurs. /// /// You may however use `IgnoreReplay` as the `ReplayChecker` for /// ratchet sub-hops and for all subhops in packet creation. pub fn replay_check<RC: ReplayChecker>(&self, replayer: RC) -> SphinxResult<()> { replayer.replay_check(&self.replay_code) } /// Returns full key schedule for the lioness cipher for the body. pub fn lioness_key(&mut self) -> [u8; BODY_CIPHER_KEY_SIZE] { let lioness_key = &mut [0u8; BODY_CIPHER_KEY_SIZE]; self.stream.seek_to(self.chunks.lioness_key.start as u64).unwrap(); self.stream.xor_read(lioness_key).unwrap(); *lioness_key } pub fn body_cipher(&mut self) -> BodyCipher<P> { BodyCipher { params: PhantomData, cipher: ::lioness::LionessDefault::new_raw(& self.lioness_key()) } } /// Returns the curve25519 scalar for blinding alpha in Sphinx. pub fn blinding(&mut self) -> ::curve::Scalar { let b = &mut [0u8; 64]; self.stream.seek_to(self.chunks.blinding.start as u64).unwrap(); self.stream.xor_read(b).unwrap(); ::curve::Scalar::make(b) } /// Returns our name for the packet for insertion into the SURB log /// if the packet gets reforwarded. pub fn packet_name(&mut self) -> &PacketName { &self.packet_name } pub fn xor_beta(&mut self, beta: &mut [u8], offset: usize, tail: usize) -> SphinxResult<()> { let len = P::BETA_LENGTH as usize - offset; if beta.len() < len { return Err( SphinxError::InternalError("Beta too short to encrypt!") ); } if tail > P::MAX_BETA_TAIL_LENGTH as usize { return Err( SphinxError::InternalError("Excessive tail length requested!") ); } if beta.len() > len+tail { return Err( SphinxError::InternalError("Beta too long to encrypt!") ); } self.stream.seek_to((self.chunks.beta.start + offset) as u64).unwrap(); self.stream.xor_read(beta).unwrap(); Ok(()) } pub fn set_beta_tail(&mut self, beta_tail: &mut [u8]) -> SphinxResult<()> { if beta_tail.len() > P::MAX_BETA_TAIL_LENGTH as usize { return Err( SphinxError::InternalError("Beta's tail is too long!") ); } for i in beta_tail.iter_mut() { *i = 0; } self.stream.seek_to(self.chunks.beta_tail.start as u64).unwrap(); self.stream.xor_read(beta_tail).unwrap(); Ok(()) } pub fn xor_surb_log(&mut self, surb_log: &mut [u8]) -> SphinxResult<()> { if surb_log.len() > P::SURB_LOG_LENGTH as usize { return Err( SphinxError::InternalError("SURB log too long!") ); } self.stream.seek_to(self.chunks.surb_log.start as u64).unwrap(); self.stream.xor_read(surb_log).unwrap(); Ok(()) } /// Sender's sugested delay for this packet. pub fn delay(&mut self) -> ::std::time::Duration { use rand::{ChaChaRng, SeedableRng}; // Rng, Rand let mut rng = { let mut seed = [0u32; 8]; fn as_bytes_mut(t: &mut [u32; 8]) -> &mut [u8; 32] { unsafe { ::std::mem::transmute(t) } } self.stream.seek_to(self.chunks.delay.start as u64).unwrap(); self.stream.xor_read(as_bytes_mut(&mut seed)).unwrap(); for i in seed.iter_mut() { *i = u32::from_le(*i); } ChaChaRng::from_seed(&seed) }; use rand::distributions::{Exp, IndependentSample}; let exp = Exp::new(P::DELAY_LAMBDA); let delay = exp.ind_sample(&mut rng); debug_assert!( delay.is_finite() && delay.is_sign_positive() ); ::std::time::Duration::from_secs( delay.round() as u64 ) // ::std::time::Duration::new( // delay.trunc() as u64, // (1000*delay.fract()).round() as u32 // ) } // /// Approximate time when mix node should forward this packet // pub fn time(&mut self) -> ::std::time::SystemTime { // ::std::time::SystemTime::now() + self.delay() // } }
} }
random_line_split
main.rs
use crate::avro_encode::encode; use avro_rs::schema::{RecordField, Schema, SchemaFingerprint, UnionSchema}; use avro_rs::types::Value; use avro_rs::{from_value, types::Record, Codec, Reader, Writer}; use clap::{App, Arg}; use failure::bail; use failure::Error; use futures::StreamExt; use futures_util::future::FutureExt; use log::{info, warn}; use rdkafka::client::ClientContext; use rdkafka::config::{ClientConfig, RDKafkaLogLevel}; use rdkafka::consumer::stream_consumer::{MessageStream, StreamConsumer}; use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, Rebalance}; use rdkafka::error::KafkaResult; use rdkafka::message::OwnedHeaders; use rdkafka::message::{Headers, Message}; use rdkafka::producer::{BaseProducer, BaseRecord, DeliveryResult, ProducerContext}; use rdkafka::producer::{FutureProducer, FutureRecord}; use rdkafka::topic_partition_list::TopicPartitionList; use rdkafka::util::get_rdkafka_version; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::future::Future; use std::thread::sleep; use std::time::Duration; mod avro_encode; struct CustomContext; impl ClientContext for CustomContext {} impl ConsumerContext for CustomContext { fn pre_rebalance(&self, rebalance: &Rebalance) { info!("Pre rebalance {:?}", rebalance); } fn post_rebalance(&self, rebalance: &Rebalance) { info!("Post rebalance {:?}", rebalance); } fn commit_callback(&self, result: KafkaResult<()>, _offsets: &TopicPartitionList) { info!("Committing offsets: {:?}", result); } } type LoggingConsumer = StreamConsumer<CustomContext>; #[tokio::main] async fn main() { let matches = App::new("consumer example") .version(option_env!("CARGO_PKG_VERSION").unwrap_or("")) .about("Simple command line consumer") .arg( Arg::with_name("brokers") .short("b") .long("brokers") .help("Broker list in kafka format") .takes_value(true) .default_value("localhost:9092"), ) .arg( Arg::with_name("group-id") .short("g") .long("group-id") .help("Consumer group id") .takes_value(true) .default_value("example_consumer_group_id"), ) .arg( Arg::with_name("log-conf") .long("log-conf") .help("Configure the logging format (example: 'rdkafka=trace')") .takes_value(true), ) .arg( Arg::with_name("topics") .short("t") .long("topics") .help("Topic list") .takes_value(true) .multiple(true) .required(true), ) .get_matches(); // setup_logger(true, matches.value_of("log-conf")); log4rs::init_file("log4rs.yml", Default::default()) .expect("'log4rs.yml' not found. Required for logging."); // let (version_n, version_s) = get_rdkafka_version(); // info!("rd_kafka_version: 0x{:08x}, {}", version_n, version_s); let brokers = matches.value_of("brokers").unwrap(); let topics = matches.values_of("topics").unwrap().collect::<Vec<&str>>(); let group_id = matches.value_of("group-id").unwrap(); info!("Brokers: ({:?})", brokers); info!("Topics: ({:?})", topics); info!("Group Id: ({:?})", group_id); // This sends over the schema in the payload // let payload = serialize().unwrap(); // publish(brokers, topics[0], &payload).await; // This uses `encode` to send a minimal payload let payload = serialize2().unwrap(); publish(brokers, topics[0], &payload).await; // Code for consumer // let context = CustomContext; // let consumer = get_consumer(context, brokers, group_id, &topics); // process_message_stream(&consumer).await; } async fn publish(brokers: &str, topic_name: &str, payload: &[u8]) { let producer: FutureProducer = ClientConfig::new() .set("bootstrap.servers", brokers) .set("message.timeout.ms", "5000") .create() .expect("Producer creation error"); let res = producer .send( FutureRecord::to(topic_name) .payload(payload) .key(&format!("Key1")) .headers(OwnedHeaders::new().add("header_key", "header_value")), 0, ) .await; info!("Future completed. Result: {:?}", res); } fn get_consumer<'a>( context: CustomContext, brokers: &str, group_id: &str, topics: &[&str], ) -> LoggingConsumer { let consumer: LoggingConsumer = ClientConfig::new() .set("group.id", group_id) .set("bootstrap.servers", brokers) .set("enable.partition.eof", "false") .set("session.timeout.ms", "6000") .set("enable.auto.commit", "true") //.set("statistics.interval.ms", "30000") //.set("auto.offset.reset", "smallest") .set_log_level(RDKafkaLogLevel::Debug) .create_with_context(context) .expect("Consumer creation failed"); consumer .subscribe(&topics.to_vec()) .expect("Can't subscribe to specified topics"); consumer } fn get_schema() -> Schema { let schema = r#"{ "type": "record", "name": "envelope", "fields": [ { "name": "before", "type": [ "null", { "type": "record", "name": "row", "fields": [ {"name": "FirstName", "type": "string"}, {"name": "LastName", "type": "string"} ] } ] }, { "name": "after", "type": [ "null", { "type": "record", "name": "row", "fields": [ {"name": "FirstName", "type": "string"}, {"name": "LastName", "type": "string"} ] } ] } ] }"#; // parse_schema(schema).unwrap() Schema::parse_str(schema).unwrap() } fn serialize() -> Result<Vec<u8>, Error> { let schema = get_schema(); let mut writer = Writer::with_codec(&schema, Vec::new(), Codec::Null); let mut record = Value::Record(vec![ ( "before".to_string(), Value::Union(Box::new(Value::Record(vec![ ("FirstName".to_string(), Value::String("Pink".to_string())), ( "LastName".to_string(), Value::String("Elephants".to_string()), ), ]))), ), ( "after".to_string(), Value::Union(Box::new(Value::Record(vec![ ( "FirstName".to_string(), Value::String("Donnatella".to_string()), ), ("LastName".to_string(), Value::String("Moss".to_string())), ]))), ), ]); writer.append(record)?; writer.flush()?; let input = writer.into_inner(); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); let output = [&body[..], &input[..]].concat(); Ok(output) } fn serialize2() -> Result<Vec<u8>, Error>
]))), ), ]); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let mut body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); encode(&record, &schema, &mut body); Ok(body) } fn deserialize(bytes: &Vec<u8>) -> Result<String, Error> { let schema = get_schema(); let out = match avro_rs::Reader::with_schema(&schema, &bytes[..]) { Ok(reader) => { let value = reader.map(|v| format!("{:?}", v)).collect::<Vec<String>>(); // let value = // avro_rs::from_avro_datum(&schema, &mut bytes.clone(), Some(&schema)); format!("Value: {:?}", value) // format!("{:?}", decode(&schema, &mut s.clone())) } Err(e) => { println!("Reader ERROR: {:?}", e); "".to_string() } }; Ok(out) } #[test] fn serialize_deserialize() { // let schema = get_schema(); // println!("Schema: {:?}", schema); // panic!("forced panic"); let bytes = serialize2().unwrap(); println!( "in bytes: len {:?}, \n {:?}, \n {:?}", bytes.len(), bytes, std::string::String::from_utf8_lossy(&bytes.as_slice()) ); //This is failing by design right now let out = deserialize(&bytes); println!("Out: {:?}", out); panic!("forced panic"); } #[derive(Debug)] pub struct DiffPair { pub before: Option<avro_rs::types::Value>, pub after: Option<avro_rs::types::Value>, } async fn process_message_stream(consumer: &LoggingConsumer) { // let mut buffer = Vec::new(); while true { if let Some(result) = consumer .get_base_consumer() .poll(std::time::Duration::from_millis(500)) { match result { Ok(message) => { println!("Message: {:?}", message); // buffer.clear(); // buffer.extend_from_slice(message.payload().unwrap()); } Err(err) => { println!("Message error: {:?}", err); } } } else { println!("No message found"); } } } fn decode(schema: &Schema, bytes: &mut &[u8]) -> Result<DiffPair, failure::Error> { let mut before = None; let mut after = None; let val = avro_rs::from_avro_datum(&schema, bytes, Some(&schema))?; match val { Value::Record(fields) => { for (name, val) in fields { if name == "before" { before = Some(val); // extract_row(val, iter::once(Datum::Int64(-1)))?; } else if name == "after" { after = Some(val); // extract_row(val, iter::once(Datum::Int64(1)))?; } else { // Intentionally ignore other fields. } } } _ => bail!("avro envelope had unexpected type: {:?}", val), } Ok(DiffPair { before, after }) }
{ let schema = get_schema(); let mut writer = Writer::new(&schema, Vec::new()); let record = Value::Record(vec![ ( "before".to_string(), Value::Union(Box::new(Value::Record(vec![ ("FirstName".to_string(), Value::String("Greg".to_string())), ("LastName".to_string(), Value::String("Berns".to_string())), ]))), ), ( "after".to_string(), Value::Union(Box::new(Value::Record(vec![ ( "FirstName".to_string(), Value::String("Hilbert".to_string()), ), ("LastName".to_string(), Value::String("McDugal".to_string())),
identifier_body
main.rs
use crate::avro_encode::encode; use avro_rs::schema::{RecordField, Schema, SchemaFingerprint, UnionSchema}; use avro_rs::types::Value; use avro_rs::{from_value, types::Record, Codec, Reader, Writer}; use clap::{App, Arg}; use failure::bail; use failure::Error; use futures::StreamExt; use futures_util::future::FutureExt; use log::{info, warn}; use rdkafka::client::ClientContext; use rdkafka::config::{ClientConfig, RDKafkaLogLevel}; use rdkafka::consumer::stream_consumer::{MessageStream, StreamConsumer}; use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, Rebalance}; use rdkafka::error::KafkaResult; use rdkafka::message::OwnedHeaders; use rdkafka::message::{Headers, Message}; use rdkafka::producer::{BaseProducer, BaseRecord, DeliveryResult, ProducerContext}; use rdkafka::producer::{FutureProducer, FutureRecord}; use rdkafka::topic_partition_list::TopicPartitionList; use rdkafka::util::get_rdkafka_version; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::future::Future; use std::thread::sleep; use std::time::Duration; mod avro_encode; struct CustomContext; impl ClientContext for CustomContext {} impl ConsumerContext for CustomContext { fn pre_rebalance(&self, rebalance: &Rebalance) { info!("Pre rebalance {:?}", rebalance); } fn post_rebalance(&self, rebalance: &Rebalance) { info!("Post rebalance {:?}", rebalance); } fn commit_callback(&self, result: KafkaResult<()>, _offsets: &TopicPartitionList) { info!("Committing offsets: {:?}", result); } } type LoggingConsumer = StreamConsumer<CustomContext>; #[tokio::main] async fn
() { let matches = App::new("consumer example") .version(option_env!("CARGO_PKG_VERSION").unwrap_or("")) .about("Simple command line consumer") .arg( Arg::with_name("brokers") .short("b") .long("brokers") .help("Broker list in kafka format") .takes_value(true) .default_value("localhost:9092"), ) .arg( Arg::with_name("group-id") .short("g") .long("group-id") .help("Consumer group id") .takes_value(true) .default_value("example_consumer_group_id"), ) .arg( Arg::with_name("log-conf") .long("log-conf") .help("Configure the logging format (example: 'rdkafka=trace')") .takes_value(true), ) .arg( Arg::with_name("topics") .short("t") .long("topics") .help("Topic list") .takes_value(true) .multiple(true) .required(true), ) .get_matches(); // setup_logger(true, matches.value_of("log-conf")); log4rs::init_file("log4rs.yml", Default::default()) .expect("'log4rs.yml' not found. Required for logging."); // let (version_n, version_s) = get_rdkafka_version(); // info!("rd_kafka_version: 0x{:08x}, {}", version_n, version_s); let brokers = matches.value_of("brokers").unwrap(); let topics = matches.values_of("topics").unwrap().collect::<Vec<&str>>(); let group_id = matches.value_of("group-id").unwrap(); info!("Brokers: ({:?})", brokers); info!("Topics: ({:?})", topics); info!("Group Id: ({:?})", group_id); // This sends over the schema in the payload // let payload = serialize().unwrap(); // publish(brokers, topics[0], &payload).await; // This uses `encode` to send a minimal payload let payload = serialize2().unwrap(); publish(brokers, topics[0], &payload).await; // Code for consumer // let context = CustomContext; // let consumer = get_consumer(context, brokers, group_id, &topics); // process_message_stream(&consumer).await; } async fn publish(brokers: &str, topic_name: &str, payload: &[u8]) { let producer: FutureProducer = ClientConfig::new() .set("bootstrap.servers", brokers) .set("message.timeout.ms", "5000") .create() .expect("Producer creation error"); let res = producer .send( FutureRecord::to(topic_name) .payload(payload) .key(&format!("Key1")) .headers(OwnedHeaders::new().add("header_key", "header_value")), 0, ) .await; info!("Future completed. Result: {:?}", res); } fn get_consumer<'a>( context: CustomContext, brokers: &str, group_id: &str, topics: &[&str], ) -> LoggingConsumer { let consumer: LoggingConsumer = ClientConfig::new() .set("group.id", group_id) .set("bootstrap.servers", brokers) .set("enable.partition.eof", "false") .set("session.timeout.ms", "6000") .set("enable.auto.commit", "true") //.set("statistics.interval.ms", "30000") //.set("auto.offset.reset", "smallest") .set_log_level(RDKafkaLogLevel::Debug) .create_with_context(context) .expect("Consumer creation failed"); consumer .subscribe(&topics.to_vec()) .expect("Can't subscribe to specified topics"); consumer } fn get_schema() -> Schema { let schema = r#"{ "type": "record", "name": "envelope", "fields": [ { "name": "before", "type": [ "null", { "type": "record", "name": "row", "fields": [ {"name": "FirstName", "type": "string"}, {"name": "LastName", "type": "string"} ] } ] }, { "name": "after", "type": [ "null", { "type": "record", "name": "row", "fields": [ {"name": "FirstName", "type": "string"}, {"name": "LastName", "type": "string"} ] } ] } ] }"#; // parse_schema(schema).unwrap() Schema::parse_str(schema).unwrap() } fn serialize() -> Result<Vec<u8>, Error> { let schema = get_schema(); let mut writer = Writer::with_codec(&schema, Vec::new(), Codec::Null); let mut record = Value::Record(vec![ ( "before".to_string(), Value::Union(Box::new(Value::Record(vec![ ("FirstName".to_string(), Value::String("Pink".to_string())), ( "LastName".to_string(), Value::String("Elephants".to_string()), ), ]))), ), ( "after".to_string(), Value::Union(Box::new(Value::Record(vec![ ( "FirstName".to_string(), Value::String("Donnatella".to_string()), ), ("LastName".to_string(), Value::String("Moss".to_string())), ]))), ), ]); writer.append(record)?; writer.flush()?; let input = writer.into_inner(); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); let output = [&body[..], &input[..]].concat(); Ok(output) } fn serialize2() -> Result<Vec<u8>, Error> { let schema = get_schema(); let mut writer = Writer::new(&schema, Vec::new()); let record = Value::Record(vec![ ( "before".to_string(), Value::Union(Box::new(Value::Record(vec![ ("FirstName".to_string(), Value::String("Greg".to_string())), ("LastName".to_string(), Value::String("Berns".to_string())), ]))), ), ( "after".to_string(), Value::Union(Box::new(Value::Record(vec![ ( "FirstName".to_string(), Value::String("Hilbert".to_string()), ), ("LastName".to_string(), Value::String("McDugal".to_string())), ]))), ), ]); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let mut body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); encode(&record, &schema, &mut body); Ok(body) } fn deserialize(bytes: &Vec<u8>) -> Result<String, Error> { let schema = get_schema(); let out = match avro_rs::Reader::with_schema(&schema, &bytes[..]) { Ok(reader) => { let value = reader.map(|v| format!("{:?}", v)).collect::<Vec<String>>(); // let value = // avro_rs::from_avro_datum(&schema, &mut bytes.clone(), Some(&schema)); format!("Value: {:?}", value) // format!("{:?}", decode(&schema, &mut s.clone())) } Err(e) => { println!("Reader ERROR: {:?}", e); "".to_string() } }; Ok(out) } #[test] fn serialize_deserialize() { // let schema = get_schema(); // println!("Schema: {:?}", schema); // panic!("forced panic"); let bytes = serialize2().unwrap(); println!( "in bytes: len {:?}, \n {:?}, \n {:?}", bytes.len(), bytes, std::string::String::from_utf8_lossy(&bytes.as_slice()) ); //This is failing by design right now let out = deserialize(&bytes); println!("Out: {:?}", out); panic!("forced panic"); } #[derive(Debug)] pub struct DiffPair { pub before: Option<avro_rs::types::Value>, pub after: Option<avro_rs::types::Value>, } async fn process_message_stream(consumer: &LoggingConsumer) { // let mut buffer = Vec::new(); while true { if let Some(result) = consumer .get_base_consumer() .poll(std::time::Duration::from_millis(500)) { match result { Ok(message) => { println!("Message: {:?}", message); // buffer.clear(); // buffer.extend_from_slice(message.payload().unwrap()); } Err(err) => { println!("Message error: {:?}", err); } } } else { println!("No message found"); } } } fn decode(schema: &Schema, bytes: &mut &[u8]) -> Result<DiffPair, failure::Error> { let mut before = None; let mut after = None; let val = avro_rs::from_avro_datum(&schema, bytes, Some(&schema))?; match val { Value::Record(fields) => { for (name, val) in fields { if name == "before" { before = Some(val); // extract_row(val, iter::once(Datum::Int64(-1)))?; } else if name == "after" { after = Some(val); // extract_row(val, iter::once(Datum::Int64(1)))?; } else { // Intentionally ignore other fields. } } } _ => bail!("avro envelope had unexpected type: {:?}", val), } Ok(DiffPair { before, after }) }
main
identifier_name
main.rs
use crate::avro_encode::encode; use avro_rs::schema::{RecordField, Schema, SchemaFingerprint, UnionSchema}; use avro_rs::types::Value; use avro_rs::{from_value, types::Record, Codec, Reader, Writer}; use clap::{App, Arg}; use failure::bail; use failure::Error; use futures::StreamExt; use futures_util::future::FutureExt; use log::{info, warn}; use rdkafka::client::ClientContext; use rdkafka::config::{ClientConfig, RDKafkaLogLevel}; use rdkafka::consumer::stream_consumer::{MessageStream, StreamConsumer}; use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, Rebalance}; use rdkafka::error::KafkaResult; use rdkafka::message::OwnedHeaders; use rdkafka::message::{Headers, Message}; use rdkafka::producer::{BaseProducer, BaseRecord, DeliveryResult, ProducerContext}; use rdkafka::producer::{FutureProducer, FutureRecord}; use rdkafka::topic_partition_list::TopicPartitionList; use rdkafka::util::get_rdkafka_version; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::future::Future; use std::thread::sleep; use std::time::Duration; mod avro_encode; struct CustomContext; impl ClientContext for CustomContext {} impl ConsumerContext for CustomContext { fn pre_rebalance(&self, rebalance: &Rebalance) { info!("Pre rebalance {:?}", rebalance); } fn post_rebalance(&self, rebalance: &Rebalance) { info!("Post rebalance {:?}", rebalance); } fn commit_callback(&self, result: KafkaResult<()>, _offsets: &TopicPartitionList) { info!("Committing offsets: {:?}", result); } } type LoggingConsumer = StreamConsumer<CustomContext>; #[tokio::main] async fn main() { let matches = App::new("consumer example") .version(option_env!("CARGO_PKG_VERSION").unwrap_or("")) .about("Simple command line consumer") .arg( Arg::with_name("brokers") .short("b") .long("brokers") .help("Broker list in kafka format") .takes_value(true) .default_value("localhost:9092"), ) .arg( Arg::with_name("group-id") .short("g") .long("group-id") .help("Consumer group id") .takes_value(true) .default_value("example_consumer_group_id"), ) .arg( Arg::with_name("log-conf") .long("log-conf") .help("Configure the logging format (example: 'rdkafka=trace')") .takes_value(true), ) .arg( Arg::with_name("topics") .short("t") .long("topics") .help("Topic list") .takes_value(true) .multiple(true) .required(true), ) .get_matches(); // setup_logger(true, matches.value_of("log-conf")); log4rs::init_file("log4rs.yml", Default::default()) .expect("'log4rs.yml' not found. Required for logging."); // let (version_n, version_s) = get_rdkafka_version(); // info!("rd_kafka_version: 0x{:08x}, {}", version_n, version_s); let brokers = matches.value_of("brokers").unwrap(); let topics = matches.values_of("topics").unwrap().collect::<Vec<&str>>(); let group_id = matches.value_of("group-id").unwrap(); info!("Brokers: ({:?})", brokers); info!("Topics: ({:?})", topics); info!("Group Id: ({:?})", group_id); // This sends over the schema in the payload // let payload = serialize().unwrap(); // publish(brokers, topics[0], &payload).await; // This uses `encode` to send a minimal payload let payload = serialize2().unwrap(); publish(brokers, topics[0], &payload).await; // Code for consumer // let context = CustomContext; // let consumer = get_consumer(context, brokers, group_id, &topics); // process_message_stream(&consumer).await; } async fn publish(brokers: &str, topic_name: &str, payload: &[u8]) { let producer: FutureProducer = ClientConfig::new() .set("bootstrap.servers", brokers) .set("message.timeout.ms", "5000") .create() .expect("Producer creation error"); let res = producer .send( FutureRecord::to(topic_name) .payload(payload) .key(&format!("Key1")) .headers(OwnedHeaders::new().add("header_key", "header_value")), 0, ) .await; info!("Future completed. Result: {:?}", res); } fn get_consumer<'a>( context: CustomContext, brokers: &str, group_id: &str, topics: &[&str], ) -> LoggingConsumer { let consumer: LoggingConsumer = ClientConfig::new() .set("group.id", group_id) .set("bootstrap.servers", brokers) .set("enable.partition.eof", "false") .set("session.timeout.ms", "6000") .set("enable.auto.commit", "true") //.set("statistics.interval.ms", "30000") //.set("auto.offset.reset", "smallest") .set_log_level(RDKafkaLogLevel::Debug) .create_with_context(context) .expect("Consumer creation failed"); consumer .subscribe(&topics.to_vec()) .expect("Can't subscribe to specified topics"); consumer } fn get_schema() -> Schema { let schema = r#"{ "type": "record", "name": "envelope", "fields": [ { "name": "before", "type": [ "null", { "type": "record", "name": "row", "fields": [ {"name": "FirstName", "type": "string"}, {"name": "LastName", "type": "string"} ] } ] }, { "name": "after", "type": [ "null", { "type": "record", "name": "row", "fields": [ {"name": "FirstName", "type": "string"}, {"name": "LastName", "type": "string"} ] } ] } ] }"#; // parse_schema(schema).unwrap() Schema::parse_str(schema).unwrap() } fn serialize() -> Result<Vec<u8>, Error> { let schema = get_schema(); let mut writer = Writer::with_codec(&schema, Vec::new(), Codec::Null); let mut record = Value::Record(vec![ ( "before".to_string(), Value::Union(Box::new(Value::Record(vec![ ("FirstName".to_string(), Value::String("Pink".to_string())), ( "LastName".to_string(), Value::String("Elephants".to_string()), ), ]))), ), ( "after".to_string(), Value::Union(Box::new(Value::Record(vec![ ( "FirstName".to_string(), Value::String("Donnatella".to_string()), ), ("LastName".to_string(), Value::String("Moss".to_string())), ]))), ), ]); writer.append(record)?; writer.flush()?;
let input = writer.into_inner(); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); let output = [&body[..], &input[..]].concat(); Ok(output) } fn serialize2() -> Result<Vec<u8>, Error> { let schema = get_schema(); let mut writer = Writer::new(&schema, Vec::new()); let record = Value::Record(vec![ ( "before".to_string(), Value::Union(Box::new(Value::Record(vec![ ("FirstName".to_string(), Value::String("Greg".to_string())), ("LastName".to_string(), Value::String("Berns".to_string())), ]))), ), ( "after".to_string(), Value::Union(Box::new(Value::Record(vec![ ( "FirstName".to_string(), Value::String("Hilbert".to_string()), ), ("LastName".to_string(), Value::String("McDugal".to_string())), ]))), ), ]); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let mut body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); encode(&record, &schema, &mut body); Ok(body) } fn deserialize(bytes: &Vec<u8>) -> Result<String, Error> { let schema = get_schema(); let out = match avro_rs::Reader::with_schema(&schema, &bytes[..]) { Ok(reader) => { let value = reader.map(|v| format!("{:?}", v)).collect::<Vec<String>>(); // let value = // avro_rs::from_avro_datum(&schema, &mut bytes.clone(), Some(&schema)); format!("Value: {:?}", value) // format!("{:?}", decode(&schema, &mut s.clone())) } Err(e) => { println!("Reader ERROR: {:?}", e); "".to_string() } }; Ok(out) } #[test] fn serialize_deserialize() { // let schema = get_schema(); // println!("Schema: {:?}", schema); // panic!("forced panic"); let bytes = serialize2().unwrap(); println!( "in bytes: len {:?}, \n {:?}, \n {:?}", bytes.len(), bytes, std::string::String::from_utf8_lossy(&bytes.as_slice()) ); //This is failing by design right now let out = deserialize(&bytes); println!("Out: {:?}", out); panic!("forced panic"); } #[derive(Debug)] pub struct DiffPair { pub before: Option<avro_rs::types::Value>, pub after: Option<avro_rs::types::Value>, } async fn process_message_stream(consumer: &LoggingConsumer) { // let mut buffer = Vec::new(); while true { if let Some(result) = consumer .get_base_consumer() .poll(std::time::Duration::from_millis(500)) { match result { Ok(message) => { println!("Message: {:?}", message); // buffer.clear(); // buffer.extend_from_slice(message.payload().unwrap()); } Err(err) => { println!("Message error: {:?}", err); } } } else { println!("No message found"); } } } fn decode(schema: &Schema, bytes: &mut &[u8]) -> Result<DiffPair, failure::Error> { let mut before = None; let mut after = None; let val = avro_rs::from_avro_datum(&schema, bytes, Some(&schema))?; match val { Value::Record(fields) => { for (name, val) in fields { if name == "before" { before = Some(val); // extract_row(val, iter::once(Datum::Int64(-1)))?; } else if name == "after" { after = Some(val); // extract_row(val, iter::once(Datum::Int64(1)))?; } else { // Intentionally ignore other fields. } } } _ => bail!("avro envelope had unexpected type: {:?}", val), } Ok(DiffPair { before, after }) }
random_line_split
cogroup.rs
//! Group records by a key, and apply a reduction function. //! //! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records //! with the same key, and apply user supplied functions to the key and a list of values, which are //! expected to populate a list of output values. //! //! Several variants of `group` exist which allow more precise control over how grouping is done. //! For example, the `_by` suffixed variants take arbitrary data, but require a key-value selector //! to be applied to each record. The `_u` suffixed variants use unsigned integers as keys, and //! will use a dense array rather than a `HashMap` to store their keys. //! //! The list of values are presented as an iterator which internally merges sorted lists of values. //! This ordering can be exploited in several cases to avoid computation when only the first few //! elements are required. //! //! #Examples //! //! This example groups a stream of `(key,val)` pairs by `key`, and yields only the most frequently //! occurring value for each key. //! //! ```ignore //! stream.group(|key, vals, output| { //! let (mut max_val, mut max_wgt) = vals.peek().unwrap(); //! for (val, wgt) in vals { //! if wgt > max_wgt { //! max_wgt = wgt; //! max_val = val; //! } //! } //! output.push((max_val.clone(), max_wgt)); //! }) //! ``` use std::rc::Rc; use std::default::Default; use std::hash::Hasher; use std::ops::DerefMut; use itertools::Itertools; use ::{Collection, Data}; use timely::dataflow::*; use timely::dataflow::operators::{Map, Binary}; use timely::dataflow::channels::pact::Exchange; use timely_sort::{LSBRadixSorter, Unsigned}; use collection::{LeastUpperBound, Lookup, Trace, Offset}; use collection::trace::{CollectionIterator, DifferenceIterator, Traceable}; use iterators::coalesce::Coalesce; use collection::compact::Compact; /// Extension trait for the `group_by` and `group_by_u` differential dataflow methods. pub trait CoGroupBy<G: Scope, K: Data, V1: Data> where G::Timestamp: LeastUpperBound { /// A primitive binary version of `group_by`, which acts on a `Collection<G, (K, V1)>` and a `Collection<G, (K, V2)>`. /// /// The two streams must already be key-value pairs, which is too bad. Also, in addition to the /// normal arguments (another stream, a hash for the key, a reduction function, and per-key logic), /// the user must specify a function implmenting `Fn(u64) -> Look`, where `Look: Lookup<K, Offset>` is something you shouldn't have to know about yet. /// The right thing to use here, for the moment, is `|_| HashMap::new()`. /// /// There are better options if you know your key is an unsigned integer, namely `|x| (Vec::new(), x)`. fn cogroup_by_inner< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<DifferenceIterator<V1>>, &mut CollectionIterator<DifferenceIterator<V2>>, &mut Vec<(V3, i32)>)+'static, Reduc: Fn(&K, &V3)->D+'static, > (&self, other: &Collection<G, (K, V2)>, key_h: KH, reduc: Reduc, look: LookG, logic: Logic) -> Collection<G, D>; } impl<G: Scope, K: Data, V1: Data> CoGroupBy<G, K, V1> for Collection<G, (K, V1)> where G::Timestamp: LeastUpperBound { fn cogroup_by_inner< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<V1>, &mut CollectionIterator<V2>, &mut Vec<(V3, i32)>)+'static, Reduc: Fn(&K, &V3)->D+'static, > (&self, other: &Collection<G, (K, V2)>, key_h: KH, reduc: Reduc, look: LookG, logic: Logic) -> Collection<G, D> { let mut source1 = Trace::new(look(0)); let mut source2 = Trace::new(look(0)); let mut result = Trace::new(look(0)); // A map from times to received (key, val, wgt) triples. let mut inputs1 = Vec::new(); let mut inputs2 = Vec::new(); // A map from times to a list of keys that need processing at that time. let mut to_do = Vec::new(); // temporary storage for operator implementations to populate let mut buffer = vec![]; let key_h = Rc::new(key_h); let key_1 = key_h.clone(); let key_2 = key_h.clone(); // create an exchange channel based on the supplied Fn(&D1)->u64. let exch1 = Exchange::new(move |&((ref k, _),_)| key_1(k).as_u64()); let exch2 = Exchange::new(move |&((ref k, _),_)| key_2(k).as_u64()); let mut sorter1 = LSBRadixSorter::new(); let mut sorter2 = LSBRadixSorter::new(); // fabricate a data-parallel operator using the `unary_notify` pattern. Collection::new(self.inner.binary_notify(&other.inner, exch1, exch2, "CoGroupBy", vec![], move |input1, input2, output, notificator| { // 1. read each input, and stash it in our staging area while let Some((time, data)) = input1.next() { inputs1.entry_or_insert(time.time(), || Vec::new()) .push(::std::mem::replace(data.deref_mut(), Vec::new())); notificator.notify_at(time); } // 1. read each input, and stash it in our staging area while let Some((time, data)) = input2.next() { inputs2.entry_or_insert(time.time(), || Vec::new()) .push(::std::mem::replace(data.deref_mut(), Vec::new())); notificator.notify_at(time); } // 2. go through each time of interest that has reached completion // times are interesting either because we received data, or because we conclude // in the processing of a time that a future time will be interesting. while let Some((index, _count)) = notificator.next() { let mut stash = Vec::new(); panic!("interesting times needs to do LUB of union of times for each key, input"); // 2a. fetch any data associated with this time. if let Some(mut queue) = inputs1.remove_key(&index) { // sort things; radix if many,.sort_by if few. let compact = if queue.len() > 1 { for element in queue.into_iter() { sorter1.extend(element.into_iter(), &|x| key_h(&(x.0).0)); } let mut sorted = sorter1.finish(&|x| key_h(&(x.0).0)); let result = Compact::from_radix(&mut sorted, &|k| key_h(k)); sorted.truncate(256); sorter1.recycle(sorted); result } else { let mut vec = queue.pop().unwrap(); let mut vec = vec.drain(..).collect::<Vec<_>>(); vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) }; if let Some(compact) = compact { for key in &compact.keys { stash.push(index.clone()); source1.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clone(), || { notificator.notify_at(index.delayed(time)); Vec::new() }); queue.push((*key).clone()); } stash.clear(); } source1.set_difference(index.time(), compact); } } // 2a. fetch any data associated with this time. if let Some(mut queue) = inputs2.remove_key(&index) { // sort things; radix if many,.sort_by if few. let compact = if queue.len() > 1 { for element in queue.into_iter() { sorter2.extend(element.into_iter(), &|x| key_h(&(x.0).0)); } let mut sorted = sorter2.finish(&|x| key_h(&(x.0).0)); let result = Compact::from_radix(&mut sorted, &|k| key_h(k)); sorted.truncate(256); sorter2.recycle(sorted); result } else { let mut vec = queue.pop().unwrap(); let mut vec = vec.drain(..).collect::<Vec<_>>(); vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) }; if let Some(compact) = compact
} // we may need to produce output at index let mut session = output.session(&index); // 2b. We must now determine for each interesting key at this time, how does the // currently reported output match up with what we need as output. Should we send // more output differences, and what are they? // Much of this logic used to hide in `OperatorTrace` and `CollectionTrace`. // They are now gone and simpler, respectively. if let Some(mut keys) = to_do.remove_key(&index) { // we would like these keys in a particular order. // TODO : use a radix sort since we have `key_h`. keys.sort_by(|x,y| (key_h(&x), x).cmp(&(key_h(&y), y))); keys.dedup(); // accumulations for installation into result let mut accumulation = Compact::new(0,0); for key in keys { // acquire an iterator over the collection at `time`. let mut input1 = source1.get_collection(&key, &index); let mut input2 = source2.get_collection(&key, &index); // if we have some data, invoke logic to populate self.dst if input1.peek().is_some() || input2.peek().is_some() { logic(&key, &mut input1, &mut input2, &mut buffer); } buffer.sort_by(|x,y| x.0.cmp(&y.0)); // push differences in to Compact. let mut compact = accumulation.session(); for (val, wgt) in Coalesce::coalesce(result.get_collection(&key, &index) .map(|(v, w)| (v,-w)) .merge_by(buffer.iter().map(|&(ref v, w)| (v, w)), |x,y| { x.0 <= y.0 })) { session.give((reduc(&key, val), wgt)); compact.push(val.clone(), wgt); } compact.done(key); buffer.clear(); } if accumulation.vals.len() > 0 { // println!("group2"); result.set_difference(index.time(), accumulation); } } } })) } }
{ for key in &compact.keys { stash.push(index.clone()); source2.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clone(), || { notificator.notify_at(index.delayed(time)); Vec::new() }); queue.push((*key).clone()); } stash.clear(); } source2.set_difference(index.time(), compact); }
conditional_block
cogroup.rs
//! Group records by a key, and apply a reduction function. //! //! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records //! with the same key, and apply user supplied functions to the key and a list of values, which are //! expected to populate a list of output values. //! //! Several variants of `group` exist which allow more precise control over how grouping is done. //! For example, the `_by` suffixed variants take arbitrary data, but require a key-value selector //! to be applied to each record. The `_u` suffixed variants use unsigned integers as keys, and //! will use a dense array rather than a `HashMap` to store their keys. //! //! The list of values are presented as an iterator which internally merges sorted lists of values. //! This ordering can be exploited in several cases to avoid computation when only the first few //! elements are required. //! //! #Examples //! //! This example groups a stream of `(key,val)` pairs by `key`, and yields only the most frequently //! occurring value for each key. //! //! ```ignore //! stream.group(|key, vals, output| { //! let (mut max_val, mut max_wgt) = vals.peek().unwrap(); //! for (val, wgt) in vals { //! if wgt > max_wgt { //! max_wgt = wgt; //! max_val = val; //! } //! } //! output.push((max_val.clone(), max_wgt)); //! }) //! ``` use std::rc::Rc; use std::default::Default; use std::hash::Hasher; use std::ops::DerefMut; use itertools::Itertools; use ::{Collection, Data}; use timely::dataflow::*; use timely::dataflow::operators::{Map, Binary}; use timely::dataflow::channels::pact::Exchange; use timely_sort::{LSBRadixSorter, Unsigned}; use collection::{LeastUpperBound, Lookup, Trace, Offset}; use collection::trace::{CollectionIterator, DifferenceIterator, Traceable}; use iterators::coalesce::Coalesce; use collection::compact::Compact; /// Extension trait for the `group_by` and `group_by_u` differential dataflow methods. pub trait CoGroupBy<G: Scope, K: Data, V1: Data> where G::Timestamp: LeastUpperBound { /// A primitive binary version of `group_by`, which acts on a `Collection<G, (K, V1)>` and a `Collection<G, (K, V2)>`. /// /// The two streams must already be key-value pairs, which is too bad. Also, in addition to the /// normal arguments (another stream, a hash for the key, a reduction function, and per-key logic), /// the user must specify a function implmenting `Fn(u64) -> Look`, where `Look: Lookup<K, Offset>` is something you shouldn't have to know about yet. /// The right thing to use here, for the moment, is `|_| HashMap::new()`. /// /// There are better options if you know your key is an unsigned integer, namely `|x| (Vec::new(), x)`. fn cogroup_by_inner< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<DifferenceIterator<V1>>, &mut CollectionIterator<DifferenceIterator<V2>>, &mut Vec<(V3, i32)>)+'static, Reduc: Fn(&K, &V3)->D+'static, > (&self, other: &Collection<G, (K, V2)>, key_h: KH, reduc: Reduc, look: LookG, logic: Logic) -> Collection<G, D>; } impl<G: Scope, K: Data, V1: Data> CoGroupBy<G, K, V1> for Collection<G, (K, V1)> where G::Timestamp: LeastUpperBound { fn cogroup_by_inner< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<V1>, &mut CollectionIterator<V2>, &mut Vec<(V3, i32)>)+'static, Reduc: Fn(&K, &V3)->D+'static, > (&self, other: &Collection<G, (K, V2)>, key_h: KH, reduc: Reduc, look: LookG, logic: Logic) -> Collection<G, D> { let mut source1 = Trace::new(look(0)); let mut source2 = Trace::new(look(0)); let mut result = Trace::new(look(0)); // A map from times to received (key, val, wgt) triples. let mut inputs1 = Vec::new(); let mut inputs2 = Vec::new(); // A map from times to a list of keys that need processing at that time. let mut to_do = Vec::new(); // temporary storage for operator implementations to populate let mut buffer = vec![]; let key_h = Rc::new(key_h); let key_1 = key_h.clone(); let key_2 = key_h.clone(); // create an exchange channel based on the supplied Fn(&D1)->u64. let exch1 = Exchange::new(move |&((ref k, _),_)| key_1(k).as_u64()); let exch2 = Exchange::new(move |&((ref k, _),_)| key_2(k).as_u64()); let mut sorter1 = LSBRadixSorter::new(); let mut sorter2 = LSBRadixSorter::new(); // fabricate a data-parallel operator using the `unary_notify` pattern. Collection::new(self.inner.binary_notify(&other.inner, exch1, exch2, "CoGroupBy", vec![], move |input1, input2, output, notificator| { // 1. read each input, and stash it in our staging area while let Some((time, data)) = input1.next() { inputs1.entry_or_insert(time.time(), || Vec::new()) .push(::std::mem::replace(data.deref_mut(), Vec::new())); notificator.notify_at(time); } // 1. read each input, and stash it in our staging area while let Some((time, data)) = input2.next() { inputs2.entry_or_insert(time.time(), || Vec::new()) .push(::std::mem::replace(data.deref_mut(), Vec::new())); notificator.notify_at(time); } // 2. go through each time of interest that has reached completion // times are interesting either because we received data, or because we conclude // in the processing of a time that a future time will be interesting. while let Some((index, _count)) = notificator.next() { let mut stash = Vec::new(); panic!("interesting times needs to do LUB of union of times for each key, input"); // 2a. fetch any data associated with this time. if let Some(mut queue) = inputs1.remove_key(&index) { // sort things; radix if many,.sort_by if few. let compact = if queue.len() > 1 { for element in queue.into_iter() { sorter1.extend(element.into_iter(), &|x| key_h(&(x.0).0)); } let mut sorted = sorter1.finish(&|x| key_h(&(x.0).0)); let result = Compact::from_radix(&mut sorted, &|k| key_h(k)); sorted.truncate(256); sorter1.recycle(sorted); result } else { let mut vec = queue.pop().unwrap(); let mut vec = vec.drain(..).collect::<Vec<_>>(); vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) }; if let Some(compact) = compact { for key in &compact.keys { stash.push(index.clone()); source1.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clone(), || { notificator.notify_at(index.delayed(time)); Vec::new() }); queue.push((*key).clone()); } stash.clear(); } source1.set_difference(index.time(), compact); } } // 2a. fetch any data associated with this time. if let Some(mut queue) = inputs2.remove_key(&index) { // sort things; radix if many,.sort_by if few. let compact = if queue.len() > 1 { for element in queue.into_iter() { sorter2.extend(element.into_iter(), &|x| key_h(&(x.0).0)); } let mut sorted = sorter2.finish(&|x| key_h(&(x.0).0)); let result = Compact::from_radix(&mut sorted, &|k| key_h(k)); sorted.truncate(256); sorter2.recycle(sorted); result } else { let mut vec = queue.pop().unwrap(); let mut vec = vec.drain(..).collect::<Vec<_>>();
if let Some(compact) = compact { for key in &compact.keys { stash.push(index.clone()); source2.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clone(), || { notificator.notify_at(index.delayed(time)); Vec::new() }); queue.push((*key).clone()); } stash.clear(); } source2.set_difference(index.time(), compact); } } // we may need to produce output at index let mut session = output.session(&index); // 2b. We must now determine for each interesting key at this time, how does the // currently reported output match up with what we need as output. Should we send // more output differences, and what are they? // Much of this logic used to hide in `OperatorTrace` and `CollectionTrace`. // They are now gone and simpler, respectively. if let Some(mut keys) = to_do.remove_key(&index) { // we would like these keys in a particular order. // TODO : use a radix sort since we have `key_h`. keys.sort_by(|x,y| (key_h(&x), x).cmp(&(key_h(&y), y))); keys.dedup(); // accumulations for installation into result let mut accumulation = Compact::new(0,0); for key in keys { // acquire an iterator over the collection at `time`. let mut input1 = source1.get_collection(&key, &index); let mut input2 = source2.get_collection(&key, &index); // if we have some data, invoke logic to populate self.dst if input1.peek().is_some() || input2.peek().is_some() { logic(&key, &mut input1, &mut input2, &mut buffer); } buffer.sort_by(|x,y| x.0.cmp(&y.0)); // push differences in to Compact. let mut compact = accumulation.session(); for (val, wgt) in Coalesce::coalesce(result.get_collection(&key, &index) .map(|(v, w)| (v,-w)) .merge_by(buffer.iter().map(|&(ref v, w)| (v, w)), |x,y| { x.0 <= y.0 })) { session.give((reduc(&key, val), wgt)); compact.push(val.clone(), wgt); } compact.done(key); buffer.clear(); } if accumulation.vals.len() > 0 { // println!("group2"); result.set_difference(index.time(), accumulation); } } } })) } }
vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) };
random_line_split
cogroup.rs
//! Group records by a key, and apply a reduction function. //! //! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records //! with the same key, and apply user supplied functions to the key and a list of values, which are //! expected to populate a list of output values. //! //! Several variants of `group` exist which allow more precise control over how grouping is done. //! For example, the `_by` suffixed variants take arbitrary data, but require a key-value selector //! to be applied to each record. The `_u` suffixed variants use unsigned integers as keys, and //! will use a dense array rather than a `HashMap` to store their keys. //! //! The list of values are presented as an iterator which internally merges sorted lists of values. //! This ordering can be exploited in several cases to avoid computation when only the first few //! elements are required. //! //! #Examples //! //! This example groups a stream of `(key,val)` pairs by `key`, and yields only the most frequently //! occurring value for each key. //! //! ```ignore //! stream.group(|key, vals, output| { //! let (mut max_val, mut max_wgt) = vals.peek().unwrap(); //! for (val, wgt) in vals { //! if wgt > max_wgt { //! max_wgt = wgt; //! max_val = val; //! } //! } //! output.push((max_val.clone(), max_wgt)); //! }) //! ``` use std::rc::Rc; use std::default::Default; use std::hash::Hasher; use std::ops::DerefMut; use itertools::Itertools; use ::{Collection, Data}; use timely::dataflow::*; use timely::dataflow::operators::{Map, Binary}; use timely::dataflow::channels::pact::Exchange; use timely_sort::{LSBRadixSorter, Unsigned}; use collection::{LeastUpperBound, Lookup, Trace, Offset}; use collection::trace::{CollectionIterator, DifferenceIterator, Traceable}; use iterators::coalesce::Coalesce; use collection::compact::Compact; /// Extension trait for the `group_by` and `group_by_u` differential dataflow methods. pub trait CoGroupBy<G: Scope, K: Data, V1: Data> where G::Timestamp: LeastUpperBound { /// A primitive binary version of `group_by`, which acts on a `Collection<G, (K, V1)>` and a `Collection<G, (K, V2)>`. /// /// The two streams must already be key-value pairs, which is too bad. Also, in addition to the /// normal arguments (another stream, a hash for the key, a reduction function, and per-key logic), /// the user must specify a function implmenting `Fn(u64) -> Look`, where `Look: Lookup<K, Offset>` is something you shouldn't have to know about yet. /// The right thing to use here, for the moment, is `|_| HashMap::new()`. /// /// There are better options if you know your key is an unsigned integer, namely `|x| (Vec::new(), x)`. fn cogroup_by_inner< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<DifferenceIterator<V1>>, &mut CollectionIterator<DifferenceIterator<V2>>, &mut Vec<(V3, i32)>)+'static, Reduc: Fn(&K, &V3)->D+'static, > (&self, other: &Collection<G, (K, V2)>, key_h: KH, reduc: Reduc, look: LookG, logic: Logic) -> Collection<G, D>; } impl<G: Scope, K: Data, V1: Data> CoGroupBy<G, K, V1> for Collection<G, (K, V1)> where G::Timestamp: LeastUpperBound { fn
< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<V1>, &mut CollectionIterator<V2>, &mut Vec<(V3, i32)>)+'static, Reduc: Fn(&K, &V3)->D+'static, > (&self, other: &Collection<G, (K, V2)>, key_h: KH, reduc: Reduc, look: LookG, logic: Logic) -> Collection<G, D> { let mut source1 = Trace::new(look(0)); let mut source2 = Trace::new(look(0)); let mut result = Trace::new(look(0)); // A map from times to received (key, val, wgt) triples. let mut inputs1 = Vec::new(); let mut inputs2 = Vec::new(); // A map from times to a list of keys that need processing at that time. let mut to_do = Vec::new(); // temporary storage for operator implementations to populate let mut buffer = vec![]; let key_h = Rc::new(key_h); let key_1 = key_h.clone(); let key_2 = key_h.clone(); // create an exchange channel based on the supplied Fn(&D1)->u64. let exch1 = Exchange::new(move |&((ref k, _),_)| key_1(k).as_u64()); let exch2 = Exchange::new(move |&((ref k, _),_)| key_2(k).as_u64()); let mut sorter1 = LSBRadixSorter::new(); let mut sorter2 = LSBRadixSorter::new(); // fabricate a data-parallel operator using the `unary_notify` pattern. Collection::new(self.inner.binary_notify(&other.inner, exch1, exch2, "CoGroupBy", vec![], move |input1, input2, output, notificator| { // 1. read each input, and stash it in our staging area while let Some((time, data)) = input1.next() { inputs1.entry_or_insert(time.time(), || Vec::new()) .push(::std::mem::replace(data.deref_mut(), Vec::new())); notificator.notify_at(time); } // 1. read each input, and stash it in our staging area while let Some((time, data)) = input2.next() { inputs2.entry_or_insert(time.time(), || Vec::new()) .push(::std::mem::replace(data.deref_mut(), Vec::new())); notificator.notify_at(time); } // 2. go through each time of interest that has reached completion // times are interesting either because we received data, or because we conclude // in the processing of a time that a future time will be interesting. while let Some((index, _count)) = notificator.next() { let mut stash = Vec::new(); panic!("interesting times needs to do LUB of union of times for each key, input"); // 2a. fetch any data associated with this time. if let Some(mut queue) = inputs1.remove_key(&index) { // sort things; radix if many,.sort_by if few. let compact = if queue.len() > 1 { for element in queue.into_iter() { sorter1.extend(element.into_iter(), &|x| key_h(&(x.0).0)); } let mut sorted = sorter1.finish(&|x| key_h(&(x.0).0)); let result = Compact::from_radix(&mut sorted, &|k| key_h(k)); sorted.truncate(256); sorter1.recycle(sorted); result } else { let mut vec = queue.pop().unwrap(); let mut vec = vec.drain(..).collect::<Vec<_>>(); vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) }; if let Some(compact) = compact { for key in &compact.keys { stash.push(index.clone()); source1.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clone(), || { notificator.notify_at(index.delayed(time)); Vec::new() }); queue.push((*key).clone()); } stash.clear(); } source1.set_difference(index.time(), compact); } } // 2a. fetch any data associated with this time. if let Some(mut queue) = inputs2.remove_key(&index) { // sort things; radix if many,.sort_by if few. let compact = if queue.len() > 1 { for element in queue.into_iter() { sorter2.extend(element.into_iter(), &|x| key_h(&(x.0).0)); } let mut sorted = sorter2.finish(&|x| key_h(&(x.0).0)); let result = Compact::from_radix(&mut sorted, &|k| key_h(k)); sorted.truncate(256); sorter2.recycle(sorted); result } else { let mut vec = queue.pop().unwrap(); let mut vec = vec.drain(..).collect::<Vec<_>>(); vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) }; if let Some(compact) = compact { for key in &compact.keys { stash.push(index.clone()); source2.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clone(), || { notificator.notify_at(index.delayed(time)); Vec::new() }); queue.push((*key).clone()); } stash.clear(); } source2.set_difference(index.time(), compact); } } // we may need to produce output at index let mut session = output.session(&index); // 2b. We must now determine for each interesting key at this time, how does the // currently reported output match up with what we need as output. Should we send // more output differences, and what are they? // Much of this logic used to hide in `OperatorTrace` and `CollectionTrace`. // They are now gone and simpler, respectively. if let Some(mut keys) = to_do.remove_key(&index) { // we would like these keys in a particular order. // TODO : use a radix sort since we have `key_h`. keys.sort_by(|x,y| (key_h(&x), x).cmp(&(key_h(&y), y))); keys.dedup(); // accumulations for installation into result let mut accumulation = Compact::new(0,0); for key in keys { // acquire an iterator over the collection at `time`. let mut input1 = source1.get_collection(&key, &index); let mut input2 = source2.get_collection(&key, &index); // if we have some data, invoke logic to populate self.dst if input1.peek().is_some() || input2.peek().is_some() { logic(&key, &mut input1, &mut input2, &mut buffer); } buffer.sort_by(|x,y| x.0.cmp(&y.0)); // push differences in to Compact. let mut compact = accumulation.session(); for (val, wgt) in Coalesce::coalesce(result.get_collection(&key, &index) .map(|(v, w)| (v,-w)) .merge_by(buffer.iter().map(|&(ref v, w)| (v, w)), |x,y| { x.0 <= y.0 })) { session.give((reduc(&key, val), wgt)); compact.push(val.clone(), wgt); } compact.done(key); buffer.clear(); } if accumulation.vals.len() > 0 { // println!("group2"); result.set_difference(index.time(), accumulation); } } } })) } }
cogroup_by_inner
identifier_name
cogroup.rs
//! Group records by a key, and apply a reduction function. //! //! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records //! with the same key, and apply user supplied functions to the key and a list of values, which are //! expected to populate a list of output values. //! //! Several variants of `group` exist which allow more precise control over how grouping is done. //! For example, the `_by` suffixed variants take arbitrary data, but require a key-value selector //! to be applied to each record. The `_u` suffixed variants use unsigned integers as keys, and //! will use a dense array rather than a `HashMap` to store their keys. //! //! The list of values are presented as an iterator which internally merges sorted lists of values. //! This ordering can be exploited in several cases to avoid computation when only the first few //! elements are required. //! //! #Examples //! //! This example groups a stream of `(key,val)` pairs by `key`, and yields only the most frequently //! occurring value for each key. //! //! ```ignore //! stream.group(|key, vals, output| { //! let (mut max_val, mut max_wgt) = vals.peek().unwrap(); //! for (val, wgt) in vals { //! if wgt > max_wgt { //! max_wgt = wgt; //! max_val = val; //! } //! } //! output.push((max_val.clone(), max_wgt)); //! }) //! ``` use std::rc::Rc; use std::default::Default; use std::hash::Hasher; use std::ops::DerefMut; use itertools::Itertools; use ::{Collection, Data}; use timely::dataflow::*; use timely::dataflow::operators::{Map, Binary}; use timely::dataflow::channels::pact::Exchange; use timely_sort::{LSBRadixSorter, Unsigned}; use collection::{LeastUpperBound, Lookup, Trace, Offset}; use collection::trace::{CollectionIterator, DifferenceIterator, Traceable}; use iterators::coalesce::Coalesce; use collection::compact::Compact; /// Extension trait for the `group_by` and `group_by_u` differential dataflow methods. pub trait CoGroupBy<G: Scope, K: Data, V1: Data> where G::Timestamp: LeastUpperBound { /// A primitive binary version of `group_by`, which acts on a `Collection<G, (K, V1)>` and a `Collection<G, (K, V2)>`. /// /// The two streams must already be key-value pairs, which is too bad. Also, in addition to the /// normal arguments (another stream, a hash for the key, a reduction function, and per-key logic), /// the user must specify a function implmenting `Fn(u64) -> Look`, where `Look: Lookup<K, Offset>` is something you shouldn't have to know about yet. /// The right thing to use here, for the moment, is `|_| HashMap::new()`. /// /// There are better options if you know your key is an unsigned integer, namely `|x| (Vec::new(), x)`. fn cogroup_by_inner< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<DifferenceIterator<V1>>, &mut CollectionIterator<DifferenceIterator<V2>>, &mut Vec<(V3, i32)>)+'static, Reduc: Fn(&K, &V3)->D+'static, > (&self, other: &Collection<G, (K, V2)>, key_h: KH, reduc: Reduc, look: LookG, logic: Logic) -> Collection<G, D>; } impl<G: Scope, K: Data, V1: Data> CoGroupBy<G, K, V1> for Collection<G, (K, V1)> where G::Timestamp: LeastUpperBound { fn cogroup_by_inner< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<V1>, &mut CollectionIterator<V2>, &mut Vec<(V3, i32)>)+'static, Reduc: Fn(&K, &V3)->D+'static, > (&self, other: &Collection<G, (K, V2)>, key_h: KH, reduc: Reduc, look: LookG, logic: Logic) -> Collection<G, D>
// create an exchange channel based on the supplied Fn(&D1)->u64. let exch1 = Exchange::new(move |&((ref k, _),_)| key_1(k).as_u64()); let exch2 = Exchange::new(move |&((ref k, _),_)| key_2(k).as_u64()); let mut sorter1 = LSBRadixSorter::new(); let mut sorter2 = LSBRadixSorter::new(); // fabricate a data-parallel operator using the `unary_notify` pattern. Collection::new(self.inner.binary_notify(&other.inner, exch1, exch2, "CoGroupBy", vec![], move |input1, input2, output, notificator| { // 1. read each input, and stash it in our staging area while let Some((time, data)) = input1.next() { inputs1.entry_or_insert(time.time(), || Vec::new()) .push(::std::mem::replace(data.deref_mut(), Vec::new())); notificator.notify_at(time); } // 1. read each input, and stash it in our staging area while let Some((time, data)) = input2.next() { inputs2.entry_or_insert(time.time(), || Vec::new()) .push(::std::mem::replace(data.deref_mut(), Vec::new())); notificator.notify_at(time); } // 2. go through each time of interest that has reached completion // times are interesting either because we received data, or because we conclude // in the processing of a time that a future time will be interesting. while let Some((index, _count)) = notificator.next() { let mut stash = Vec::new(); panic!("interesting times needs to do LUB of union of times for each key, input"); // 2a. fetch any data associated with this time. if let Some(mut queue) = inputs1.remove_key(&index) { // sort things; radix if many,.sort_by if few. let compact = if queue.len() > 1 { for element in queue.into_iter() { sorter1.extend(element.into_iter(), &|x| key_h(&(x.0).0)); } let mut sorted = sorter1.finish(&|x| key_h(&(x.0).0)); let result = Compact::from_radix(&mut sorted, &|k| key_h(k)); sorted.truncate(256); sorter1.recycle(sorted); result } else { let mut vec = queue.pop().unwrap(); let mut vec = vec.drain(..).collect::<Vec<_>>(); vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) }; if let Some(compact) = compact { for key in &compact.keys { stash.push(index.clone()); source1.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clone(), || { notificator.notify_at(index.delayed(time)); Vec::new() }); queue.push((*key).clone()); } stash.clear(); } source1.set_difference(index.time(), compact); } } // 2a. fetch any data associated with this time. if let Some(mut queue) = inputs2.remove_key(&index) { // sort things; radix if many,.sort_by if few. let compact = if queue.len() > 1 { for element in queue.into_iter() { sorter2.extend(element.into_iter(), &|x| key_h(&(x.0).0)); } let mut sorted = sorter2.finish(&|x| key_h(&(x.0).0)); let result = Compact::from_radix(&mut sorted, &|k| key_h(k)); sorted.truncate(256); sorter2.recycle(sorted); result } else { let mut vec = queue.pop().unwrap(); let mut vec = vec.drain(..).collect::<Vec<_>>(); vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) }; if let Some(compact) = compact { for key in &compact.keys { stash.push(index.clone()); source2.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clone(), || { notificator.notify_at(index.delayed(time)); Vec::new() }); queue.push((*key).clone()); } stash.clear(); } source2.set_difference(index.time(), compact); } } // we may need to produce output at index let mut session = output.session(&index); // 2b. We must now determine for each interesting key at this time, how does the // currently reported output match up with what we need as output. Should we send // more output differences, and what are they? // Much of this logic used to hide in `OperatorTrace` and `CollectionTrace`. // They are now gone and simpler, respectively. if let Some(mut keys) = to_do.remove_key(&index) { // we would like these keys in a particular order. // TODO : use a radix sort since we have `key_h`. keys.sort_by(|x,y| (key_h(&x), x).cmp(&(key_h(&y), y))); keys.dedup(); // accumulations for installation into result let mut accumulation = Compact::new(0,0); for key in keys { // acquire an iterator over the collection at `time`. let mut input1 = source1.get_collection(&key, &index); let mut input2 = source2.get_collection(&key, &index); // if we have some data, invoke logic to populate self.dst if input1.peek().is_some() || input2.peek().is_some() { logic(&key, &mut input1, &mut input2, &mut buffer); } buffer.sort_by(|x,y| x.0.cmp(&y.0)); // push differences in to Compact. let mut compact = accumulation.session(); for (val, wgt) in Coalesce::coalesce(result.get_collection(&key, &index) .map(|(v, w)| (v,-w)) .merge_by(buffer.iter().map(|&(ref v, w)| (v, w)), |x,y| { x.0 <= y.0 })) { session.give((reduc(&key, val), wgt)); compact.push(val.clone(), wgt); } compact.done(key); buffer.clear(); } if accumulation.vals.len() > 0 { // println!("group2"); result.set_difference(index.time(), accumulation); } } } })) } }
{ let mut source1 = Trace::new(look(0)); let mut source2 = Trace::new(look(0)); let mut result = Trace::new(look(0)); // A map from times to received (key, val, wgt) triples. let mut inputs1 = Vec::new(); let mut inputs2 = Vec::new(); // A map from times to a list of keys that need processing at that time. let mut to_do = Vec::new(); // temporary storage for operator implementations to populate let mut buffer = vec![]; let key_h = Rc::new(key_h); let key_1 = key_h.clone(); let key_2 = key_h.clone();
identifier_body
mod.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::io; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use std::mem::size_of; use std::os::unix::io::AsRawFd; use std::ptr::null_mut; use std::result; use kvm_bindings::kvm_run; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use kvm_bindings::{kvm_cpuid2, kvm_cpuid_entry2}; /// Wrappers over KVM device ioctls. pub mod device; /// Wrappers over KVM system ioctls. pub mod system; /// Wrappers over KVM VCPU ioctls. pub mod vcpu; /// Wrappers over KVM Virtual Machine ioctls. pub mod vm; /// A specialized `Result` type for KVM ioctls. /// /// This typedef is generally used to avoid writing out io::Error directly and /// is otherwise a direct mapping to Result. pub type Result<T> = result::Result<T, io::Error>; // Returns a `Vec<T>` with a size in bytes at least as large as `size_in_bytes`. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_with_size_in_bytes<T: Default>(size_in_bytes: usize) -> Vec<T> { let rounded_size = (size_in_bytes + size_of::<T>() - 1) / size_of::<T>(); let mut v = Vec::with_capacity(rounded_size); for _ in 0..rounded_size { v.push(T::default()) } v } // The kvm API has many structs that resemble the following `Foo` structure: // // ``` // #[repr(C)] // struct Foo { // some_data: u32 // entries: __IncompleteArrayField<__u32>, // } // ``` // // In order to allocate such a structure, `size_of::<Foo>()` would be too small because it would not // include any space for `entries`. To make the allocation large enough while still being aligned // for `Foo`, a `Vec<Foo>` is created. Only the first element of `Vec<Foo>` would actually be used // as a `Foo`. The remaining memory in the `Vec<Foo>` is for `entries`, which must be contiguous // with `Foo`. This function is used to make the `Vec<Foo>` with enough space for `count` entries. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_with_array_field<T: Default, F>(count: usize) -> Vec<T> { let element_space = count * size_of::<F>(); let vec_size_bytes = size_of::<T>() + element_space; vec_with_size_in_bytes(vec_size_bytes) } /// Wrapper over the `kvm_cpuid2` structure. /// /// The structure has a zero length array at the end, hidden behind bounds check. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub struct CpuId { // Wrapper over `kvm_cpuid2` from which we only use the first element. kvm_cpuid: Vec<kvm_cpuid2>, // Number of `kvm_cpuid_entry2` structs at the end of kvm_cpuid2. allocated_len: usize, } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl Clone for CpuId { fn clone(&self) -> Self { let mut kvm_cpuid = Vec::with_capacity(self.kvm_cpuid.len()); for _ in 0..self.kvm_cpuid.len() { kvm_cpuid.push(kvm_cpuid2::default()); } let num_bytes = self.kvm_cpuid.len() * size_of::<kvm_cpuid2>(); let src_byte_slice = unsafe { std::slice::from_raw_parts(self.kvm_cpuid.as_ptr() as *const u8, num_bytes) }; let dst_byte_slice = unsafe { std::slice::from_raw_parts_mut(kvm_cpuid.as_mut_ptr() as *mut u8, num_bytes) }; dst_byte_slice.copy_from_slice(src_byte_slice); CpuId { kvm_cpuid, allocated_len: self.allocated_len, } } } #[cfg(test)] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl PartialEq for CpuId { fn eq(&self, other: &CpuId) -> bool { let entries: &[kvm_cpuid_entry2] = unsafe { self.kvm_cpuid[0].entries.as_slice(self.allocated_len) }; let other_entries: &[kvm_cpuid_entry2] = unsafe { self.kvm_cpuid[0].entries.as_slice(other.allocated_len) }; self.allocated_len == other.allocated_len && entries == other_entries } } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl CpuId { /// Creates a new `CpuId` structure that contains at most `array_len` KVM CPUID entries. /// /// # Arguments /// /// * `array_len` - Maximum number of CPUID entries. /// /// # Example /// /// ``` /// use kvm_ioctls::CpuId; /// let cpu_id = CpuId::new(32); /// ``` pub fn new(array_len: usize) -> CpuId { let mut kvm_cpuid = vec_with_array_field::<kvm_cpuid2, kvm_cpuid_entry2>(array_len); kvm_cpuid[0].nent = array_len as u32; CpuId { kvm_cpuid, allocated_len: array_len, } } /// Creates a new `CpuId` structure based on a supplied vector of `kvm_cpuid_entry2`. /// /// # Arguments /// /// * `entries` - The vector of `kvm_cpuid_entry2` entries. /// /// # Example /// /// ```rust /// # extern crate kvm_ioctls; /// extern crate kvm_bindings; /// /// use kvm_bindings::kvm_cpuid_entry2; /// use kvm_ioctls::CpuId; /// // Create a Cpuid to hold one entry. /// let mut cpuid = CpuId::new(1); /// let mut entries = cpuid.mut_entries_slice().to_vec(); /// let new_entry = kvm_cpuid_entry2 { /// function: 0x4, /// index: 0, /// flags: 1, /// eax: 0b1100000, /// ebx: 0, /// ecx: 0, /// edx: 0, /// padding: [0, 0, 0], /// }; /// entries.insert(0, new_entry); /// cpuid = CpuId::from_entries(&entries); /// ``` /// pub fn from_entries(entries: &[kvm_cpuid_entry2]) -> CpuId { let mut kvm_cpuid = vec_with_array_field::<kvm_cpuid2, kvm_cpuid_entry2>(entries.len()); kvm_cpuid[0].nent = entries.len() as u32; unsafe { kvm_cpuid[0] .entries .as_mut_slice(entries.len()) .copy_from_slice(entries); } CpuId { kvm_cpuid, allocated_len: entries.len(), } } /// Returns the mutable entries slice so they can be modified before passing to the VCPU. /// /// # Example /// ```rust /// use kvm_ioctls::{CpuId, Kvm, MAX_KVM_CPUID_ENTRIES}; /// let kvm = Kvm::new().unwrap(); /// let mut cpuid = kvm.get_supported_cpuid(MAX_KVM_CPUID_ENTRIES).unwrap(); /// let cpuid_entries = cpuid.mut_entries_slice(); /// ``` /// pub fn mut_entries_slice(&mut self) -> &mut [kvm_cpuid_entry2] { // Mapping the unsized array to a slice is unsafe because the length isn't known. Using // the length we originally allocated with eliminates the possibility of overflow. if self.kvm_cpuid[0].nent as usize > self.allocated_len { self.kvm_cpuid[0].nent = self.allocated_len as u32; } let nent = self.kvm_cpuid[0].nent as usize; unsafe { self.kvm_cpuid[0].entries.as_mut_slice(nent) } } /// Get a pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn
(&self) -> *const kvm_cpuid2 { &self.kvm_cpuid[0] } /// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_mut_ptr(&mut self) -> *mut kvm_cpuid2 { &mut self.kvm_cpuid[0] } } /// Safe wrapper over the `kvm_run` struct. /// /// The wrapper is needed for sending the pointer to `kvm_run` between /// threads as raw pointers do not implement `Send` and `Sync`. pub struct KvmRunWrapper { kvm_run_ptr: *mut u8, // This field is need so we can `munmap` the memory mapped to hold `kvm_run`. mmap_size: usize, } // Send and Sync aren't automatically inherited for the raw address pointer. // Accessing that pointer is only done through the stateless interface which // allows the object to be shared by multiple threads without a decrease in // safety. unsafe impl Send for KvmRunWrapper {} unsafe impl Sync for KvmRunWrapper {} impl KvmRunWrapper { /// Maps the first `size` bytes of the given `fd`. /// /// # Arguments /// * `fd` - File descriptor to mmap from. /// * `size` - Size of memory region in bytes. pub fn mmap_from_fd(fd: &AsRawFd, size: usize) -> Result<KvmRunWrapper> { // This is safe because we are creating a mapping in a place not already used by any other // area in this process. let addr = unsafe { libc::mmap( null_mut(), size, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_SHARED, fd.as_raw_fd(), 0, ) }; if addr == libc::MAP_FAILED { return Err(io::Error::last_os_error()); } Ok(KvmRunWrapper { kvm_run_ptr: addr as *mut u8, mmap_size: size, }) } /// Returns a mutable reference to `kvm_run`. /// #[allow(clippy::mut_from_ref)] pub fn as_mut_ref(&self) -> &mut kvm_run { // Safe because we know we mapped enough memory to hold the kvm_run struct because the // kernel told us how large it was. #[allow(clippy::cast_ptr_alignment)] unsafe { &mut *(self.kvm_run_ptr as *mut kvm_run) } } } impl Drop for KvmRunWrapper { fn drop(&mut self) { // This is safe because we mmap the area at kvm_run_ptr ourselves, // and nobody else is holding a reference to it. unsafe { libc::munmap(self.kvm_run_ptr as *mut libc::c_void, self.mmap_size); } } } #[cfg(test)] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod tests { use super::*; #[test] fn test_cpuid_from_entries() { let num_entries = 4; let mut cpuid = CpuId::new(num_entries); // add entry let mut entries = cpuid.mut_entries_slice().to_vec(); let new_entry = kvm_cpuid_entry2 { function: 0x4, index: 0, flags: 1, eax: 0b1100000, ebx: 0, ecx: 0, edx: 0, padding: [0, 0, 0], }; entries.insert(0, new_entry); cpuid = CpuId::from_entries(&entries); // check that the cpuid contains the new entry assert_eq!(cpuid.allocated_len, num_entries + 1); assert_eq!(cpuid.kvm_cpuid[0].nent, (num_entries + 1) as u32); assert_eq!(cpuid.mut_entries_slice().len(), num_entries + 1); assert_eq!(cpuid.mut_entries_slice()[0], new_entry); } }
as_ptr
identifier_name
mod.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::io; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use std::mem::size_of; use std::os::unix::io::AsRawFd; use std::ptr::null_mut; use std::result; use kvm_bindings::kvm_run; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use kvm_bindings::{kvm_cpuid2, kvm_cpuid_entry2}; /// Wrappers over KVM device ioctls. pub mod device; /// Wrappers over KVM system ioctls. pub mod system; /// Wrappers over KVM VCPU ioctls. pub mod vcpu; /// Wrappers over KVM Virtual Machine ioctls. pub mod vm; /// A specialized `Result` type for KVM ioctls. /// /// This typedef is generally used to avoid writing out io::Error directly and /// is otherwise a direct mapping to Result. pub type Result<T> = result::Result<T, io::Error>; // Returns a `Vec<T>` with a size in bytes at least as large as `size_in_bytes`. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_with_size_in_bytes<T: Default>(size_in_bytes: usize) -> Vec<T> { let rounded_size = (size_in_bytes + size_of::<T>() - 1) / size_of::<T>(); let mut v = Vec::with_capacity(rounded_size); for _ in 0..rounded_size { v.push(T::default()) } v } // The kvm API has many structs that resemble the following `Foo` structure: // // ``` // #[repr(C)] // struct Foo { // some_data: u32 // entries: __IncompleteArrayField<__u32>, // } // ``` // // In order to allocate such a structure, `size_of::<Foo>()` would be too small because it would not // include any space for `entries`. To make the allocation large enough while still being aligned // for `Foo`, a `Vec<Foo>` is created. Only the first element of `Vec<Foo>` would actually be used // as a `Foo`. The remaining memory in the `Vec<Foo>` is for `entries`, which must be contiguous // with `Foo`. This function is used to make the `Vec<Foo>` with enough space for `count` entries. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_with_array_field<T: Default, F>(count: usize) -> Vec<T> { let element_space = count * size_of::<F>(); let vec_size_bytes = size_of::<T>() + element_space; vec_with_size_in_bytes(vec_size_bytes) } /// Wrapper over the `kvm_cpuid2` structure. /// /// The structure has a zero length array at the end, hidden behind bounds check. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub struct CpuId { // Wrapper over `kvm_cpuid2` from which we only use the first element. kvm_cpuid: Vec<kvm_cpuid2>, // Number of `kvm_cpuid_entry2` structs at the end of kvm_cpuid2. allocated_len: usize, } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl Clone for CpuId { fn clone(&self) -> Self { let mut kvm_cpuid = Vec::with_capacity(self.kvm_cpuid.len()); for _ in 0..self.kvm_cpuid.len() { kvm_cpuid.push(kvm_cpuid2::default()); } let num_bytes = self.kvm_cpuid.len() * size_of::<kvm_cpuid2>(); let src_byte_slice = unsafe { std::slice::from_raw_parts(self.kvm_cpuid.as_ptr() as *const u8, num_bytes) }; let dst_byte_slice = unsafe { std::slice::from_raw_parts_mut(kvm_cpuid.as_mut_ptr() as *mut u8, num_bytes) }; dst_byte_slice.copy_from_slice(src_byte_slice); CpuId { kvm_cpuid, allocated_len: self.allocated_len, } } } #[cfg(test)] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl PartialEq for CpuId { fn eq(&self, other: &CpuId) -> bool { let entries: &[kvm_cpuid_entry2] = unsafe { self.kvm_cpuid[0].entries.as_slice(self.allocated_len) }; let other_entries: &[kvm_cpuid_entry2] = unsafe { self.kvm_cpuid[0].entries.as_slice(other.allocated_len) }; self.allocated_len == other.allocated_len && entries == other_entries } } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl CpuId { /// Creates a new `CpuId` structure that contains at most `array_len` KVM CPUID entries. /// /// # Arguments /// /// * `array_len` - Maximum number of CPUID entries. /// /// # Example /// /// ``` /// use kvm_ioctls::CpuId; /// let cpu_id = CpuId::new(32); /// ``` pub fn new(array_len: usize) -> CpuId { let mut kvm_cpuid = vec_with_array_field::<kvm_cpuid2, kvm_cpuid_entry2>(array_len); kvm_cpuid[0].nent = array_len as u32; CpuId { kvm_cpuid, allocated_len: array_len, } } /// Creates a new `CpuId` structure based on a supplied vector of `kvm_cpuid_entry2`. /// /// # Arguments /// /// * `entries` - The vector of `kvm_cpuid_entry2` entries. /// /// # Example /// /// ```rust /// # extern crate kvm_ioctls; /// extern crate kvm_bindings; /// /// use kvm_bindings::kvm_cpuid_entry2; /// use kvm_ioctls::CpuId; /// // Create a Cpuid to hold one entry. /// let mut cpuid = CpuId::new(1); /// let mut entries = cpuid.mut_entries_slice().to_vec(); /// let new_entry = kvm_cpuid_entry2 { /// function: 0x4, /// index: 0, /// flags: 1, /// eax: 0b1100000, /// ebx: 0, /// ecx: 0, /// edx: 0, /// padding: [0, 0, 0], /// }; /// entries.insert(0, new_entry); /// cpuid = CpuId::from_entries(&entries); /// ``` /// pub fn from_entries(entries: &[kvm_cpuid_entry2]) -> CpuId { let mut kvm_cpuid = vec_with_array_field::<kvm_cpuid2, kvm_cpuid_entry2>(entries.len()); kvm_cpuid[0].nent = entries.len() as u32; unsafe { kvm_cpuid[0] .entries .as_mut_slice(entries.len()) .copy_from_slice(entries); } CpuId { kvm_cpuid, allocated_len: entries.len(), } } /// Returns the mutable entries slice so they can be modified before passing to the VCPU. /// /// # Example /// ```rust /// use kvm_ioctls::{CpuId, Kvm, MAX_KVM_CPUID_ENTRIES}; /// let kvm = Kvm::new().unwrap(); /// let mut cpuid = kvm.get_supported_cpuid(MAX_KVM_CPUID_ENTRIES).unwrap(); /// let cpuid_entries = cpuid.mut_entries_slice(); /// ``` /// pub fn mut_entries_slice(&mut self) -> &mut [kvm_cpuid_entry2] { // Mapping the unsized array to a slice is unsafe because the length isn't known. Using // the length we originally allocated with eliminates the possibility of overflow. if self.kvm_cpuid[0].nent as usize > self.allocated_len { self.kvm_cpuid[0].nent = self.allocated_len as u32; } let nent = self.kvm_cpuid[0].nent as usize; unsafe { self.kvm_cpuid[0].entries.as_mut_slice(nent) } } /// Get a pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_ptr(&self) -> *const kvm_cpuid2 { &self.kvm_cpuid[0] } /// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_mut_ptr(&mut self) -> *mut kvm_cpuid2 { &mut self.kvm_cpuid[0] } } /// Safe wrapper over the `kvm_run` struct. /// /// The wrapper is needed for sending the pointer to `kvm_run` between /// threads as raw pointers do not implement `Send` and `Sync`. pub struct KvmRunWrapper { kvm_run_ptr: *mut u8, // This field is need so we can `munmap` the memory mapped to hold `kvm_run`. mmap_size: usize, } // Send and Sync aren't automatically inherited for the raw address pointer. // Accessing that pointer is only done through the stateless interface which // allows the object to be shared by multiple threads without a decrease in // safety. unsafe impl Send for KvmRunWrapper {} unsafe impl Sync for KvmRunWrapper {} impl KvmRunWrapper { /// Maps the first `size` bytes of the given `fd`. /// /// # Arguments /// * `fd` - File descriptor to mmap from. /// * `size` - Size of memory region in bytes. pub fn mmap_from_fd(fd: &AsRawFd, size: usize) -> Result<KvmRunWrapper> { // This is safe because we are creating a mapping in a place not already used by any other // area in this process. let addr = unsafe { libc::mmap( null_mut(), size, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_SHARED, fd.as_raw_fd(), 0, ) }; if addr == libc::MAP_FAILED
Ok(KvmRunWrapper { kvm_run_ptr: addr as *mut u8, mmap_size: size, }) } /// Returns a mutable reference to `kvm_run`. /// #[allow(clippy::mut_from_ref)] pub fn as_mut_ref(&self) -> &mut kvm_run { // Safe because we know we mapped enough memory to hold the kvm_run struct because the // kernel told us how large it was. #[allow(clippy::cast_ptr_alignment)] unsafe { &mut *(self.kvm_run_ptr as *mut kvm_run) } } } impl Drop for KvmRunWrapper { fn drop(&mut self) { // This is safe because we mmap the area at kvm_run_ptr ourselves, // and nobody else is holding a reference to it. unsafe { libc::munmap(self.kvm_run_ptr as *mut libc::c_void, self.mmap_size); } } } #[cfg(test)] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod tests { use super::*; #[test] fn test_cpuid_from_entries() { let num_entries = 4; let mut cpuid = CpuId::new(num_entries); // add entry let mut entries = cpuid.mut_entries_slice().to_vec(); let new_entry = kvm_cpuid_entry2 { function: 0x4, index: 0, flags: 1, eax: 0b1100000, ebx: 0, ecx: 0, edx: 0, padding: [0, 0, 0], }; entries.insert(0, new_entry); cpuid = CpuId::from_entries(&entries); // check that the cpuid contains the new entry assert_eq!(cpuid.allocated_len, num_entries + 1); assert_eq!(cpuid.kvm_cpuid[0].nent, (num_entries + 1) as u32); assert_eq!(cpuid.mut_entries_slice().len(), num_entries + 1); assert_eq!(cpuid.mut_entries_slice()[0], new_entry); } }
{ return Err(io::Error::last_os_error()); }
conditional_block
mod.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::io; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use std::mem::size_of; use std::os::unix::io::AsRawFd; use std::ptr::null_mut; use std::result; use kvm_bindings::kvm_run; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use kvm_bindings::{kvm_cpuid2, kvm_cpuid_entry2}; /// Wrappers over KVM device ioctls. pub mod device; /// Wrappers over KVM system ioctls. pub mod system; /// Wrappers over KVM VCPU ioctls. pub mod vcpu; /// Wrappers over KVM Virtual Machine ioctls. pub mod vm; /// A specialized `Result` type for KVM ioctls. /// /// This typedef is generally used to avoid writing out io::Error directly and /// is otherwise a direct mapping to Result. pub type Result<T> = result::Result<T, io::Error>; // Returns a `Vec<T>` with a size in bytes at least as large as `size_in_bytes`. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_with_size_in_bytes<T: Default>(size_in_bytes: usize) -> Vec<T> { let rounded_size = (size_in_bytes + size_of::<T>() - 1) / size_of::<T>(); let mut v = Vec::with_capacity(rounded_size); for _ in 0..rounded_size { v.push(T::default()) } v } // The kvm API has many structs that resemble the following `Foo` structure: // // ``` // #[repr(C)] // struct Foo { // some_data: u32 // entries: __IncompleteArrayField<__u32>, // } // ``` // // In order to allocate such a structure, `size_of::<Foo>()` would be too small because it would not // include any space for `entries`. To make the allocation large enough while still being aligned // for `Foo`, a `Vec<Foo>` is created. Only the first element of `Vec<Foo>` would actually be used // as a `Foo`. The remaining memory in the `Vec<Foo>` is for `entries`, which must be contiguous // with `Foo`. This function is used to make the `Vec<Foo>` with enough space for `count` entries. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_with_array_field<T: Default, F>(count: usize) -> Vec<T> { let element_space = count * size_of::<F>(); let vec_size_bytes = size_of::<T>() + element_space; vec_with_size_in_bytes(vec_size_bytes) } /// Wrapper over the `kvm_cpuid2` structure. /// /// The structure has a zero length array at the end, hidden behind bounds check. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub struct CpuId { // Wrapper over `kvm_cpuid2` from which we only use the first element. kvm_cpuid: Vec<kvm_cpuid2>, // Number of `kvm_cpuid_entry2` structs at the end of kvm_cpuid2. allocated_len: usize, } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl Clone for CpuId { fn clone(&self) -> Self { let mut kvm_cpuid = Vec::with_capacity(self.kvm_cpuid.len()); for _ in 0..self.kvm_cpuid.len() { kvm_cpuid.push(kvm_cpuid2::default()); } let num_bytes = self.kvm_cpuid.len() * size_of::<kvm_cpuid2>(); let src_byte_slice = unsafe { std::slice::from_raw_parts(self.kvm_cpuid.as_ptr() as *const u8, num_bytes) }; let dst_byte_slice = unsafe { std::slice::from_raw_parts_mut(kvm_cpuid.as_mut_ptr() as *mut u8, num_bytes) }; dst_byte_slice.copy_from_slice(src_byte_slice); CpuId { kvm_cpuid, allocated_len: self.allocated_len, } } } #[cfg(test)] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl PartialEq for CpuId { fn eq(&self, other: &CpuId) -> bool { let entries: &[kvm_cpuid_entry2] = unsafe { self.kvm_cpuid[0].entries.as_slice(self.allocated_len) }; let other_entries: &[kvm_cpuid_entry2] = unsafe { self.kvm_cpuid[0].entries.as_slice(other.allocated_len) }; self.allocated_len == other.allocated_len && entries == other_entries } } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl CpuId { /// Creates a new `CpuId` structure that contains at most `array_len` KVM CPUID entries. /// /// # Arguments /// /// * `array_len` - Maximum number of CPUID entries. /// /// # Example /// /// ``` /// use kvm_ioctls::CpuId; /// let cpu_id = CpuId::new(32); /// ``` pub fn new(array_len: usize) -> CpuId { let mut kvm_cpuid = vec_with_array_field::<kvm_cpuid2, kvm_cpuid_entry2>(array_len); kvm_cpuid[0].nent = array_len as u32; CpuId { kvm_cpuid, allocated_len: array_len, } } /// Creates a new `CpuId` structure based on a supplied vector of `kvm_cpuid_entry2`. /// /// # Arguments /// /// * `entries` - The vector of `kvm_cpuid_entry2` entries. /// /// # Example /// /// ```rust /// # extern crate kvm_ioctls; /// extern crate kvm_bindings; /// /// use kvm_bindings::kvm_cpuid_entry2; /// use kvm_ioctls::CpuId; /// // Create a Cpuid to hold one entry. /// let mut cpuid = CpuId::new(1); /// let mut entries = cpuid.mut_entries_slice().to_vec(); /// let new_entry = kvm_cpuid_entry2 { /// function: 0x4, /// index: 0, /// flags: 1, /// eax: 0b1100000, /// ebx: 0, /// ecx: 0, /// edx: 0, /// padding: [0, 0, 0], /// }; /// entries.insert(0, new_entry); /// cpuid = CpuId::from_entries(&entries); /// ``` /// pub fn from_entries(entries: &[kvm_cpuid_entry2]) -> CpuId { let mut kvm_cpuid = vec_with_array_field::<kvm_cpuid2, kvm_cpuid_entry2>(entries.len()); kvm_cpuid[0].nent = entries.len() as u32; unsafe { kvm_cpuid[0] .entries .as_mut_slice(entries.len()) .copy_from_slice(entries); } CpuId { kvm_cpuid, allocated_len: entries.len(), } } /// Returns the mutable entries slice so they can be modified before passing to the VCPU. /// /// # Example /// ```rust /// use kvm_ioctls::{CpuId, Kvm, MAX_KVM_CPUID_ENTRIES}; /// let kvm = Kvm::new().unwrap(); /// let mut cpuid = kvm.get_supported_cpuid(MAX_KVM_CPUID_ENTRIES).unwrap(); /// let cpuid_entries = cpuid.mut_entries_slice(); /// ``` /// pub fn mut_entries_slice(&mut self) -> &mut [kvm_cpuid_entry2]
/// Get a pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_ptr(&self) -> *const kvm_cpuid2 { &self.kvm_cpuid[0] } /// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_mut_ptr(&mut self) -> *mut kvm_cpuid2 { &mut self.kvm_cpuid[0] } } /// Safe wrapper over the `kvm_run` struct. /// /// The wrapper is needed for sending the pointer to `kvm_run` between /// threads as raw pointers do not implement `Send` and `Sync`. pub struct KvmRunWrapper { kvm_run_ptr: *mut u8, // This field is need so we can `munmap` the memory mapped to hold `kvm_run`. mmap_size: usize, } // Send and Sync aren't automatically inherited for the raw address pointer. // Accessing that pointer is only done through the stateless interface which // allows the object to be shared by multiple threads without a decrease in // safety. unsafe impl Send for KvmRunWrapper {} unsafe impl Sync for KvmRunWrapper {} impl KvmRunWrapper { /// Maps the first `size` bytes of the given `fd`. /// /// # Arguments /// * `fd` - File descriptor to mmap from. /// * `size` - Size of memory region in bytes. pub fn mmap_from_fd(fd: &AsRawFd, size: usize) -> Result<KvmRunWrapper> { // This is safe because we are creating a mapping in a place not already used by any other // area in this process. let addr = unsafe { libc::mmap( null_mut(), size, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_SHARED, fd.as_raw_fd(), 0, ) }; if addr == libc::MAP_FAILED { return Err(io::Error::last_os_error()); } Ok(KvmRunWrapper { kvm_run_ptr: addr as *mut u8, mmap_size: size, }) } /// Returns a mutable reference to `kvm_run`. /// #[allow(clippy::mut_from_ref)] pub fn as_mut_ref(&self) -> &mut kvm_run { // Safe because we know we mapped enough memory to hold the kvm_run struct because the // kernel told us how large it was. #[allow(clippy::cast_ptr_alignment)] unsafe { &mut *(self.kvm_run_ptr as *mut kvm_run) } } } impl Drop for KvmRunWrapper { fn drop(&mut self) { // This is safe because we mmap the area at kvm_run_ptr ourselves, // and nobody else is holding a reference to it. unsafe { libc::munmap(self.kvm_run_ptr as *mut libc::c_void, self.mmap_size); } } } #[cfg(test)] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod tests { use super::*; #[test] fn test_cpuid_from_entries() { let num_entries = 4; let mut cpuid = CpuId::new(num_entries); // add entry let mut entries = cpuid.mut_entries_slice().to_vec(); let new_entry = kvm_cpuid_entry2 { function: 0x4, index: 0, flags: 1, eax: 0b1100000, ebx: 0, ecx: 0, edx: 0, padding: [0, 0, 0], }; entries.insert(0, new_entry); cpuid = CpuId::from_entries(&entries); // check that the cpuid contains the new entry assert_eq!(cpuid.allocated_len, num_entries + 1); assert_eq!(cpuid.kvm_cpuid[0].nent, (num_entries + 1) as u32); assert_eq!(cpuid.mut_entries_slice().len(), num_entries + 1); assert_eq!(cpuid.mut_entries_slice()[0], new_entry); } }
{ // Mapping the unsized array to a slice is unsafe because the length isn't known. Using // the length we originally allocated with eliminates the possibility of overflow. if self.kvm_cpuid[0].nent as usize > self.allocated_len { self.kvm_cpuid[0].nent = self.allocated_len as u32; } let nent = self.kvm_cpuid[0].nent as usize; unsafe { self.kvm_cpuid[0].entries.as_mut_slice(nent) } }
identifier_body
mod.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::io; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use std::mem::size_of; use std::os::unix::io::AsRawFd; use std::ptr::null_mut; use std::result; use kvm_bindings::kvm_run; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use kvm_bindings::{kvm_cpuid2, kvm_cpuid_entry2}; /// Wrappers over KVM device ioctls. pub mod device; /// Wrappers over KVM system ioctls. pub mod system; /// Wrappers over KVM VCPU ioctls. pub mod vcpu; /// Wrappers over KVM Virtual Machine ioctls. pub mod vm; /// A specialized `Result` type for KVM ioctls. /// /// This typedef is generally used to avoid writing out io::Error directly and /// is otherwise a direct mapping to Result. pub type Result<T> = result::Result<T, io::Error>; // Returns a `Vec<T>` with a size in bytes at least as large as `size_in_bytes`. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_with_size_in_bytes<T: Default>(size_in_bytes: usize) -> Vec<T> { let rounded_size = (size_in_bytes + size_of::<T>() - 1) / size_of::<T>(); let mut v = Vec::with_capacity(rounded_size); for _ in 0..rounded_size { v.push(T::default()) } v } // The kvm API has many structs that resemble the following `Foo` structure: // // ``` // #[repr(C)] // struct Foo { // some_data: u32 // entries: __IncompleteArrayField<__u32>, // } // ``` // // In order to allocate such a structure, `size_of::<Foo>()` would be too small because it would not // include any space for `entries`. To make the allocation large enough while still being aligned // for `Foo`, a `Vec<Foo>` is created. Only the first element of `Vec<Foo>` would actually be used // as a `Foo`. The remaining memory in the `Vec<Foo>` is for `entries`, which must be contiguous // with `Foo`. This function is used to make the `Vec<Foo>` with enough space for `count` entries. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_with_array_field<T: Default, F>(count: usize) -> Vec<T> { let element_space = count * size_of::<F>(); let vec_size_bytes = size_of::<T>() + element_space; vec_with_size_in_bytes(vec_size_bytes) } /// Wrapper over the `kvm_cpuid2` structure. /// /// The structure has a zero length array at the end, hidden behind bounds check. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub struct CpuId { // Wrapper over `kvm_cpuid2` from which we only use the first element. kvm_cpuid: Vec<kvm_cpuid2>, // Number of `kvm_cpuid_entry2` structs at the end of kvm_cpuid2. allocated_len: usize, } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl Clone for CpuId { fn clone(&self) -> Self { let mut kvm_cpuid = Vec::with_capacity(self.kvm_cpuid.len()); for _ in 0..self.kvm_cpuid.len() { kvm_cpuid.push(kvm_cpuid2::default()); } let num_bytes = self.kvm_cpuid.len() * size_of::<kvm_cpuid2>(); let src_byte_slice = unsafe { std::slice::from_raw_parts(self.kvm_cpuid.as_ptr() as *const u8, num_bytes) }; let dst_byte_slice = unsafe { std::slice::from_raw_parts_mut(kvm_cpuid.as_mut_ptr() as *mut u8, num_bytes) }; dst_byte_slice.copy_from_slice(src_byte_slice); CpuId { kvm_cpuid, allocated_len: self.allocated_len, } } } #[cfg(test)] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl PartialEq for CpuId { fn eq(&self, other: &CpuId) -> bool { let entries: &[kvm_cpuid_entry2] = unsafe { self.kvm_cpuid[0].entries.as_slice(self.allocated_len) }; let other_entries: &[kvm_cpuid_entry2] = unsafe { self.kvm_cpuid[0].entries.as_slice(other.allocated_len) }; self.allocated_len == other.allocated_len && entries == other_entries } } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] impl CpuId { /// Creates a new `CpuId` structure that contains at most `array_len` KVM CPUID entries. /// /// # Arguments /// /// * `array_len` - Maximum number of CPUID entries. /// /// # Example /// /// ``` /// use kvm_ioctls::CpuId; /// let cpu_id = CpuId::new(32); /// ``` pub fn new(array_len: usize) -> CpuId { let mut kvm_cpuid = vec_with_array_field::<kvm_cpuid2, kvm_cpuid_entry2>(array_len); kvm_cpuid[0].nent = array_len as u32; CpuId { kvm_cpuid, allocated_len: array_len, } } /// Creates a new `CpuId` structure based on a supplied vector of `kvm_cpuid_entry2`. /// /// # Arguments /// /// * `entries` - The vector of `kvm_cpuid_entry2` entries. /// /// # Example /// /// ```rust /// # extern crate kvm_ioctls; /// extern crate kvm_bindings; /// /// use kvm_bindings::kvm_cpuid_entry2; /// use kvm_ioctls::CpuId; /// // Create a Cpuid to hold one entry. /// let mut cpuid = CpuId::new(1); /// let mut entries = cpuid.mut_entries_slice().to_vec(); /// let new_entry = kvm_cpuid_entry2 { /// function: 0x4, /// index: 0, /// flags: 1, /// eax: 0b1100000, /// ebx: 0, /// ecx: 0, /// edx: 0, /// padding: [0, 0, 0], /// }; /// entries.insert(0, new_entry); /// cpuid = CpuId::from_entries(&entries); /// ``` /// pub fn from_entries(entries: &[kvm_cpuid_entry2]) -> CpuId { let mut kvm_cpuid = vec_with_array_field::<kvm_cpuid2, kvm_cpuid_entry2>(entries.len()); kvm_cpuid[0].nent = entries.len() as u32; unsafe { kvm_cpuid[0] .entries .as_mut_slice(entries.len()) .copy_from_slice(entries); }
CpuId { kvm_cpuid, allocated_len: entries.len(), } } /// Returns the mutable entries slice so they can be modified before passing to the VCPU. /// /// # Example /// ```rust /// use kvm_ioctls::{CpuId, Kvm, MAX_KVM_CPUID_ENTRIES}; /// let kvm = Kvm::new().unwrap(); /// let mut cpuid = kvm.get_supported_cpuid(MAX_KVM_CPUID_ENTRIES).unwrap(); /// let cpuid_entries = cpuid.mut_entries_slice(); /// ``` /// pub fn mut_entries_slice(&mut self) -> &mut [kvm_cpuid_entry2] { // Mapping the unsized array to a slice is unsafe because the length isn't known. Using // the length we originally allocated with eliminates the possibility of overflow. if self.kvm_cpuid[0].nent as usize > self.allocated_len { self.kvm_cpuid[0].nent = self.allocated_len as u32; } let nent = self.kvm_cpuid[0].nent as usize; unsafe { self.kvm_cpuid[0].entries.as_mut_slice(nent) } } /// Get a pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_ptr(&self) -> *const kvm_cpuid2 { &self.kvm_cpuid[0] } /// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_mut_ptr(&mut self) -> *mut kvm_cpuid2 { &mut self.kvm_cpuid[0] } } /// Safe wrapper over the `kvm_run` struct. /// /// The wrapper is needed for sending the pointer to `kvm_run` between /// threads as raw pointers do not implement `Send` and `Sync`. pub struct KvmRunWrapper { kvm_run_ptr: *mut u8, // This field is need so we can `munmap` the memory mapped to hold `kvm_run`. mmap_size: usize, } // Send and Sync aren't automatically inherited for the raw address pointer. // Accessing that pointer is only done through the stateless interface which // allows the object to be shared by multiple threads without a decrease in // safety. unsafe impl Send for KvmRunWrapper {} unsafe impl Sync for KvmRunWrapper {} impl KvmRunWrapper { /// Maps the first `size` bytes of the given `fd`. /// /// # Arguments /// * `fd` - File descriptor to mmap from. /// * `size` - Size of memory region in bytes. pub fn mmap_from_fd(fd: &AsRawFd, size: usize) -> Result<KvmRunWrapper> { // This is safe because we are creating a mapping in a place not already used by any other // area in this process. let addr = unsafe { libc::mmap( null_mut(), size, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_SHARED, fd.as_raw_fd(), 0, ) }; if addr == libc::MAP_FAILED { return Err(io::Error::last_os_error()); } Ok(KvmRunWrapper { kvm_run_ptr: addr as *mut u8, mmap_size: size, }) } /// Returns a mutable reference to `kvm_run`. /// #[allow(clippy::mut_from_ref)] pub fn as_mut_ref(&self) -> &mut kvm_run { // Safe because we know we mapped enough memory to hold the kvm_run struct because the // kernel told us how large it was. #[allow(clippy::cast_ptr_alignment)] unsafe { &mut *(self.kvm_run_ptr as *mut kvm_run) } } } impl Drop for KvmRunWrapper { fn drop(&mut self) { // This is safe because we mmap the area at kvm_run_ptr ourselves, // and nobody else is holding a reference to it. unsafe { libc::munmap(self.kvm_run_ptr as *mut libc::c_void, self.mmap_size); } } } #[cfg(test)] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod tests { use super::*; #[test] fn test_cpuid_from_entries() { let num_entries = 4; let mut cpuid = CpuId::new(num_entries); // add entry let mut entries = cpuid.mut_entries_slice().to_vec(); let new_entry = kvm_cpuid_entry2 { function: 0x4, index: 0, flags: 1, eax: 0b1100000, ebx: 0, ecx: 0, edx: 0, padding: [0, 0, 0], }; entries.insert(0, new_entry); cpuid = CpuId::from_entries(&entries); // check that the cpuid contains the new entry assert_eq!(cpuid.allocated_len, num_entries + 1); assert_eq!(cpuid.kvm_cpuid[0].nent, (num_entries + 1) as u32); assert_eq!(cpuid.mut_entries_slice().len(), num_entries + 1); assert_eq!(cpuid.mut_entries_slice()[0], new_entry); } }
random_line_split
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileServer` is a Source which cooperatively schedules reads over files, /// converting the lines of said files into `LogLine` structures. As /// `FileServer` is intended to be useful across multiple operating systems with /// POSIX filesystem semantics `FileServer` must poll for changes. That is, no /// event notification is used by `FileServer`. /// /// `FileServer` is configured on a path to watch. The files do _not_ need to /// exist at cernan startup. `FileServer` will discover new files which match /// its path in at most 60 seconds. pub struct FileServer { pub include: Vec<PathBuf>, pub exclude: Vec<PathBuf>, pub max_read_bytes: usize, pub start_at_beginning: bool, pub ignore_before: Option<time::SystemTime>, pub max_line_bytes: usize, pub fingerprint_bytes: usize, pub ignored_header_bytes: usize, } type FileFingerprint = u64; /// `FileServer` as Source /// /// The 'run' of `FileServer` performs the cooperative scheduling of reads over /// `FileServer`'s configured files. Much care has been taking to make this /// scheduling 'fair', meaning busy files do not drown out quiet files or vice /// versa but there's no one perfect approach. Very fast files _will_ be lost if /// your system aggressively rolls log files. `FileServer` will keep a file /// handler open but should your system move so quickly that a file disappears /// before cernan is able to open it the contents will be lost. This should be a /// rare occurence. /// /// Specific operating systems support evented interfaces that correct this /// problem but your intrepid authors know of no generic solution. impl FileServer { pub fn run( self, mut chans: impl Sink<SinkItem = (Bytes, String), SinkError = ()>, shutdown: std::sync::mpsc::Receiver<()>, ) { let mut line_buffer = Vec::new(); let mut fingerprint_buffer = Vec::new(); let mut fp_map: HashMap<FileFingerprint, FileWatcher> = Default::default(); let mut backoff_cap: usize = 1; let mut lines = Vec::new(); let mut start_of_run = true; // Alright friends, how does this work? // // We want to avoid burning up users' CPUs. To do this we sleep after // reading lines out of files. But! We want to be responsive as well. We // keep track of a 'backoff_cap' to decide how long we'll wait in any // given loop. This cap grows each time we fail to read lines in an // exponential fashion to some hard-coded cap. loop { let mut global_bytes_read: usize = 0; // glob poll let exclude_patterns = self .exclude .iter() .map(|e| Pattern::new(e.to_str().expect("no ability to glob")).unwrap()) .collect::<Vec<_>>(); for (_file_id, watcher) in &mut fp_map { watcher.set_file_findable(false); // assume not findable until found } for include_pattern in &self.include { for entry in glob(include_pattern.to_str().expect("no ability to glob")) .expect("Failed to read glob pattern") { if let Ok(path) = entry { if exclude_patterns .iter() .any(|e| e.matches(path.to_str().unwrap())) { continue; } if let Some(file_id) = self.get_fingerprint_of_file(&path, &mut fingerprint_buffer) { if let Some(watcher) = fp_map.get_mut(&file_id) { // file fingerprint matches a watched file let was_found_this_cycle = watcher.file_findable(); watcher.set_file_findable(true); if watcher.path == path { trace!( message = "Continue watching file.", path = field::debug(&path), ); } else { // matches a file with a different path if!was_found_this_cycle { info!( message = "Watched file has been renamed.", path = field::debug(&path), old_path = field::debug(&watcher.path) ); watcher.update_path(path).ok(); // ok if this fails: might fix next cycle } else { info!( message = "More than one file has same fingerprint.", path = field::debug(&path), old_path = field::debug(&watcher.path) ); let (old_path, new_path) = (&watcher.path, &path); if let (Ok(old_modified_time), Ok(new_modified_time)) = ( fs::metadata(&old_path).and_then(|m| m.modified()), fs::metadata(&new_path).and_then(|m| m.modified()), ) { if old_modified_time < new_modified_time { info!( message = "Switching to watch most recently modified file.", new_modified_time = field::debug(&new_modified_time), old_modified_time = field::debug(&old_modified_time), ); watcher.update_path(path).ok(); // ok if this fails: might fix next cycle } } } } } else { // unknown (new) file fingerprint let read_file_from_beginning = if start_of_run { self.start_at_beginning } else { true }; if let Ok(mut watcher) = FileWatcher::new( path, read_file_from_beginning, self.ignore_before, ) { info!( message = "Found file to watch.", path = field::debug(&watcher.path), start_at_beginning = field::debug(&self.start_at_beginning), start_of_run = field::debug(&start_of_run), ); watcher.set_file_findable(true); fp_map.insert(file_id, watcher); }; } } } } } // line polling for (_file_id, watcher) in &mut fp_map { let mut bytes_read: usize = 0; while let Ok(sz) = watcher.read_line(&mut line_buffer, self.max_line_bytes) { if sz > 0 { trace!( message = "Read bytes.", path = field::debug(&watcher.path), bytes = field::debug(sz) ); bytes_read += sz; if!line_buffer.is_empty() { lines.push(( line_buffer.clone().into(), watcher.path.to_str().expect("not a valid path").to_owned(), )); line_buffer.clear(); } } else { break; } if bytes_read > self.max_read_bytes { break; } } global_bytes_read = global_bytes_read.saturating_add(bytes_read); } // A FileWatcher is dead when the underlying file has disappeared. // If the FileWatcher is dead we don't retain it; it will be deallocated. fp_map.retain(|_file_id, watcher|!watcher.dead()); match stream::iter_ok::<_, ()>(lines.drain(..)) .forward(chans) .wait() { Ok((_, sink)) => chans = sink, Err(_) => unreachable!("Output channel is closed"), } // When no lines have been read we kick the backup_cap up by twice, // limited by the hard-coded cap. Else, we set the backup_cap to its // minimum on the assumption that next time through there will be // more lines to read promptly. if global_bytes_read == 0 { let lim = backoff_cap.saturating_mul(2); if lim > 2_048 { backoff_cap = 2_048; } else { backoff_cap = lim; } } else { backoff_cap = 1; } let backoff = backoff_cap.saturating_sub(global_bytes_read); match shutdown.recv_timeout(time::Duration::from_millis(backoff as u64)) { Ok(()) => unreachable!(), // The sender should never actually send Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => return, } start_of_run = false; } } fn
( &self, path: &PathBuf, buffer: &mut Vec<u8>, ) -> Option<FileFingerprint> { let i = self.ignored_header_bytes as u64; let b = self.fingerprint_bytes; buffer.resize(b, 0u8); if let Ok(mut fp) = fs::File::open(path) { if fp.seek(SeekFrom::Start(i)).is_ok() && fp.read_exact(&mut buffer[..b]).is_ok() { let fingerprint = crc::crc64::checksum_ecma(&buffer[..b]); Some(fingerprint) } else { None } } else { None } } }
get_fingerprint_of_file
identifier_name
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileServer` is a Source which cooperatively schedules reads over files, /// converting the lines of said files into `LogLine` structures. As /// `FileServer` is intended to be useful across multiple operating systems with /// POSIX filesystem semantics `FileServer` must poll for changes. That is, no /// event notification is used by `FileServer`. /// /// `FileServer` is configured on a path to watch. The files do _not_ need to /// exist at cernan startup. `FileServer` will discover new files which match /// its path in at most 60 seconds. pub struct FileServer { pub include: Vec<PathBuf>, pub exclude: Vec<PathBuf>, pub max_read_bytes: usize, pub start_at_beginning: bool, pub ignore_before: Option<time::SystemTime>, pub max_line_bytes: usize, pub fingerprint_bytes: usize, pub ignored_header_bytes: usize, } type FileFingerprint = u64; /// `FileServer` as Source /// /// The 'run' of `FileServer` performs the cooperative scheduling of reads over /// `FileServer`'s configured files. Much care has been taking to make this /// scheduling 'fair', meaning busy files do not drown out quiet files or vice /// versa but there's no one perfect approach. Very fast files _will_ be lost if /// your system aggressively rolls log files. `FileServer` will keep a file /// handler open but should your system move so quickly that a file disappears /// before cernan is able to open it the contents will be lost. This should be a /// rare occurence. /// /// Specific operating systems support evented interfaces that correct this /// problem but your intrepid authors know of no generic solution. impl FileServer { pub fn run( self, mut chans: impl Sink<SinkItem = (Bytes, String), SinkError = ()>, shutdown: std::sync::mpsc::Receiver<()>, )
.exclude .iter() .map(|e| Pattern::new(e.to_str().expect("no ability to glob")).unwrap()) .collect::<Vec<_>>(); for (_file_id, watcher) in &mut fp_map { watcher.set_file_findable(false); // assume not findable until found } for include_pattern in &self.include { for entry in glob(include_pattern.to_str().expect("no ability to glob")) .expect("Failed to read glob pattern") { if let Ok(path) = entry { if exclude_patterns .iter() .any(|e| e.matches(path.to_str().unwrap())) { continue; } if let Some(file_id) = self.get_fingerprint_of_file(&path, &mut fingerprint_buffer) { if let Some(watcher) = fp_map.get_mut(&file_id) { // file fingerprint matches a watched file let was_found_this_cycle = watcher.file_findable(); watcher.set_file_findable(true); if watcher.path == path { trace!( message = "Continue watching file.", path = field::debug(&path), ); } else { // matches a file with a different path if!was_found_this_cycle { info!( message = "Watched file has been renamed.", path = field::debug(&path), old_path = field::debug(&watcher.path) ); watcher.update_path(path).ok(); // ok if this fails: might fix next cycle } else { info!( message = "More than one file has same fingerprint.", path = field::debug(&path), old_path = field::debug(&watcher.path) ); let (old_path, new_path) = (&watcher.path, &path); if let (Ok(old_modified_time), Ok(new_modified_time)) = ( fs::metadata(&old_path).and_then(|m| m.modified()), fs::metadata(&new_path).and_then(|m| m.modified()), ) { if old_modified_time < new_modified_time { info!( message = "Switching to watch most recently modified file.", new_modified_time = field::debug(&new_modified_time), old_modified_time = field::debug(&old_modified_time), ); watcher.update_path(path).ok(); // ok if this fails: might fix next cycle } } } } } else { // unknown (new) file fingerprint let read_file_from_beginning = if start_of_run { self.start_at_beginning } else { true }; if let Ok(mut watcher) = FileWatcher::new( path, read_file_from_beginning, self.ignore_before, ) { info!( message = "Found file to watch.", path = field::debug(&watcher.path), start_at_beginning = field::debug(&self.start_at_beginning), start_of_run = field::debug(&start_of_run), ); watcher.set_file_findable(true); fp_map.insert(file_id, watcher); }; } } } } } // line polling for (_file_id, watcher) in &mut fp_map { let mut bytes_read: usize = 0; while let Ok(sz) = watcher.read_line(&mut line_buffer, self.max_line_bytes) { if sz > 0 { trace!( message = "Read bytes.", path = field::debug(&watcher.path), bytes = field::debug(sz) ); bytes_read += sz; if!line_buffer.is_empty() { lines.push(( line_buffer.clone().into(), watcher.path.to_str().expect("not a valid path").to_owned(), )); line_buffer.clear(); } } else { break; } if bytes_read > self.max_read_bytes { break; } } global_bytes_read = global_bytes_read.saturating_add(bytes_read); } // A FileWatcher is dead when the underlying file has disappeared. // If the FileWatcher is dead we don't retain it; it will be deallocated. fp_map.retain(|_file_id, watcher|!watcher.dead()); match stream::iter_ok::<_, ()>(lines.drain(..)) .forward(chans) .wait() { Ok((_, sink)) => chans = sink, Err(_) => unreachable!("Output channel is closed"), } // When no lines have been read we kick the backup_cap up by twice, // limited by the hard-coded cap. Else, we set the backup_cap to its // minimum on the assumption that next time through there will be // more lines to read promptly. if global_bytes_read == 0 { let lim = backoff_cap.saturating_mul(2); if lim > 2_048 { backoff_cap = 2_048; } else { backoff_cap = lim; } } else { backoff_cap = 1; } let backoff = backoff_cap.saturating_sub(global_bytes_read); match shutdown.recv_timeout(time::Duration::from_millis(backoff as u64)) { Ok(()) => unreachable!(), // The sender should never actually send Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => return, } start_of_run = false; } } fn get_fingerprint_of_file( &self, path: &PathBuf, buffer: &mut Vec<u8>, ) -> Option<FileFingerprint> { let i = self.ignored_header_bytes as u64; let b = self.fingerprint_bytes; buffer.resize(b, 0u8); if let Ok(mut fp) = fs::File::open(path) { if fp.seek(SeekFrom::Start(i)).is_ok() && fp.read_exact(&mut buffer[..b]).is_ok() { let fingerprint = crc::crc64::checksum_ecma(&buffer[..b]); Some(fingerprint) } else { None } } else { None } } }
{ let mut line_buffer = Vec::new(); let mut fingerprint_buffer = Vec::new(); let mut fp_map: HashMap<FileFingerprint, FileWatcher> = Default::default(); let mut backoff_cap: usize = 1; let mut lines = Vec::new(); let mut start_of_run = true; // Alright friends, how does this work? // // We want to avoid burning up users' CPUs. To do this we sleep after // reading lines out of files. But! We want to be responsive as well. We // keep track of a 'backoff_cap' to decide how long we'll wait in any // given loop. This cap grows each time we fail to read lines in an // exponential fashion to some hard-coded cap. loop { let mut global_bytes_read: usize = 0; // glob poll let exclude_patterns = self
identifier_body
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileServer` is a Source which cooperatively schedules reads over files, /// converting the lines of said files into `LogLine` structures. As /// `FileServer` is intended to be useful across multiple operating systems with /// POSIX filesystem semantics `FileServer` must poll for changes. That is, no /// event notification is used by `FileServer`. /// /// `FileServer` is configured on a path to watch. The files do _not_ need to /// exist at cernan startup. `FileServer` will discover new files which match /// its path in at most 60 seconds. pub struct FileServer { pub include: Vec<PathBuf>, pub exclude: Vec<PathBuf>, pub max_read_bytes: usize, pub start_at_beginning: bool, pub ignore_before: Option<time::SystemTime>, pub max_line_bytes: usize, pub fingerprint_bytes: usize, pub ignored_header_bytes: usize, } type FileFingerprint = u64; /// `FileServer` as Source /// /// The 'run' of `FileServer` performs the cooperative scheduling of reads over /// `FileServer`'s configured files. Much care has been taking to make this /// scheduling 'fair', meaning busy files do not drown out quiet files or vice /// versa but there's no one perfect approach. Very fast files _will_ be lost if /// your system aggressively rolls log files. `FileServer` will keep a file /// handler open but should your system move so quickly that a file disappears /// before cernan is able to open it the contents will be lost. This should be a /// rare occurence. /// /// Specific operating systems support evented interfaces that correct this /// problem but your intrepid authors know of no generic solution. impl FileServer { pub fn run( self, mut chans: impl Sink<SinkItem = (Bytes, String), SinkError = ()>, shutdown: std::sync::mpsc::Receiver<()>, ) { let mut line_buffer = Vec::new(); let mut fingerprint_buffer = Vec::new(); let mut fp_map: HashMap<FileFingerprint, FileWatcher> = Default::default(); let mut backoff_cap: usize = 1; let mut lines = Vec::new(); let mut start_of_run = true; // Alright friends, how does this work? // // We want to avoid burning up users' CPUs. To do this we sleep after // reading lines out of files. But! We want to be responsive as well. We // keep track of a 'backoff_cap' to decide how long we'll wait in any // given loop. This cap grows each time we fail to read lines in an // exponential fashion to some hard-coded cap. loop { let mut global_bytes_read: usize = 0; // glob poll let exclude_patterns = self .exclude .iter() .map(|e| Pattern::new(e.to_str().expect("no ability to glob")).unwrap()) .collect::<Vec<_>>(); for (_file_id, watcher) in &mut fp_map { watcher.set_file_findable(false); // assume not findable until found } for include_pattern in &self.include { for entry in glob(include_pattern.to_str().expect("no ability to glob")) .expect("Failed to read glob pattern") { if let Ok(path) = entry { if exclude_patterns .iter() .any(|e| e.matches(path.to_str().unwrap())) { continue; } if let Some(file_id) = self.get_fingerprint_of_file(&path, &mut fingerprint_buffer) { if let Some(watcher) = fp_map.get_mut(&file_id) { // file fingerprint matches a watched file let was_found_this_cycle = watcher.file_findable(); watcher.set_file_findable(true); if watcher.path == path { trace!( message = "Continue watching file.", path = field::debug(&path), ); } else
if old_modified_time < new_modified_time { info!( message = "Switching to watch most recently modified file.", new_modified_time = field::debug(&new_modified_time), old_modified_time = field::debug(&old_modified_time), ); watcher.update_path(path).ok(); // ok if this fails: might fix next cycle } } } } } else { // unknown (new) file fingerprint let read_file_from_beginning = if start_of_run { self.start_at_beginning } else { true }; if let Ok(mut watcher) = FileWatcher::new( path, read_file_from_beginning, self.ignore_before, ) { info!( message = "Found file to watch.", path = field::debug(&watcher.path), start_at_beginning = field::debug(&self.start_at_beginning), start_of_run = field::debug(&start_of_run), ); watcher.set_file_findable(true); fp_map.insert(file_id, watcher); }; } } } } } // line polling for (_file_id, watcher) in &mut fp_map { let mut bytes_read: usize = 0; while let Ok(sz) = watcher.read_line(&mut line_buffer, self.max_line_bytes) { if sz > 0 { trace!( message = "Read bytes.", path = field::debug(&watcher.path), bytes = field::debug(sz) ); bytes_read += sz; if!line_buffer.is_empty() { lines.push(( line_buffer.clone().into(), watcher.path.to_str().expect("not a valid path").to_owned(), )); line_buffer.clear(); } } else { break; } if bytes_read > self.max_read_bytes { break; } } global_bytes_read = global_bytes_read.saturating_add(bytes_read); } // A FileWatcher is dead when the underlying file has disappeared. // If the FileWatcher is dead we don't retain it; it will be deallocated. fp_map.retain(|_file_id, watcher|!watcher.dead()); match stream::iter_ok::<_, ()>(lines.drain(..)) .forward(chans) .wait() { Ok((_, sink)) => chans = sink, Err(_) => unreachable!("Output channel is closed"), } // When no lines have been read we kick the backup_cap up by twice, // limited by the hard-coded cap. Else, we set the backup_cap to its // minimum on the assumption that next time through there will be // more lines to read promptly. if global_bytes_read == 0 { let lim = backoff_cap.saturating_mul(2); if lim > 2_048 { backoff_cap = 2_048; } else { backoff_cap = lim; } } else { backoff_cap = 1; } let backoff = backoff_cap.saturating_sub(global_bytes_read); match shutdown.recv_timeout(time::Duration::from_millis(backoff as u64)) { Ok(()) => unreachable!(), // The sender should never actually send Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => return, } start_of_run = false; } } fn get_fingerprint_of_file( &self, path: &PathBuf, buffer: &mut Vec<u8>, ) -> Option<FileFingerprint> { let i = self.ignored_header_bytes as u64; let b = self.fingerprint_bytes; buffer.resize(b, 0u8); if let Ok(mut fp) = fs::File::open(path) { if fp.seek(SeekFrom::Start(i)).is_ok() && fp.read_exact(&mut buffer[..b]).is_ok() { let fingerprint = crc::crc64::checksum_ecma(&buffer[..b]); Some(fingerprint) } else { None } } else { None } } }
{ // matches a file with a different path if !was_found_this_cycle { info!( message = "Watched file has been renamed.", path = field::debug(&path), old_path = field::debug(&watcher.path) ); watcher.update_path(path).ok(); // ok if this fails: might fix next cycle } else { info!( message = "More than one file has same fingerprint.", path = field::debug(&path), old_path = field::debug(&watcher.path) ); let (old_path, new_path) = (&watcher.path, &path); if let (Ok(old_modified_time), Ok(new_modified_time)) = ( fs::metadata(&old_path).and_then(|m| m.modified()), fs::metadata(&new_path).and_then(|m| m.modified()), ) {
conditional_block
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileServer` is a Source which cooperatively schedules reads over files, /// converting the lines of said files into `LogLine` structures. As /// `FileServer` is intended to be useful across multiple operating systems with /// POSIX filesystem semantics `FileServer` must poll for changes. That is, no /// event notification is used by `FileServer`. /// /// `FileServer` is configured on a path to watch. The files do _not_ need to /// exist at cernan startup. `FileServer` will discover new files which match /// its path in at most 60 seconds. pub struct FileServer { pub include: Vec<PathBuf>, pub exclude: Vec<PathBuf>, pub max_read_bytes: usize, pub start_at_beginning: bool, pub ignore_before: Option<time::SystemTime>, pub max_line_bytes: usize, pub fingerprint_bytes: usize, pub ignored_header_bytes: usize, } type FileFingerprint = u64; /// `FileServer` as Source /// /// The 'run' of `FileServer` performs the cooperative scheduling of reads over /// `FileServer`'s configured files. Much care has been taking to make this /// scheduling 'fair', meaning busy files do not drown out quiet files or vice /// versa but there's no one perfect approach. Very fast files _will_ be lost if /// your system aggressively rolls log files. `FileServer` will keep a file /// handler open but should your system move so quickly that a file disappears /// before cernan is able to open it the contents will be lost. This should be a /// rare occurence. /// /// Specific operating systems support evented interfaces that correct this /// problem but your intrepid authors know of no generic solution. impl FileServer { pub fn run( self, mut chans: impl Sink<SinkItem = (Bytes, String), SinkError = ()>, shutdown: std::sync::mpsc::Receiver<()>, ) { let mut line_buffer = Vec::new(); let mut fingerprint_buffer = Vec::new(); let mut fp_map: HashMap<FileFingerprint, FileWatcher> = Default::default();
let mut start_of_run = true; // Alright friends, how does this work? // // We want to avoid burning up users' CPUs. To do this we sleep after // reading lines out of files. But! We want to be responsive as well. We // keep track of a 'backoff_cap' to decide how long we'll wait in any // given loop. This cap grows each time we fail to read lines in an // exponential fashion to some hard-coded cap. loop { let mut global_bytes_read: usize = 0; // glob poll let exclude_patterns = self .exclude .iter() .map(|e| Pattern::new(e.to_str().expect("no ability to glob")).unwrap()) .collect::<Vec<_>>(); for (_file_id, watcher) in &mut fp_map { watcher.set_file_findable(false); // assume not findable until found } for include_pattern in &self.include { for entry in glob(include_pattern.to_str().expect("no ability to glob")) .expect("Failed to read glob pattern") { if let Ok(path) = entry { if exclude_patterns .iter() .any(|e| e.matches(path.to_str().unwrap())) { continue; } if let Some(file_id) = self.get_fingerprint_of_file(&path, &mut fingerprint_buffer) { if let Some(watcher) = fp_map.get_mut(&file_id) { // file fingerprint matches a watched file let was_found_this_cycle = watcher.file_findable(); watcher.set_file_findable(true); if watcher.path == path { trace!( message = "Continue watching file.", path = field::debug(&path), ); } else { // matches a file with a different path if!was_found_this_cycle { info!( message = "Watched file has been renamed.", path = field::debug(&path), old_path = field::debug(&watcher.path) ); watcher.update_path(path).ok(); // ok if this fails: might fix next cycle } else { info!( message = "More than one file has same fingerprint.", path = field::debug(&path), old_path = field::debug(&watcher.path) ); let (old_path, new_path) = (&watcher.path, &path); if let (Ok(old_modified_time), Ok(new_modified_time)) = ( fs::metadata(&old_path).and_then(|m| m.modified()), fs::metadata(&new_path).and_then(|m| m.modified()), ) { if old_modified_time < new_modified_time { info!( message = "Switching to watch most recently modified file.", new_modified_time = field::debug(&new_modified_time), old_modified_time = field::debug(&old_modified_time), ); watcher.update_path(path).ok(); // ok if this fails: might fix next cycle } } } } } else { // unknown (new) file fingerprint let read_file_from_beginning = if start_of_run { self.start_at_beginning } else { true }; if let Ok(mut watcher) = FileWatcher::new( path, read_file_from_beginning, self.ignore_before, ) { info!( message = "Found file to watch.", path = field::debug(&watcher.path), start_at_beginning = field::debug(&self.start_at_beginning), start_of_run = field::debug(&start_of_run), ); watcher.set_file_findable(true); fp_map.insert(file_id, watcher); }; } } } } } // line polling for (_file_id, watcher) in &mut fp_map { let mut bytes_read: usize = 0; while let Ok(sz) = watcher.read_line(&mut line_buffer, self.max_line_bytes) { if sz > 0 { trace!( message = "Read bytes.", path = field::debug(&watcher.path), bytes = field::debug(sz) ); bytes_read += sz; if!line_buffer.is_empty() { lines.push(( line_buffer.clone().into(), watcher.path.to_str().expect("not a valid path").to_owned(), )); line_buffer.clear(); } } else { break; } if bytes_read > self.max_read_bytes { break; } } global_bytes_read = global_bytes_read.saturating_add(bytes_read); } // A FileWatcher is dead when the underlying file has disappeared. // If the FileWatcher is dead we don't retain it; it will be deallocated. fp_map.retain(|_file_id, watcher|!watcher.dead()); match stream::iter_ok::<_, ()>(lines.drain(..)) .forward(chans) .wait() { Ok((_, sink)) => chans = sink, Err(_) => unreachable!("Output channel is closed"), } // When no lines have been read we kick the backup_cap up by twice, // limited by the hard-coded cap. Else, we set the backup_cap to its // minimum on the assumption that next time through there will be // more lines to read promptly. if global_bytes_read == 0 { let lim = backoff_cap.saturating_mul(2); if lim > 2_048 { backoff_cap = 2_048; } else { backoff_cap = lim; } } else { backoff_cap = 1; } let backoff = backoff_cap.saturating_sub(global_bytes_read); match shutdown.recv_timeout(time::Duration::from_millis(backoff as u64)) { Ok(()) => unreachable!(), // The sender should never actually send Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => return, } start_of_run = false; } } fn get_fingerprint_of_file( &self, path: &PathBuf, buffer: &mut Vec<u8>, ) -> Option<FileFingerprint> { let i = self.ignored_header_bytes as u64; let b = self.fingerprint_bytes; buffer.resize(b, 0u8); if let Ok(mut fp) = fs::File::open(path) { if fp.seek(SeekFrom::Start(i)).is_ok() && fp.read_exact(&mut buffer[..b]).is_ok() { let fingerprint = crc::crc64::checksum_ecma(&buffer[..b]); Some(fingerprint) } else { None } } else { None } } }
let mut backoff_cap: usize = 1; let mut lines = Vec::new();
random_line_split
debug.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #![allow(dead_code)] #![allow(unused_macros)] /// Low-level functions for testing. // Macro to parse a `Borrow<str>` to an `edn::Value` and assert the given `edn::Value` `matches` // against it. // // This is a macro only to give nice line numbers when tests fail. #[macro_export] macro_rules! assert_matches { ( $input: expr, $expected: expr ) => {{ // Failure to parse the expected pattern is a coding error, so we unwrap. let pattern_value = edn::parse::value($expected.borrow()) .expect(format!("to be able to parse expected {}", $expected).as_str()) .without_spans(); let input_value = $input.to_edn(); assert!( input_value.matches(&pattern_value), "Expected value:\n{}\nto match pattern:\n{}\n", input_value.to_pretty(120).unwrap(), pattern_value.to_pretty(120).unwrap() ); }}; } // Transact $input against the given $conn, expecting success or a `Result<TxReport, String>`. // // This unwraps safely and makes asserting errors pleasant. #[macro_export] macro_rules! assert_transact { ( $conn: expr, $input: expr, $expected: expr ) => {{ trace!("assert_transact: {}", $input); let result = $conn.transact($input).map_err(|e| e.to_string()); assert_eq!(result, $expected.map_err(|e| e.to_string())); }}; ( $conn: expr, $input: expr ) => {{ trace!("assert_transact: {}", $input); let result = $conn.transact($input); assert!( result.is_ok(), "Expected Ok(_), got `{}`", result.unwrap_err() ); result.unwrap() }}; } use std::borrow::Borrow; use std::collections::BTreeMap; use std::io::Write; use itertools::Itertools; use rusqlite; use rusqlite::types::ToSql; use rusqlite::TransactionBehavior; use tabwriter::TabWriter; use crate::bootstrap; use crate::db::*; use crate::db::{read_attribute_map, read_ident_map}; use crate::entids; use db_traits::errors::Result; use edn; use core_traits::{Entid, TypedValue, ValueType}; use crate::internal_types::TermWithTempIds; use crate::schema::SchemaBuilding; use crate::tx::{transact, transact_terms}; use crate::types::*; use crate::watcher::NullWatcher; use edn::entities::{EntidOrIdent, TempId}; use edn::InternSet; use mentat_core::{HasSchema, SQLValueType, TxReport}; /// Represents a *datom* (assertion) in the store. #[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)] pub struct Datom { // TODO: generalize this. pub e: EntidOrIdent, pub a: EntidOrIdent, pub v: edn::Value, pub tx: i64, pub added: Option<bool>, } /// Represents a set of datoms (assertions) in the store. /// /// To make comparision easier, we deterministically order. The ordering is the ascending tuple /// ordering determined by `(e, a, (value_type_tag, v), tx)`, where `value_type_tag` is an internal /// value that is not exposed but is deterministic. pub struct Datoms(pub Vec<Datom>); /// Represents an ordered sequence of transactions in the store. /// /// To make comparision easier, we deterministically order. The ordering is the ascending tuple /// ordering determined by `(e, a, (value_type_tag, v), tx, added)`, where `value_type_tag` is an /// internal value that is not exposed but is deterministic, and `added` is ordered such that /// retracted assertions appear before added assertions. pub struct Transactions(pub Vec<Datoms>); /// Represents the fulltext values in the store. pub struct FulltextValues(pub Vec<(i64, String)>); impl Datom { pub fn to_edn(&self) -> edn::Value { let f = |entid: &EntidOrIdent| -> edn::Value { match *entid { EntidOrIdent::Entid(ref y) => edn::Value::Integer(*y), EntidOrIdent::Ident(ref y) => edn::Value::Keyword(y.clone()), } }; let mut v = vec![f(&self.e), f(&self.a), self.v.clone()]; if let Some(added) = self.added { v.push(edn::Value::Integer(self.tx)); v.push(edn::Value::Boolean(added)); } edn::Value::Vector(v) } } impl Datoms { pub fn to_edn(&self) -> edn::Value { edn::Value::Vector((&self.0).iter().map(|x| x.to_edn()).collect()) } } impl Transactions { pub fn to_edn(&self) -> edn::Value { edn::Value::Vector((&self.0).iter().map(|x| x.to_edn()).collect()) } } impl FulltextValues { pub fn to_edn(&self) -> edn::Value { edn::Value::Vector( (&self.0) .iter() .map(|&(x, ref y)| { edn::Value::Vector(vec![edn::Value::Integer(x), edn::Value::Text(y.clone())]) }) .collect(), ) } } /// Turn TypedValue::Ref into TypedValue::Keyword when it is possible. trait ToIdent { fn map_ident(self, schema: &Schema) -> Self; } impl ToIdent for TypedValue { fn map_ident(self, schema: &Schema) -> Self { if let TypedValue::Ref(e) = self { schema .get_ident(e) .cloned() .map(|i| i.into()) .unwrap_or(TypedValue::Ref(e)) } else { self } } } /// Convert a numeric entid to an ident `Entid` if possible, otherwise a numeric `Entid`. pub fn to_entid(schema: &Schema, entid: i64) -> EntidOrIdent { schema .get_ident(entid) .map_or(EntidOrIdent::Entid(entid), |ident| { EntidOrIdent::Ident(ident.clone()) }) } // /// Convert a symbolic ident to an ident `Entid` if possible, otherwise a numeric `Entid`. // pub fn to_ident(schema: &Schema, entid: i64) -> Entid { // schema.get_ident(entid).map_or(Entid::Entid(entid), |ident| Entid::Ident(ident.clone())) // } /// Return the set of datoms in the store, ordered by (e, a, v, tx), but not including any datoms of /// the form [... :db/txInstant...]. pub fn datoms<S: Borrow<Schema>>(conn: &rusqlite::Connection, schema: &S) -> Result<Datoms> { datoms_after(conn, schema, bootstrap::TX0 - 1) } /// Return the set of datoms in the store with transaction ID strictly greater than the given `tx`, /// ordered by (e, a, v, tx). /// /// The datom set returned does not include any datoms of the form [... :db/txInstant...]. pub fn datoms_after<S: Borrow<Schema>>( conn: &rusqlite::Connection, schema: &S, tx: i64, ) -> Result<Datoms> { let borrowed_schema = schema.borrow(); let mut stmt: rusqlite::Statement = conn.prepare("SELECT e, a, v, value_type_tag, tx FROM datoms WHERE tx >? ORDER BY e ASC, a ASC, value_type_tag ASC, v ASC, tx ASC")?; let r: Result<Vec<_>> = stmt .query_and_then(&[&tx], |row| { let e: i64 = row.get(0)?; let a: i64 = row.get(1)?; if a == entids::DB_TX_INSTANT { return Ok(None); } let v: rusqlite::types::Value = row.get(2)?; let value_type_tag: i32 = row.get(3)?; let attribute = borrowed_schema.require_attribute_for_entid(a)?; let value_type_tag = if!attribute.fulltext { value_type_tag } else { ValueType::Long.value_type_tag() }; let typed_value = TypedValue::from_sql_value_pair(v, value_type_tag)?.map_ident(borrowed_schema); let (value, _) = typed_value.to_edn_value_pair(); let tx: i64 = row.get(4)?; Ok(Some(Datom { e: EntidOrIdent::Entid(e), a: to_entid(borrowed_schema, a), v: value, tx, added: None, })) })? .collect(); Ok(Datoms(r?.into_iter().filter_map(|x| x).collect())) } /// Return the sequence of transactions in the store with transaction ID strictly greater than the /// given `tx`, ordered by (tx, e, a, v). /// /// Each transaction returned includes the [(transaction-tx) :db/txInstant...] datom. pub fn transactions_after<S: Borrow<Schema>>( conn: &rusqlite::Connection, schema: &S, tx: i64, ) -> Result<Transactions> { let borrowed_schema = schema.borrow(); let mut stmt: rusqlite::Statement = conn.prepare("SELECT e, a, v, value_type_tag, tx, added FROM transactions WHERE tx >? ORDER BY tx ASC, e ASC, a ASC, value_type_tag ASC, v ASC, added ASC")?; let r: Result<Vec<_>> = stmt .query_and_then(&[&tx], |row| { let e: i64 = row.get(0)?; let a: i64 = row.get(1)?; let v: rusqlite::types::Value = row.get(2)?; let value_type_tag: i32 = row.get(3)?; let attribute = borrowed_schema.require_attribute_for_entid(a)?; let value_type_tag = if!attribute.fulltext { value_type_tag } else
; let typed_value = TypedValue::from_sql_value_pair(v, value_type_tag)?.map_ident(borrowed_schema); let (value, _) = typed_value.to_edn_value_pair(); let tx: i64 = row.get(4)?; let added: bool = row.get(5)?; Ok(Datom { e: EntidOrIdent::Entid(e), a: to_entid(borrowed_schema, a), v: value, tx, added: Some(added), }) })? .collect(); // Group by tx. let r: Vec<Datoms> = r? .into_iter() .group_by(|x| x.tx) .into_iter() .map(|(_key, group)| Datoms(group.collect())) .collect(); Ok(Transactions(r)) } /// Return the set of fulltext values in the store, ordered by rowid. pub fn fulltext_values(conn: &rusqlite::Connection) -> Result<FulltextValues> { let mut stmt: rusqlite::Statement = conn.prepare("SELECT rowid, text FROM fulltext_values ORDER BY rowid")?; let r: Result<Vec<_>> = stmt .query_and_then([], |row| { let rowid: i64 = row.get(0)?; let text: String = row.get(1)?; Ok((rowid, text)) })? .collect(); r.map(FulltextValues) } /// Execute the given `sql` query with the given `params` and format the results as a /// tab-and-newline formatted string suitable for debug printing. /// /// The query is printed followed by a newline, then the returned columns followed by a newline, and /// then the data rows and columns. All columns are aligned. pub fn dump_sql_query( conn: &rusqlite::Connection, sql: &str, params: &[&dyn ToSql], ) -> Result<String> { let mut stmt: rusqlite::Statement = conn.prepare(sql)?; let mut tw = TabWriter::new(Vec::new()).padding(2); writeln!(&mut tw, "{}", sql).unwrap(); for column_name in stmt.column_names() { write!(&mut tw, "{}\t", column_name).unwrap(); } writeln!(&mut tw).unwrap(); let r: Result<Vec<_>> = stmt .query_and_then(params, |row| { for i in 0..row.as_ref().column_count() { let value: rusqlite::types::Value = row.get(i)?; write!(&mut tw, "{:?}\t", value).unwrap(); } writeln!(&mut tw).unwrap(); Ok(()) })? .collect(); r?; let dump = String::from_utf8(tw.into_inner().unwrap()).unwrap(); Ok(dump) } // A connection that doesn't try to be clever about possibly sharing its `Schema`. Compare to // `mentat::Conn`. pub struct TestConn { pub sqlite: rusqlite::Connection, pub partition_map: PartitionMap, pub schema: Schema, } impl TestConn { fn assert_materialized_views(&self) { let materialized_ident_map = read_ident_map(&self.sqlite).expect("ident map"); let materialized_attribute_map = read_attribute_map(&self.sqlite).expect("schema map"); let materialized_schema = Schema::from_ident_map_and_attribute_map( materialized_ident_map, materialized_attribute_map, ) .expect("schema"); assert_eq!(materialized_schema, self.schema); } pub fn transact<I>(&mut self, transaction: I) -> Result<TxReport> where I: Borrow<str>, { // Failure to parse the transaction is a coding error, so we unwrap. let entities = edn::parse::entities(transaction.borrow()).unwrap_or_else(|_| { panic!("to be able to parse {} into entities", transaction.borrow()) }); let details = { // The block scopes the borrow of self.sqlite. // We're about to write, so go straight ahead and get an IMMEDIATE transaction. let tx = self .sqlite .transaction_with_behavior(TransactionBehavior::Immediate)?; // Applying the transaction can fail, so we don't unwrap. let details = transact( &tx, self.partition_map.clone(), &self.schema, &self.schema, NullWatcher(), entities, )?; tx.commit()?; details }; let (report, next_partition_map, next_schema, _watcher) = details; self.partition_map = next_partition_map; if let Some(next_schema) = next_schema { self.schema = next_schema; } // Verify that we've updated the materialized views during transacting. self.assert_materialized_views(); Ok(report) } pub fn transact_simple_terms<I>( &mut self, terms: I, tempid_set: InternSet<TempId>, ) -> Result<TxReport> where I: IntoIterator<Item = TermWithTempIds>, { let details = { // The block scopes the borrow of self.sqlite. // We're about to write, so go straight ahead and get an IMMEDIATE transaction. let tx = self .sqlite .transaction_with_behavior(TransactionBehavior::Immediate)?; // Applying the transaction can fail, so we don't unwrap. let details = transact_terms( &tx, self.partition_map.clone(), &self.schema, &self.schema, NullWatcher(), terms, tempid_set, )?; tx.commit()?; details }; let (report, next_partition_map, next_schema, _watcher) = details; self.partition_map = next_partition_map; if let Some(next_schema) = next_schema { self.schema = next_schema; } // Verify that we've updated the materialized views during transacting. self.assert_materialized_views(); Ok(report) } pub fn last_tx_id(&self) -> Entid { self.partition_map .get(&":db.part/tx".to_string()) .unwrap() .next_entid() - 1 } pub fn last_transaction(&self) -> Datoms { transactions_after(&self.sqlite, &self.schema, self.last_tx_id() - 1) .expect("last_transaction") .0 .pop() .unwrap() } pub fn transactions(&self) -> Transactions { transactions_after(&self.sqlite, &self.schema, bootstrap::TX0).expect("transactions") } pub fn datoms(&self) -> Datoms { datoms_after(&self.sqlite, &self.schema, bootstrap::TX0).expect("datoms") } pub fn fulltext_values(&self) -> FulltextValues { fulltext_values(&self.sqlite).expect("fulltext_values") } pub fn with_sqlite(mut conn: rusqlite::Connection) -> TestConn { let db = ensure_current_version(&mut conn).unwrap(); // Does not include :db/txInstant. let datoms = datoms_after(&conn, &db.schema, 0).unwrap(); assert_eq!(datoms.0.len(), 94); // Includes :db/txInstant. let transactions = transactions_after(&conn, &db.schema, 0).unwrap(); assert_eq!(transactions.0.len(), 1); assert_eq!(transactions.0[0].0.len(), 95); let mut parts = db.partition_map; // Add a fake partition to allow tests to do things like // [:db/add 111 :foo/bar 222] { let fake_partition = Partition::new(100, 2000, 1000, true); parts.insert(":db.part/fake".into(), fake_partition); } let test_conn = TestConn { sqlite: conn, partition_map: parts, schema: db.schema, }; // Verify that we've created the materialized views during bootstrapping. test_conn.assert_materialized_views(); test_conn } pub fn sanitized_partition_map(&mut self) { self.partition_map.remove(":db.part/fake"); } } impl Default for TestConn { fn default() -> TestConn { TestConn::with_sqlite(new_connection("").expect("Couldn't open in-memory db")) } } pub struct TempIds(edn::Value); impl TempIds { pub fn to_edn(&self) -> edn::Value { self.0.clone() } } pub fn tempids(report: &TxReport) -> TempIds { let mut map: BTreeMap<edn::Value, edn::Value> = BTreeMap::default(); for (tempid, &entid) in report.tempids.iter() { map.insert(edn::Value::Text(tempid.clone()), edn::Value::Integer(entid)); } TempIds(edn::Value::Map(map)) }
{ ValueType::Long.value_type_tag() }
conditional_block
debug.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #![allow(dead_code)] #![allow(unused_macros)] /// Low-level functions for testing. // Macro to parse a `Borrow<str>` to an `edn::Value` and assert the given `edn::Value` `matches` // against it. // // This is a macro only to give nice line numbers when tests fail. #[macro_export] macro_rules! assert_matches { ( $input: expr, $expected: expr ) => {{ // Failure to parse the expected pattern is a coding error, so we unwrap. let pattern_value = edn::parse::value($expected.borrow()) .expect(format!("to be able to parse expected {}", $expected).as_str()) .without_spans(); let input_value = $input.to_edn(); assert!( input_value.matches(&pattern_value), "Expected value:\n{}\nto match pattern:\n{}\n", input_value.to_pretty(120).unwrap(), pattern_value.to_pretty(120).unwrap() ); }}; } // Transact $input against the given $conn, expecting success or a `Result<TxReport, String>`. // // This unwraps safely and makes asserting errors pleasant. #[macro_export] macro_rules! assert_transact { ( $conn: expr, $input: expr, $expected: expr ) => {{ trace!("assert_transact: {}", $input); let result = $conn.transact($input).map_err(|e| e.to_string()); assert_eq!(result, $expected.map_err(|e| e.to_string())); }}; ( $conn: expr, $input: expr ) => {{ trace!("assert_transact: {}", $input); let result = $conn.transact($input); assert!( result.is_ok(), "Expected Ok(_), got `{}`", result.unwrap_err() ); result.unwrap() }}; } use std::borrow::Borrow; use std::collections::BTreeMap; use std::io::Write; use itertools::Itertools; use rusqlite; use rusqlite::types::ToSql; use rusqlite::TransactionBehavior; use tabwriter::TabWriter; use crate::bootstrap; use crate::db::*; use crate::db::{read_attribute_map, read_ident_map}; use crate::entids; use db_traits::errors::Result; use edn; use core_traits::{Entid, TypedValue, ValueType}; use crate::internal_types::TermWithTempIds; use crate::schema::SchemaBuilding; use crate::tx::{transact, transact_terms}; use crate::types::*; use crate::watcher::NullWatcher; use edn::entities::{EntidOrIdent, TempId}; use edn::InternSet; use mentat_core::{HasSchema, SQLValueType, TxReport}; /// Represents a *datom* (assertion) in the store. #[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)] pub struct Datom { // TODO: generalize this. pub e: EntidOrIdent, pub a: EntidOrIdent, pub v: edn::Value, pub tx: i64, pub added: Option<bool>, } /// Represents a set of datoms (assertions) in the store. /// /// To make comparision easier, we deterministically order. The ordering is the ascending tuple /// ordering determined by `(e, a, (value_type_tag, v), tx)`, where `value_type_tag` is an internal /// value that is not exposed but is deterministic. pub struct Datoms(pub Vec<Datom>); /// Represents an ordered sequence of transactions in the store. /// /// To make comparision easier, we deterministically order. The ordering is the ascending tuple /// ordering determined by `(e, a, (value_type_tag, v), tx, added)`, where `value_type_tag` is an /// internal value that is not exposed but is deterministic, and `added` is ordered such that /// retracted assertions appear before added assertions. pub struct Transactions(pub Vec<Datoms>); /// Represents the fulltext values in the store. pub struct FulltextValues(pub Vec<(i64, String)>); impl Datom { pub fn to_edn(&self) -> edn::Value { let f = |entid: &EntidOrIdent| -> edn::Value { match *entid { EntidOrIdent::Entid(ref y) => edn::Value::Integer(*y), EntidOrIdent::Ident(ref y) => edn::Value::Keyword(y.clone()), } }; let mut v = vec![f(&self.e), f(&self.a), self.v.clone()]; if let Some(added) = self.added { v.push(edn::Value::Integer(self.tx)); v.push(edn::Value::Boolean(added)); } edn::Value::Vector(v) } } impl Datoms { pub fn to_edn(&self) -> edn::Value { edn::Value::Vector((&self.0).iter().map(|x| x.to_edn()).collect()) } } impl Transactions { pub fn to_edn(&self) -> edn::Value { edn::Value::Vector((&self.0).iter().map(|x| x.to_edn()).collect()) } } impl FulltextValues { pub fn to_edn(&self) -> edn::Value { edn::Value::Vector( (&self.0) .iter() .map(|&(x, ref y)| { edn::Value::Vector(vec![edn::Value::Integer(x), edn::Value::Text(y.clone())]) }) .collect(), ) } } /// Turn TypedValue::Ref into TypedValue::Keyword when it is possible. trait ToIdent { fn map_ident(self, schema: &Schema) -> Self; } impl ToIdent for TypedValue { fn map_ident(self, schema: &Schema) -> Self { if let TypedValue::Ref(e) = self { schema .get_ident(e) .cloned() .map(|i| i.into()) .unwrap_or(TypedValue::Ref(e)) } else { self } } } /// Convert a numeric entid to an ident `Entid` if possible, otherwise a numeric `Entid`. pub fn to_entid(schema: &Schema, entid: i64) -> EntidOrIdent { schema .get_ident(entid) .map_or(EntidOrIdent::Entid(entid), |ident| { EntidOrIdent::Ident(ident.clone()) }) } // /// Convert a symbolic ident to an ident `Entid` if possible, otherwise a numeric `Entid`. // pub fn to_ident(schema: &Schema, entid: i64) -> Entid { // schema.get_ident(entid).map_or(Entid::Entid(entid), |ident| Entid::Ident(ident.clone())) // } /// Return the set of datoms in the store, ordered by (e, a, v, tx), but not including any datoms of /// the form [... :db/txInstant...]. pub fn datoms<S: Borrow<Schema>>(conn: &rusqlite::Connection, schema: &S) -> Result<Datoms> { datoms_after(conn, schema, bootstrap::TX0 - 1) } /// Return the set of datoms in the store with transaction ID strictly greater than the given `tx`, /// ordered by (e, a, v, tx). /// /// The datom set returned does not include any datoms of the form [... :db/txInstant...]. pub fn datoms_after<S: Borrow<Schema>>( conn: &rusqlite::Connection, schema: &S, tx: i64, ) -> Result<Datoms> { let borrowed_schema = schema.borrow(); let mut stmt: rusqlite::Statement = conn.prepare("SELECT e, a, v, value_type_tag, tx FROM datoms WHERE tx >? ORDER BY e ASC, a ASC, value_type_tag ASC, v ASC, tx ASC")?; let r: Result<Vec<_>> = stmt .query_and_then(&[&tx], |row| { let e: i64 = row.get(0)?; let a: i64 = row.get(1)?; if a == entids::DB_TX_INSTANT { return Ok(None); } let v: rusqlite::types::Value = row.get(2)?; let value_type_tag: i32 = row.get(3)?; let attribute = borrowed_schema.require_attribute_for_entid(a)?; let value_type_tag = if!attribute.fulltext { value_type_tag } else { ValueType::Long.value_type_tag() }; let typed_value = TypedValue::from_sql_value_pair(v, value_type_tag)?.map_ident(borrowed_schema); let (value, _) = typed_value.to_edn_value_pair(); let tx: i64 = row.get(4)?; Ok(Some(Datom { e: EntidOrIdent::Entid(e), a: to_entid(borrowed_schema, a), v: value, tx, added: None, })) })? .collect(); Ok(Datoms(r?.into_iter().filter_map(|x| x).collect())) } /// Return the sequence of transactions in the store with transaction ID strictly greater than the /// given `tx`, ordered by (tx, e, a, v). /// /// Each transaction returned includes the [(transaction-tx) :db/txInstant...] datom. pub fn transactions_after<S: Borrow<Schema>>( conn: &rusqlite::Connection, schema: &S, tx: i64, ) -> Result<Transactions> { let borrowed_schema = schema.borrow(); let mut stmt: rusqlite::Statement = conn.prepare("SELECT e, a, v, value_type_tag, tx, added FROM transactions WHERE tx >? ORDER BY tx ASC, e ASC, a ASC, value_type_tag ASC, v ASC, added ASC")?; let r: Result<Vec<_>> = stmt .query_and_then(&[&tx], |row| { let e: i64 = row.get(0)?; let a: i64 = row.get(1)?; let v: rusqlite::types::Value = row.get(2)?; let value_type_tag: i32 = row.get(3)?; let attribute = borrowed_schema.require_attribute_for_entid(a)?; let value_type_tag = if!attribute.fulltext { value_type_tag } else { ValueType::Long.value_type_tag() }; let typed_value = TypedValue::from_sql_value_pair(v, value_type_tag)?.map_ident(borrowed_schema); let (value, _) = typed_value.to_edn_value_pair(); let tx: i64 = row.get(4)?; let added: bool = row.get(5)?; Ok(Datom { e: EntidOrIdent::Entid(e), a: to_entid(borrowed_schema, a), v: value, tx, added: Some(added), }) })? .collect(); // Group by tx. let r: Vec<Datoms> = r? .into_iter() .group_by(|x| x.tx) .into_iter() .map(|(_key, group)| Datoms(group.collect())) .collect(); Ok(Transactions(r)) } /// Return the set of fulltext values in the store, ordered by rowid. pub fn fulltext_values(conn: &rusqlite::Connection) -> Result<FulltextValues> { let mut stmt: rusqlite::Statement = conn.prepare("SELECT rowid, text FROM fulltext_values ORDER BY rowid")?; let r: Result<Vec<_>> = stmt .query_and_then([], |row| { let rowid: i64 = row.get(0)?; let text: String = row.get(1)?; Ok((rowid, text)) })? .collect(); r.map(FulltextValues) } /// Execute the given `sql` query with the given `params` and format the results as a /// tab-and-newline formatted string suitable for debug printing. /// /// The query is printed followed by a newline, then the returned columns followed by a newline, and /// then the data rows and columns. All columns are aligned. pub fn dump_sql_query( conn: &rusqlite::Connection, sql: &str, params: &[&dyn ToSql], ) -> Result<String> { let mut stmt: rusqlite::Statement = conn.prepare(sql)?; let mut tw = TabWriter::new(Vec::new()).padding(2); writeln!(&mut tw, "{}", sql).unwrap(); for column_name in stmt.column_names() { write!(&mut tw, "{}\t", column_name).unwrap(); } writeln!(&mut tw).unwrap(); let r: Result<Vec<_>> = stmt .query_and_then(params, |row| { for i in 0..row.as_ref().column_count() { let value: rusqlite::types::Value = row.get(i)?; write!(&mut tw, "{:?}\t", value).unwrap(); } writeln!(&mut tw).unwrap(); Ok(()) })? .collect(); r?; let dump = String::from_utf8(tw.into_inner().unwrap()).unwrap(); Ok(dump) } // A connection that doesn't try to be clever about possibly sharing its `Schema`. Compare to // `mentat::Conn`. pub struct TestConn { pub sqlite: rusqlite::Connection, pub partition_map: PartitionMap, pub schema: Schema, } impl TestConn { fn assert_materialized_views(&self) { let materialized_ident_map = read_ident_map(&self.sqlite).expect("ident map"); let materialized_attribute_map = read_attribute_map(&self.sqlite).expect("schema map"); let materialized_schema = Schema::from_ident_map_and_attribute_map( materialized_ident_map, materialized_attribute_map, ) .expect("schema"); assert_eq!(materialized_schema, self.schema); } pub fn transact<I>(&mut self, transaction: I) -> Result<TxReport> where I: Borrow<str>, { // Failure to parse the transaction is a coding error, so we unwrap. let entities = edn::parse::entities(transaction.borrow()).unwrap_or_else(|_| { panic!("to be able to parse {} into entities", transaction.borrow()) }); let details = { // The block scopes the borrow of self.sqlite. // We're about to write, so go straight ahead and get an IMMEDIATE transaction. let tx = self .sqlite .transaction_with_behavior(TransactionBehavior::Immediate)?; // Applying the transaction can fail, so we don't unwrap. let details = transact( &tx, self.partition_map.clone(), &self.schema, &self.schema, NullWatcher(), entities, )?; tx.commit()?; details }; let (report, next_partition_map, next_schema, _watcher) = details; self.partition_map = next_partition_map; if let Some(next_schema) = next_schema { self.schema = next_schema; } // Verify that we've updated the materialized views during transacting. self.assert_materialized_views(); Ok(report) } pub fn
<I>( &mut self, terms: I, tempid_set: InternSet<TempId>, ) -> Result<TxReport> where I: IntoIterator<Item = TermWithTempIds>, { let details = { // The block scopes the borrow of self.sqlite. // We're about to write, so go straight ahead and get an IMMEDIATE transaction. let tx = self .sqlite .transaction_with_behavior(TransactionBehavior::Immediate)?; // Applying the transaction can fail, so we don't unwrap. let details = transact_terms( &tx, self.partition_map.clone(), &self.schema, &self.schema, NullWatcher(), terms, tempid_set, )?; tx.commit()?; details }; let (report, next_partition_map, next_schema, _watcher) = details; self.partition_map = next_partition_map; if let Some(next_schema) = next_schema { self.schema = next_schema; } // Verify that we've updated the materialized views during transacting. self.assert_materialized_views(); Ok(report) } pub fn last_tx_id(&self) -> Entid { self.partition_map .get(&":db.part/tx".to_string()) .unwrap() .next_entid() - 1 } pub fn last_transaction(&self) -> Datoms { transactions_after(&self.sqlite, &self.schema, self.last_tx_id() - 1) .expect("last_transaction") .0 .pop() .unwrap() } pub fn transactions(&self) -> Transactions { transactions_after(&self.sqlite, &self.schema, bootstrap::TX0).expect("transactions") } pub fn datoms(&self) -> Datoms { datoms_after(&self.sqlite, &self.schema, bootstrap::TX0).expect("datoms") } pub fn fulltext_values(&self) -> FulltextValues { fulltext_values(&self.sqlite).expect("fulltext_values") } pub fn with_sqlite(mut conn: rusqlite::Connection) -> TestConn { let db = ensure_current_version(&mut conn).unwrap(); // Does not include :db/txInstant. let datoms = datoms_after(&conn, &db.schema, 0).unwrap(); assert_eq!(datoms.0.len(), 94); // Includes :db/txInstant. let transactions = transactions_after(&conn, &db.schema, 0).unwrap(); assert_eq!(transactions.0.len(), 1); assert_eq!(transactions.0[0].0.len(), 95); let mut parts = db.partition_map; // Add a fake partition to allow tests to do things like // [:db/add 111 :foo/bar 222] { let fake_partition = Partition::new(100, 2000, 1000, true); parts.insert(":db.part/fake".into(), fake_partition); } let test_conn = TestConn { sqlite: conn, partition_map: parts, schema: db.schema, }; // Verify that we've created the materialized views during bootstrapping. test_conn.assert_materialized_views(); test_conn } pub fn sanitized_partition_map(&mut self) { self.partition_map.remove(":db.part/fake"); } } impl Default for TestConn { fn default() -> TestConn { TestConn::with_sqlite(new_connection("").expect("Couldn't open in-memory db")) } } pub struct TempIds(edn::Value); impl TempIds { pub fn to_edn(&self) -> edn::Value { self.0.clone() } } pub fn tempids(report: &TxReport) -> TempIds { let mut map: BTreeMap<edn::Value, edn::Value> = BTreeMap::default(); for (tempid, &entid) in report.tempids.iter() { map.insert(edn::Value::Text(tempid.clone()), edn::Value::Integer(entid)); } TempIds(edn::Value::Map(map)) }
transact_simple_terms
identifier_name
debug.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #![allow(dead_code)] #![allow(unused_macros)] /// Low-level functions for testing. // Macro to parse a `Borrow<str>` to an `edn::Value` and assert the given `edn::Value` `matches` // against it. // // This is a macro only to give nice line numbers when tests fail. #[macro_export] macro_rules! assert_matches { ( $input: expr, $expected: expr ) => {{ // Failure to parse the expected pattern is a coding error, so we unwrap. let pattern_value = edn::parse::value($expected.borrow()) .expect(format!("to be able to parse expected {}", $expected).as_str()) .without_spans(); let input_value = $input.to_edn(); assert!( input_value.matches(&pattern_value), "Expected value:\n{}\nto match pattern:\n{}\n", input_value.to_pretty(120).unwrap(), pattern_value.to_pretty(120).unwrap() ); }}; } // Transact $input against the given $conn, expecting success or a `Result<TxReport, String>`. // // This unwraps safely and makes asserting errors pleasant. #[macro_export] macro_rules! assert_transact { ( $conn: expr, $input: expr, $expected: expr ) => {{ trace!("assert_transact: {}", $input); let result = $conn.transact($input).map_err(|e| e.to_string()); assert_eq!(result, $expected.map_err(|e| e.to_string())); }}; ( $conn: expr, $input: expr ) => {{ trace!("assert_transact: {}", $input); let result = $conn.transact($input); assert!( result.is_ok(), "Expected Ok(_), got `{}`", result.unwrap_err() ); result.unwrap() }}; } use std::borrow::Borrow; use std::collections::BTreeMap; use std::io::Write; use itertools::Itertools; use rusqlite; use rusqlite::types::ToSql; use rusqlite::TransactionBehavior; use tabwriter::TabWriter; use crate::bootstrap; use crate::db::*; use crate::db::{read_attribute_map, read_ident_map}; use crate::entids; use db_traits::errors::Result; use edn; use core_traits::{Entid, TypedValue, ValueType}; use crate::internal_types::TermWithTempIds; use crate::schema::SchemaBuilding; use crate::tx::{transact, transact_terms}; use crate::types::*; use crate::watcher::NullWatcher; use edn::entities::{EntidOrIdent, TempId}; use edn::InternSet; use mentat_core::{HasSchema, SQLValueType, TxReport}; /// Represents a *datom* (assertion) in the store. #[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)] pub struct Datom { // TODO: generalize this. pub e: EntidOrIdent, pub a: EntidOrIdent, pub v: edn::Value, pub tx: i64, pub added: Option<bool>, } /// Represents a set of datoms (assertions) in the store. /// /// To make comparision easier, we deterministically order. The ordering is the ascending tuple /// ordering determined by `(e, a, (value_type_tag, v), tx)`, where `value_type_tag` is an internal /// value that is not exposed but is deterministic. pub struct Datoms(pub Vec<Datom>); /// Represents an ordered sequence of transactions in the store. /// /// To make comparision easier, we deterministically order. The ordering is the ascending tuple /// ordering determined by `(e, a, (value_type_tag, v), tx, added)`, where `value_type_tag` is an /// internal value that is not exposed but is deterministic, and `added` is ordered such that /// retracted assertions appear before added assertions. pub struct Transactions(pub Vec<Datoms>); /// Represents the fulltext values in the store. pub struct FulltextValues(pub Vec<(i64, String)>); impl Datom { pub fn to_edn(&self) -> edn::Value { let f = |entid: &EntidOrIdent| -> edn::Value { match *entid { EntidOrIdent::Entid(ref y) => edn::Value::Integer(*y), EntidOrIdent::Ident(ref y) => edn::Value::Keyword(y.clone()), } }; let mut v = vec![f(&self.e), f(&self.a), self.v.clone()]; if let Some(added) = self.added { v.push(edn::Value::Integer(self.tx)); v.push(edn::Value::Boolean(added)); } edn::Value::Vector(v) } } impl Datoms { pub fn to_edn(&self) -> edn::Value { edn::Value::Vector((&self.0).iter().map(|x| x.to_edn()).collect()) } } impl Transactions { pub fn to_edn(&self) -> edn::Value { edn::Value::Vector((&self.0).iter().map(|x| x.to_edn()).collect()) } } impl FulltextValues { pub fn to_edn(&self) -> edn::Value { edn::Value::Vector( (&self.0) .iter() .map(|&(x, ref y)| { edn::Value::Vector(vec![edn::Value::Integer(x), edn::Value::Text(y.clone())]) }) .collect(), ) } } /// Turn TypedValue::Ref into TypedValue::Keyword when it is possible. trait ToIdent { fn map_ident(self, schema: &Schema) -> Self; } impl ToIdent for TypedValue { fn map_ident(self, schema: &Schema) -> Self { if let TypedValue::Ref(e) = self { schema .get_ident(e) .cloned() .map(|i| i.into()) .unwrap_or(TypedValue::Ref(e)) } else { self } } } /// Convert a numeric entid to an ident `Entid` if possible, otherwise a numeric `Entid`. pub fn to_entid(schema: &Schema, entid: i64) -> EntidOrIdent { schema .get_ident(entid) .map_or(EntidOrIdent::Entid(entid), |ident| { EntidOrIdent::Ident(ident.clone()) }) } // /// Convert a symbolic ident to an ident `Entid` if possible, otherwise a numeric `Entid`. // pub fn to_ident(schema: &Schema, entid: i64) -> Entid { // schema.get_ident(entid).map_or(Entid::Entid(entid), |ident| Entid::Ident(ident.clone())) // } /// Return the set of datoms in the store, ordered by (e, a, v, tx), but not including any datoms of /// the form [... :db/txInstant...]. pub fn datoms<S: Borrow<Schema>>(conn: &rusqlite::Connection, schema: &S) -> Result<Datoms> { datoms_after(conn, schema, bootstrap::TX0 - 1) } /// Return the set of datoms in the store with transaction ID strictly greater than the given `tx`, /// ordered by (e, a, v, tx). /// /// The datom set returned does not include any datoms of the form [... :db/txInstant...]. pub fn datoms_after<S: Borrow<Schema>>( conn: &rusqlite::Connection, schema: &S, tx: i64, ) -> Result<Datoms> { let borrowed_schema = schema.borrow(); let mut stmt: rusqlite::Statement = conn.prepare("SELECT e, a, v, value_type_tag, tx FROM datoms WHERE tx >? ORDER BY e ASC, a ASC, value_type_tag ASC, v ASC, tx ASC")?; let r: Result<Vec<_>> = stmt .query_and_then(&[&tx], |row| { let e: i64 = row.get(0)?; let a: i64 = row.get(1)?; if a == entids::DB_TX_INSTANT { return Ok(None); } let v: rusqlite::types::Value = row.get(2)?; let value_type_tag: i32 = row.get(3)?; let attribute = borrowed_schema.require_attribute_for_entid(a)?; let value_type_tag = if!attribute.fulltext { value_type_tag } else { ValueType::Long.value_type_tag() }; let typed_value = TypedValue::from_sql_value_pair(v, value_type_tag)?.map_ident(borrowed_schema); let (value, _) = typed_value.to_edn_value_pair(); let tx: i64 = row.get(4)?; Ok(Some(Datom { e: EntidOrIdent::Entid(e), a: to_entid(borrowed_schema, a), v: value, tx, added: None, })) })? .collect(); Ok(Datoms(r?.into_iter().filter_map(|x| x).collect())) } /// Return the sequence of transactions in the store with transaction ID strictly greater than the /// given `tx`, ordered by (tx, e, a, v). /// /// Each transaction returned includes the [(transaction-tx) :db/txInstant...] datom. pub fn transactions_after<S: Borrow<Schema>>( conn: &rusqlite::Connection, schema: &S, tx: i64, ) -> Result<Transactions> { let borrowed_schema = schema.borrow(); let mut stmt: rusqlite::Statement = conn.prepare("SELECT e, a, v, value_type_tag, tx, added FROM transactions WHERE tx >? ORDER BY tx ASC, e ASC, a ASC, value_type_tag ASC, v ASC, added ASC")?; let r: Result<Vec<_>> = stmt .query_and_then(&[&tx], |row| { let e: i64 = row.get(0)?; let a: i64 = row.get(1)?; let v: rusqlite::types::Value = row.get(2)?; let value_type_tag: i32 = row.get(3)?; let attribute = borrowed_schema.require_attribute_for_entid(a)?; let value_type_tag = if!attribute.fulltext { value_type_tag } else { ValueType::Long.value_type_tag() }; let typed_value = TypedValue::from_sql_value_pair(v, value_type_tag)?.map_ident(borrowed_schema); let (value, _) = typed_value.to_edn_value_pair(); let tx: i64 = row.get(4)?; let added: bool = row.get(5)?; Ok(Datom { e: EntidOrIdent::Entid(e), a: to_entid(borrowed_schema, a), v: value, tx, added: Some(added), }) })? .collect(); // Group by tx. let r: Vec<Datoms> = r? .into_iter() .group_by(|x| x.tx) .into_iter() .map(|(_key, group)| Datoms(group.collect())) .collect(); Ok(Transactions(r)) } /// Return the set of fulltext values in the store, ordered by rowid. pub fn fulltext_values(conn: &rusqlite::Connection) -> Result<FulltextValues> { let mut stmt: rusqlite::Statement = conn.prepare("SELECT rowid, text FROM fulltext_values ORDER BY rowid")?; let r: Result<Vec<_>> = stmt .query_and_then([], |row| { let rowid: i64 = row.get(0)?; let text: String = row.get(1)?; Ok((rowid, text)) })? .collect(); r.map(FulltextValues) } /// Execute the given `sql` query with the given `params` and format the results as a /// tab-and-newline formatted string suitable for debug printing. /// /// The query is printed followed by a newline, then the returned columns followed by a newline, and /// then the data rows and columns. All columns are aligned. pub fn dump_sql_query( conn: &rusqlite::Connection,
params: &[&dyn ToSql], ) -> Result<String> { let mut stmt: rusqlite::Statement = conn.prepare(sql)?; let mut tw = TabWriter::new(Vec::new()).padding(2); writeln!(&mut tw, "{}", sql).unwrap(); for column_name in stmt.column_names() { write!(&mut tw, "{}\t", column_name).unwrap(); } writeln!(&mut tw).unwrap(); let r: Result<Vec<_>> = stmt .query_and_then(params, |row| { for i in 0..row.as_ref().column_count() { let value: rusqlite::types::Value = row.get(i)?; write!(&mut tw, "{:?}\t", value).unwrap(); } writeln!(&mut tw).unwrap(); Ok(()) })? .collect(); r?; let dump = String::from_utf8(tw.into_inner().unwrap()).unwrap(); Ok(dump) } // A connection that doesn't try to be clever about possibly sharing its `Schema`. Compare to // `mentat::Conn`. pub struct TestConn { pub sqlite: rusqlite::Connection, pub partition_map: PartitionMap, pub schema: Schema, } impl TestConn { fn assert_materialized_views(&self) { let materialized_ident_map = read_ident_map(&self.sqlite).expect("ident map"); let materialized_attribute_map = read_attribute_map(&self.sqlite).expect("schema map"); let materialized_schema = Schema::from_ident_map_and_attribute_map( materialized_ident_map, materialized_attribute_map, ) .expect("schema"); assert_eq!(materialized_schema, self.schema); } pub fn transact<I>(&mut self, transaction: I) -> Result<TxReport> where I: Borrow<str>, { // Failure to parse the transaction is a coding error, so we unwrap. let entities = edn::parse::entities(transaction.borrow()).unwrap_or_else(|_| { panic!("to be able to parse {} into entities", transaction.borrow()) }); let details = { // The block scopes the borrow of self.sqlite. // We're about to write, so go straight ahead and get an IMMEDIATE transaction. let tx = self .sqlite .transaction_with_behavior(TransactionBehavior::Immediate)?; // Applying the transaction can fail, so we don't unwrap. let details = transact( &tx, self.partition_map.clone(), &self.schema, &self.schema, NullWatcher(), entities, )?; tx.commit()?; details }; let (report, next_partition_map, next_schema, _watcher) = details; self.partition_map = next_partition_map; if let Some(next_schema) = next_schema { self.schema = next_schema; } // Verify that we've updated the materialized views during transacting. self.assert_materialized_views(); Ok(report) } pub fn transact_simple_terms<I>( &mut self, terms: I, tempid_set: InternSet<TempId>, ) -> Result<TxReport> where I: IntoIterator<Item = TermWithTempIds>, { let details = { // The block scopes the borrow of self.sqlite. // We're about to write, so go straight ahead and get an IMMEDIATE transaction. let tx = self .sqlite .transaction_with_behavior(TransactionBehavior::Immediate)?; // Applying the transaction can fail, so we don't unwrap. let details = transact_terms( &tx, self.partition_map.clone(), &self.schema, &self.schema, NullWatcher(), terms, tempid_set, )?; tx.commit()?; details }; let (report, next_partition_map, next_schema, _watcher) = details; self.partition_map = next_partition_map; if let Some(next_schema) = next_schema { self.schema = next_schema; } // Verify that we've updated the materialized views during transacting. self.assert_materialized_views(); Ok(report) } pub fn last_tx_id(&self) -> Entid { self.partition_map .get(&":db.part/tx".to_string()) .unwrap() .next_entid() - 1 } pub fn last_transaction(&self) -> Datoms { transactions_after(&self.sqlite, &self.schema, self.last_tx_id() - 1) .expect("last_transaction") .0 .pop() .unwrap() } pub fn transactions(&self) -> Transactions { transactions_after(&self.sqlite, &self.schema, bootstrap::TX0).expect("transactions") } pub fn datoms(&self) -> Datoms { datoms_after(&self.sqlite, &self.schema, bootstrap::TX0).expect("datoms") } pub fn fulltext_values(&self) -> FulltextValues { fulltext_values(&self.sqlite).expect("fulltext_values") } pub fn with_sqlite(mut conn: rusqlite::Connection) -> TestConn { let db = ensure_current_version(&mut conn).unwrap(); // Does not include :db/txInstant. let datoms = datoms_after(&conn, &db.schema, 0).unwrap(); assert_eq!(datoms.0.len(), 94); // Includes :db/txInstant. let transactions = transactions_after(&conn, &db.schema, 0).unwrap(); assert_eq!(transactions.0.len(), 1); assert_eq!(transactions.0[0].0.len(), 95); let mut parts = db.partition_map; // Add a fake partition to allow tests to do things like // [:db/add 111 :foo/bar 222] { let fake_partition = Partition::new(100, 2000, 1000, true); parts.insert(":db.part/fake".into(), fake_partition); } let test_conn = TestConn { sqlite: conn, partition_map: parts, schema: db.schema, }; // Verify that we've created the materialized views during bootstrapping. test_conn.assert_materialized_views(); test_conn } pub fn sanitized_partition_map(&mut self) { self.partition_map.remove(":db.part/fake"); } } impl Default for TestConn { fn default() -> TestConn { TestConn::with_sqlite(new_connection("").expect("Couldn't open in-memory db")) } } pub struct TempIds(edn::Value); impl TempIds { pub fn to_edn(&self) -> edn::Value { self.0.clone() } } pub fn tempids(report: &TxReport) -> TempIds { let mut map: BTreeMap<edn::Value, edn::Value> = BTreeMap::default(); for (tempid, &entid) in report.tempids.iter() { map.insert(edn::Value::Text(tempid.clone()), edn::Value::Integer(entid)); } TempIds(edn::Value::Map(map)) }
sql: &str,
random_line_split
hkdf.rs
// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate alloc; pub use crate::prelude::*; use crate::CryptoProvider; use alloc::vec; use alloc::vec::Vec; use core::iter; use core::marker::PhantomData; use crypto_provider::hkdf::Hkdf; use hex_literal::hex; use rstest_reuse::template; /// Generates the test cases to validate the hkdf implementation. /// For example, to test `MyCryptoProvider`: /// /// ``` /// mod tests { /// use std::marker::PhantomData; /// use crypto_provider::testing::CryptoProviderTestCase; /// #[apply(hkdf_test_cases)] /// fn hkdf_tests(testcase: CryptoProviderTestCase<MyCryptoProvider>){ /// testcase(PhantomData::<MyCryptoProvider>); /// } /// } /// ``` #[template] #[export] #[rstest] #[case::basic_test_hkdf(basic_test_hkdf)] #[case::test_rfc5869_sha256(test_rfc5869_sha256)] #[case::test_lengths(test_lengths)] #[case::test_max_length(test_max_length)] #[case::test_max_length_exceeded(test_max_length_exceeded)] #[case::test_unsupported_length(test_unsupported_length)] #[case::test_expand_multi_info(test_expand_multi_info)] #[case::run_hkdf_sha256_vectors(run_hkdf_sha256_vectors)] #[case::run_hkdf_sha512_vectors(run_hkdf_sha512_vectors)] fn hkdf_test_cases<C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>) {} const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160 /// pub struct Test<'a> { ikm: &'a [u8], salt: &'a [u8], info: &'a [u8], okm: &'a [u8], } /// data taken from sample code in Readme of crates.io page pub fn basic_test_hkdf<C: CryptoProvider>(_: PhantomData<C>) { let ikm = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); let salt = hex!("000102030405060708090a0b0c"); let info = hex!("f0f1f2f3f4f5f6f7f8f9"); let hk = C::HkdfSha256::new(Some(&salt[..]), &ikm); let mut okm = [0u8; 42]; hk.expand(&info, &mut okm) .expect("42 is a valid length for Sha256 to output"); let expected = hex!( " 3cb25f25faacd57a90434f64d0362f2a 2d2d0a90cf1a5a4c5db02d56ecc4c5bf 34007208d5b887185865 " ); assert_eq!(okm, expected); } // Test Vectors from https://tools.ietf.org/html/rfc5869. #[rustfmt::skip] /// pub fn test_rfc5869_sha256<C: CryptoProvider>(_: PhantomData<C>) { let tests = [ Test { // Test Case 1 ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"), salt: &hex!("000102030405060708090a0b0c"), info: &hex!("f0f1f2f3f4f5f6f7f8f9"), okm: &hex!(" 3cb25f25faacd57a90434f64d0362f2a 2d2d0a90cf1a5a4c5db02d56ecc4c5bf
34007208d5b887185865 "), }, Test { // Test Case 2 ikm: &hex!(" 000102030405060708090a0b0c0d0e0f 101112131415161718191a1b1c1d1e1f 202122232425262728292a2b2c2d2e2f 303132333435363738393a3b3c3d3e3f 404142434445464748494a4b4c4d4e4f "), salt: &hex!(" 606162636465666768696a6b6c6d6e6f 707172737475767778797a7b7c7d7e7f 808182838485868788898a8b8c8d8e8f 909192939495969798999a9b9c9d9e9f a0a1a2a3a4a5a6a7a8a9aaabacadaeaf "), info: &hex!(" b0b1b2b3b4b5b6b7b8b9babbbcbdbebf c0c1c2c3c4c5c6c7c8c9cacbcccdcecf d0d1d2d3d4d5d6d7d8d9dadbdcdddedf e0e1e2e3e4e5e6e7e8e9eaebecedeeef f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff "), okm: &hex!(" b11e398dc80327a1c8e7f78c596a4934 4f012eda2d4efad8a050cc4c19afa97c 59045a99cac7827271cb41c65e590e09 da3275600c2f09b8367793a9aca3db71 cc30c58179ec3e87c14c01d5c1f3434f 1d87 "), }, Test { // Test Case 3 ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"), salt: &hex!(""), info: &hex!(""), okm: &hex!(" 8da4e775a563c18f715f802a063c5a31 b8a11f5c5ee1879ec3454e5f3c738d2d 9d201395faa4b61a96c8 "), }, ]; for Test { ikm, salt, info, okm } in tests.iter() { let salt = if salt.is_empty() { None } else { Some(&salt[..]) }; let hkdf = C::HkdfSha256::new(salt, ikm); let mut okm2 = vec![0u8; okm.len()]; assert!(hkdf.expand(&info[..], &mut okm2).is_ok()); assert_eq!(okm2[..], okm[..]); } } /// pub fn test_lengths<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(None, &[]); let mut longest = vec![0u8; MAX_SHA256_LENGTH]; assert!(hkdf.expand(&[], &mut longest).is_ok()); // Runtime is O(length), so exhaustively testing all legal lengths // would take too long (at least without --release). Only test a // subset: the first 500, the last 10, and every 100th in between. // 0 is an invalid key length for openssl, so start at 1 let lengths = (1..MAX_SHA256_LENGTH + 1) .filter(|&len|!(500..=MAX_SHA256_LENGTH - 10).contains(&len) || len % 100 == 0); for length in lengths { let mut okm = vec![0u8; length]; assert!(hkdf.expand(&[], &mut okm).is_ok()); assert_eq!(okm.len(), length); assert_eq!(okm[..], longest[..length]); } } /// pub fn test_max_length<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(Some(&[]), &[]); let mut okm = vec![0u8; MAX_SHA256_LENGTH]; assert!(hkdf.expand(&[], &mut okm).is_ok()); } /// pub fn test_max_length_exceeded<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(Some(&[]), &[]); let mut okm = vec![0u8; MAX_SHA256_LENGTH + 1]; assert!(hkdf.expand(&[], &mut okm).is_err()); } /// pub fn test_unsupported_length<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(Some(&[]), &[]); let mut okm = vec![0u8; 90000]; assert!(hkdf.expand(&[], &mut okm).is_err()); } /// pub fn test_expand_multi_info<C: CryptoProvider>(_: PhantomData<C>) { let info_components = &[ &b"09090909090909090909090909090909090909090909"[..], &b"8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a"[..], &b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"[..], &b"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4"[..], &b"1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d"[..], ]; let hkdf = C::HkdfSha256::new(None, b"some ikm here"); // Compute HKDF-Expand on the concatenation of all the info components let mut oneshot_res = [0u8; 16]; hkdf.expand(&info_components.concat(), &mut oneshot_res) .unwrap(); // Now iteratively join the components of info_components until it's all 1 component. The value // of HKDF-Expand should be the same throughout let mut num_concatted = 0; let mut info_head = Vec::new(); while num_concatted < info_components.len() { info_head.extend(info_components[num_concatted]); // Build the new input to be the info head followed by the remaining components let input: Vec<&[u8]> = iter::once(info_head.as_slice()) .chain(info_components.iter().cloned().skip(num_concatted + 1)) .collect(); // Compute and compare to the one-shot answer let mut multipart_res = [0u8; 16]; hkdf.expand_multi_info(&input, &mut multipart_res).unwrap(); assert_eq!(multipart_res, oneshot_res); num_concatted += 1; } } /// pub fn run_hkdf_sha256_vectors<C: CryptoProvider>(_: PhantomData<C>) { run_hkdf_test_vectors::<C::HkdfSha256>(HashAlg::Sha256) } /// pub fn run_hkdf_sha512_vectors<C: CryptoProvider>(_: PhantomData<C>) { run_hkdf_test_vectors::<C::HkdfSha512>(HashAlg::Sha512) } enum HashAlg { Sha256, Sha512, } /// fn run_hkdf_test_vectors<K: Hkdf>(hash: HashAlg) { let test_name = match hash { HashAlg::Sha256 => wycheproof::hkdf::TestName::HkdfSha256, HashAlg::Sha512 => wycheproof::hkdf::TestName::HkdfSha512, }; let test_set = wycheproof::hkdf::TestSet::load(test_name).expect("should be able to load test set"); for test_group in test_set.test_groups { for test in test_group.tests { let ikm = test.ikm; let salt = test.salt; let info = test.info; let okm = test.okm; let tc_id = test.tc_id; if let Some(desc) = run_test::<K>( ikm.as_slice(), salt.as_slice(), info.as_slice(), okm.as_slice(), ) { panic!( "\n\ Failed test {tc_id}: {desc}\n\ ikm:\t{ikm:?}\n\ salt:\t{salt:?}\n\ info:\t{info:?}\n\ okm:\t{okm:?}\n" ); } } } } fn run_test<K: Hkdf>(ikm: &[u8], salt: &[u8], info: &[u8], okm: &[u8]) -> Option<&'static str> { let prk = K::new(Some(salt), ikm); let mut got_okm = vec![0; okm.len()]; if prk.expand(info, &mut got_okm).is_err() { return Some("prk expand"); } if got_okm!= okm { return Some("mismatch in okm"); } None }
random_line_split
hkdf.rs
// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate alloc; pub use crate::prelude::*; use crate::CryptoProvider; use alloc::vec; use alloc::vec::Vec; use core::iter; use core::marker::PhantomData; use crypto_provider::hkdf::Hkdf; use hex_literal::hex; use rstest_reuse::template; /// Generates the test cases to validate the hkdf implementation. /// For example, to test `MyCryptoProvider`: /// /// ``` /// mod tests { /// use std::marker::PhantomData; /// use crypto_provider::testing::CryptoProviderTestCase; /// #[apply(hkdf_test_cases)] /// fn hkdf_tests(testcase: CryptoProviderTestCase<MyCryptoProvider>){ /// testcase(PhantomData::<MyCryptoProvider>); /// } /// } /// ``` #[template] #[export] #[rstest] #[case::basic_test_hkdf(basic_test_hkdf)] #[case::test_rfc5869_sha256(test_rfc5869_sha256)] #[case::test_lengths(test_lengths)] #[case::test_max_length(test_max_length)] #[case::test_max_length_exceeded(test_max_length_exceeded)] #[case::test_unsupported_length(test_unsupported_length)] #[case::test_expand_multi_info(test_expand_multi_info)] #[case::run_hkdf_sha256_vectors(run_hkdf_sha256_vectors)] #[case::run_hkdf_sha512_vectors(run_hkdf_sha512_vectors)] fn
<C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>) {} const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160 /// pub struct Test<'a> { ikm: &'a [u8], salt: &'a [u8], info: &'a [u8], okm: &'a [u8], } /// data taken from sample code in Readme of crates.io page pub fn basic_test_hkdf<C: CryptoProvider>(_: PhantomData<C>) { let ikm = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); let salt = hex!("000102030405060708090a0b0c"); let info = hex!("f0f1f2f3f4f5f6f7f8f9"); let hk = C::HkdfSha256::new(Some(&salt[..]), &ikm); let mut okm = [0u8; 42]; hk.expand(&info, &mut okm) .expect("42 is a valid length for Sha256 to output"); let expected = hex!( " 3cb25f25faacd57a90434f64d0362f2a 2d2d0a90cf1a5a4c5db02d56ecc4c5bf 34007208d5b887185865 " ); assert_eq!(okm, expected); } // Test Vectors from https://tools.ietf.org/html/rfc5869. #[rustfmt::skip] /// pub fn test_rfc5869_sha256<C: CryptoProvider>(_: PhantomData<C>) { let tests = [ Test { // Test Case 1 ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"), salt: &hex!("000102030405060708090a0b0c"), info: &hex!("f0f1f2f3f4f5f6f7f8f9"), okm: &hex!(" 3cb25f25faacd57a90434f64d0362f2a 2d2d0a90cf1a5a4c5db02d56ecc4c5bf 34007208d5b887185865 "), }, Test { // Test Case 2 ikm: &hex!(" 000102030405060708090a0b0c0d0e0f 101112131415161718191a1b1c1d1e1f 202122232425262728292a2b2c2d2e2f 303132333435363738393a3b3c3d3e3f 404142434445464748494a4b4c4d4e4f "), salt: &hex!(" 606162636465666768696a6b6c6d6e6f 707172737475767778797a7b7c7d7e7f 808182838485868788898a8b8c8d8e8f 909192939495969798999a9b9c9d9e9f a0a1a2a3a4a5a6a7a8a9aaabacadaeaf "), info: &hex!(" b0b1b2b3b4b5b6b7b8b9babbbcbdbebf c0c1c2c3c4c5c6c7c8c9cacbcccdcecf d0d1d2d3d4d5d6d7d8d9dadbdcdddedf e0e1e2e3e4e5e6e7e8e9eaebecedeeef f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff "), okm: &hex!(" b11e398dc80327a1c8e7f78c596a4934 4f012eda2d4efad8a050cc4c19afa97c 59045a99cac7827271cb41c65e590e09 da3275600c2f09b8367793a9aca3db71 cc30c58179ec3e87c14c01d5c1f3434f 1d87 "), }, Test { // Test Case 3 ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"), salt: &hex!(""), info: &hex!(""), okm: &hex!(" 8da4e775a563c18f715f802a063c5a31 b8a11f5c5ee1879ec3454e5f3c738d2d 9d201395faa4b61a96c8 "), }, ]; for Test { ikm, salt, info, okm } in tests.iter() { let salt = if salt.is_empty() { None } else { Some(&salt[..]) }; let hkdf = C::HkdfSha256::new(salt, ikm); let mut okm2 = vec![0u8; okm.len()]; assert!(hkdf.expand(&info[..], &mut okm2).is_ok()); assert_eq!(okm2[..], okm[..]); } } /// pub fn test_lengths<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(None, &[]); let mut longest = vec![0u8; MAX_SHA256_LENGTH]; assert!(hkdf.expand(&[], &mut longest).is_ok()); // Runtime is O(length), so exhaustively testing all legal lengths // would take too long (at least without --release). Only test a // subset: the first 500, the last 10, and every 100th in between. // 0 is an invalid key length for openssl, so start at 1 let lengths = (1..MAX_SHA256_LENGTH + 1) .filter(|&len|!(500..=MAX_SHA256_LENGTH - 10).contains(&len) || len % 100 == 0); for length in lengths { let mut okm = vec![0u8; length]; assert!(hkdf.expand(&[], &mut okm).is_ok()); assert_eq!(okm.len(), length); assert_eq!(okm[..], longest[..length]); } } /// pub fn test_max_length<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(Some(&[]), &[]); let mut okm = vec![0u8; MAX_SHA256_LENGTH]; assert!(hkdf.expand(&[], &mut okm).is_ok()); } /// pub fn test_max_length_exceeded<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(Some(&[]), &[]); let mut okm = vec![0u8; MAX_SHA256_LENGTH + 1]; assert!(hkdf.expand(&[], &mut okm).is_err()); } /// pub fn test_unsupported_length<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(Some(&[]), &[]); let mut okm = vec![0u8; 90000]; assert!(hkdf.expand(&[], &mut okm).is_err()); } /// pub fn test_expand_multi_info<C: CryptoProvider>(_: PhantomData<C>) { let info_components = &[ &b"09090909090909090909090909090909090909090909"[..], &b"8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a"[..], &b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"[..], &b"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4"[..], &b"1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d"[..], ]; let hkdf = C::HkdfSha256::new(None, b"some ikm here"); // Compute HKDF-Expand on the concatenation of all the info components let mut oneshot_res = [0u8; 16]; hkdf.expand(&info_components.concat(), &mut oneshot_res) .unwrap(); // Now iteratively join the components of info_components until it's all 1 component. The value // of HKDF-Expand should be the same throughout let mut num_concatted = 0; let mut info_head = Vec::new(); while num_concatted < info_components.len() { info_head.extend(info_components[num_concatted]); // Build the new input to be the info head followed by the remaining components let input: Vec<&[u8]> = iter::once(info_head.as_slice()) .chain(info_components.iter().cloned().skip(num_concatted + 1)) .collect(); // Compute and compare to the one-shot answer let mut multipart_res = [0u8; 16]; hkdf.expand_multi_info(&input, &mut multipart_res).unwrap(); assert_eq!(multipart_res, oneshot_res); num_concatted += 1; } } /// pub fn run_hkdf_sha256_vectors<C: CryptoProvider>(_: PhantomData<C>) { run_hkdf_test_vectors::<C::HkdfSha256>(HashAlg::Sha256) } /// pub fn run_hkdf_sha512_vectors<C: CryptoProvider>(_: PhantomData<C>) { run_hkdf_test_vectors::<C::HkdfSha512>(HashAlg::Sha512) } enum HashAlg { Sha256, Sha512, } /// fn run_hkdf_test_vectors<K: Hkdf>(hash: HashAlg) { let test_name = match hash { HashAlg::Sha256 => wycheproof::hkdf::TestName::HkdfSha256, HashAlg::Sha512 => wycheproof::hkdf::TestName::HkdfSha512, }; let test_set = wycheproof::hkdf::TestSet::load(test_name).expect("should be able to load test set"); for test_group in test_set.test_groups { for test in test_group.tests { let ikm = test.ikm; let salt = test.salt; let info = test.info; let okm = test.okm; let tc_id = test.tc_id; if let Some(desc) = run_test::<K>( ikm.as_slice(), salt.as_slice(), info.as_slice(), okm.as_slice(), ) { panic!( "\n\ Failed test {tc_id}: {desc}\n\ ikm:\t{ikm:?}\n\ salt:\t{salt:?}\n\ info:\t{info:?}\n\ okm:\t{okm:?}\n" ); } } } } fn run_test<K: Hkdf>(ikm: &[u8], salt: &[u8], info: &[u8], okm: &[u8]) -> Option<&'static str> { let prk = K::new(Some(salt), ikm); let mut got_okm = vec![0; okm.len()]; if prk.expand(info, &mut got_okm).is_err() { return Some("prk expand"); } if got_okm!= okm { return Some("mismatch in okm"); } None }
hkdf_test_cases
identifier_name
hkdf.rs
// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate alloc; pub use crate::prelude::*; use crate::CryptoProvider; use alloc::vec; use alloc::vec::Vec; use core::iter; use core::marker::PhantomData; use crypto_provider::hkdf::Hkdf; use hex_literal::hex; use rstest_reuse::template; /// Generates the test cases to validate the hkdf implementation. /// For example, to test `MyCryptoProvider`: /// /// ``` /// mod tests { /// use std::marker::PhantomData; /// use crypto_provider::testing::CryptoProviderTestCase; /// #[apply(hkdf_test_cases)] /// fn hkdf_tests(testcase: CryptoProviderTestCase<MyCryptoProvider>){ /// testcase(PhantomData::<MyCryptoProvider>); /// } /// } /// ``` #[template] #[export] #[rstest] #[case::basic_test_hkdf(basic_test_hkdf)] #[case::test_rfc5869_sha256(test_rfc5869_sha256)] #[case::test_lengths(test_lengths)] #[case::test_max_length(test_max_length)] #[case::test_max_length_exceeded(test_max_length_exceeded)] #[case::test_unsupported_length(test_unsupported_length)] #[case::test_expand_multi_info(test_expand_multi_info)] #[case::run_hkdf_sha256_vectors(run_hkdf_sha256_vectors)] #[case::run_hkdf_sha512_vectors(run_hkdf_sha512_vectors)] fn hkdf_test_cases<C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>) {} const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160 /// pub struct Test<'a> { ikm: &'a [u8], salt: &'a [u8], info: &'a [u8], okm: &'a [u8], } /// data taken from sample code in Readme of crates.io page pub fn basic_test_hkdf<C: CryptoProvider>(_: PhantomData<C>) { let ikm = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); let salt = hex!("000102030405060708090a0b0c"); let info = hex!("f0f1f2f3f4f5f6f7f8f9"); let hk = C::HkdfSha256::new(Some(&salt[..]), &ikm); let mut okm = [0u8; 42]; hk.expand(&info, &mut okm) .expect("42 is a valid length for Sha256 to output"); let expected = hex!( " 3cb25f25faacd57a90434f64d0362f2a 2d2d0a90cf1a5a4c5db02d56ecc4c5bf 34007208d5b887185865 " ); assert_eq!(okm, expected); } // Test Vectors from https://tools.ietf.org/html/rfc5869. #[rustfmt::skip] /// pub fn test_rfc5869_sha256<C: CryptoProvider>(_: PhantomData<C>) { let tests = [ Test { // Test Case 1 ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"), salt: &hex!("000102030405060708090a0b0c"), info: &hex!("f0f1f2f3f4f5f6f7f8f9"), okm: &hex!(" 3cb25f25faacd57a90434f64d0362f2a 2d2d0a90cf1a5a4c5db02d56ecc4c5bf 34007208d5b887185865 "), }, Test { // Test Case 2 ikm: &hex!(" 000102030405060708090a0b0c0d0e0f 101112131415161718191a1b1c1d1e1f 202122232425262728292a2b2c2d2e2f 303132333435363738393a3b3c3d3e3f 404142434445464748494a4b4c4d4e4f "), salt: &hex!(" 606162636465666768696a6b6c6d6e6f 707172737475767778797a7b7c7d7e7f 808182838485868788898a8b8c8d8e8f 909192939495969798999a9b9c9d9e9f a0a1a2a3a4a5a6a7a8a9aaabacadaeaf "), info: &hex!(" b0b1b2b3b4b5b6b7b8b9babbbcbdbebf c0c1c2c3c4c5c6c7c8c9cacbcccdcecf d0d1d2d3d4d5d6d7d8d9dadbdcdddedf e0e1e2e3e4e5e6e7e8e9eaebecedeeef f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff "), okm: &hex!(" b11e398dc80327a1c8e7f78c596a4934 4f012eda2d4efad8a050cc4c19afa97c 59045a99cac7827271cb41c65e590e09 da3275600c2f09b8367793a9aca3db71 cc30c58179ec3e87c14c01d5c1f3434f 1d87 "), }, Test { // Test Case 3 ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"), salt: &hex!(""), info: &hex!(""), okm: &hex!(" 8da4e775a563c18f715f802a063c5a31 b8a11f5c5ee1879ec3454e5f3c738d2d 9d201395faa4b61a96c8 "), }, ]; for Test { ikm, salt, info, okm } in tests.iter() { let salt = if salt.is_empty() { None } else { Some(&salt[..]) }; let hkdf = C::HkdfSha256::new(salt, ikm); let mut okm2 = vec![0u8; okm.len()]; assert!(hkdf.expand(&info[..], &mut okm2).is_ok()); assert_eq!(okm2[..], okm[..]); } } /// pub fn test_lengths<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(None, &[]); let mut longest = vec![0u8; MAX_SHA256_LENGTH]; assert!(hkdf.expand(&[], &mut longest).is_ok()); // Runtime is O(length), so exhaustively testing all legal lengths // would take too long (at least without --release). Only test a // subset: the first 500, the last 10, and every 100th in between. // 0 is an invalid key length for openssl, so start at 1 let lengths = (1..MAX_SHA256_LENGTH + 1) .filter(|&len|!(500..=MAX_SHA256_LENGTH - 10).contains(&len) || len % 100 == 0); for length in lengths { let mut okm = vec![0u8; length]; assert!(hkdf.expand(&[], &mut okm).is_ok()); assert_eq!(okm.len(), length); assert_eq!(okm[..], longest[..length]); } } /// pub fn test_max_length<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(Some(&[]), &[]); let mut okm = vec![0u8; MAX_SHA256_LENGTH]; assert!(hkdf.expand(&[], &mut okm).is_ok()); } /// pub fn test_max_length_exceeded<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(Some(&[]), &[]); let mut okm = vec![0u8; MAX_SHA256_LENGTH + 1]; assert!(hkdf.expand(&[], &mut okm).is_err()); } /// pub fn test_unsupported_length<C: CryptoProvider>(_: PhantomData<C>) { let hkdf = C::HkdfSha256::new(Some(&[]), &[]); let mut okm = vec![0u8; 90000]; assert!(hkdf.expand(&[], &mut okm).is_err()); } /// pub fn test_expand_multi_info<C: CryptoProvider>(_: PhantomData<C>) { let info_components = &[ &b"09090909090909090909090909090909090909090909"[..], &b"8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a"[..], &b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"[..], &b"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4"[..], &b"1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d"[..], ]; let hkdf = C::HkdfSha256::new(None, b"some ikm here"); // Compute HKDF-Expand on the concatenation of all the info components let mut oneshot_res = [0u8; 16]; hkdf.expand(&info_components.concat(), &mut oneshot_res) .unwrap(); // Now iteratively join the components of info_components until it's all 1 component. The value // of HKDF-Expand should be the same throughout let mut num_concatted = 0; let mut info_head = Vec::new(); while num_concatted < info_components.len() { info_head.extend(info_components[num_concatted]); // Build the new input to be the info head followed by the remaining components let input: Vec<&[u8]> = iter::once(info_head.as_slice()) .chain(info_components.iter().cloned().skip(num_concatted + 1)) .collect(); // Compute and compare to the one-shot answer let mut multipart_res = [0u8; 16]; hkdf.expand_multi_info(&input, &mut multipart_res).unwrap(); assert_eq!(multipart_res, oneshot_res); num_concatted += 1; } } /// pub fn run_hkdf_sha256_vectors<C: CryptoProvider>(_: PhantomData<C>) { run_hkdf_test_vectors::<C::HkdfSha256>(HashAlg::Sha256) } /// pub fn run_hkdf_sha512_vectors<C: CryptoProvider>(_: PhantomData<C>) { run_hkdf_test_vectors::<C::HkdfSha512>(HashAlg::Sha512) } enum HashAlg { Sha256, Sha512, } /// fn run_hkdf_test_vectors<K: Hkdf>(hash: HashAlg) { let test_name = match hash { HashAlg::Sha256 => wycheproof::hkdf::TestName::HkdfSha256, HashAlg::Sha512 => wycheproof::hkdf::TestName::HkdfSha512, }; let test_set = wycheproof::hkdf::TestSet::load(test_name).expect("should be able to load test set"); for test_group in test_set.test_groups { for test in test_group.tests { let ikm = test.ikm; let salt = test.salt; let info = test.info; let okm = test.okm; let tc_id = test.tc_id; if let Some(desc) = run_test::<K>( ikm.as_slice(), salt.as_slice(), info.as_slice(), okm.as_slice(), )
} } } fn run_test<K: Hkdf>(ikm: &[u8], salt: &[u8], info: &[u8], okm: &[u8]) -> Option<&'static str> { let prk = K::new(Some(salt), ikm); let mut got_okm = vec![0; okm.len()]; if prk.expand(info, &mut got_okm).is_err() { return Some("prk expand"); } if got_okm!= okm { return Some("mismatch in okm"); } None }
{ panic!( "\n\ Failed test {tc_id}: {desc}\n\ ikm:\t{ikm:?}\n\ salt:\t{salt:?}\n\ info:\t{info:?}\n\ okm:\t{okm:?}\n" ); }
conditional_block
msg.rs
use super::{nlmsg_length, nlmsg_header_length}; use std::fmt; use std::mem::size_of; use std::slice::from_raw_parts; use std::io::{self, ErrorKind, Cursor}; use byteorder::{NativeEndian, ReadBytesExt}; #[derive(Clone, Copy, Debug)] pub enum MsgType { /// Request Request, /// No op Noop, /// Error Error, /// End of a dump Done, /// Data lost Overrun, /// minimum type, below 10 for reserved control messages MinType, /// User defined type, passed to the user UserDefined(u16), } impl Into<u16> for MsgType { fn into(self) -> u16 { use self::MsgType::*; match self { Request => 0, Noop => 1, Error => 2, Done => 3, Overrun => 4, MinType => 10, UserDefined(i) => i, } } } impl From<u16> for MsgType { fn from(t: u16) -> MsgType { use self::MsgType::*; match t { 0 => Request, 1 => Noop, 2 => Error, 3 => Done, 4 => Overrun, 10 => MinType, i => UserDefined(i), } } } #[derive(Clone, Copy, Debug)] enum Flags { /// It is request message. Request, /// Multipart message, terminated by NLMSG_DONE Multi, /// Reply with ack, with zero or error code Ack, /// Echo this request Echo, } impl Into<u16> for Flags { fn into(self) -> u16 { use self::Flags::*; match self { Request => 1, Multi => 2, Ack => 4, Echo => 8, } } } /// Modifiers to GET request #[derive(Clone, Copy, Debug)] enum GetFlags { /// specify tree root Root, /// return all matching Match, /// atomic GET Atomic, /// (Root|Match) Dump, } impl Into<u16> for GetFlags { fn into(self) -> u16 { use self::GetFlags::*; match self { Root => 0x100, Match => 0x200, Atomic => 0x400, Dump => 0x100 | 0x200, } } } /// Modifiers to NEW request #[derive(Clone, Copy, Debug)] enum NewFlags { /// Override existing Replace, /// Do not touch, if it exists Excl, /// Create, if it does not exist Create, /// Add to end of list Append, } impl Into<u16> for NewFlags { fn into(self) -> u16 { use self::NewFlags::*; match self { Replace => 0x100, Excl => 0x200, Create => 0x400, Append => 0x800, } } } // HEADER FORMAT // __u32 nlmsg_len; /* Length of message including header. */ // __u16 nlmsg_type; /* Type of message content. */ // __u16 nlmsg_flags; /* Additional flags. */ // __u32 nlmsg_seq; /* Sequence number. */ // __u32 nlmsg_pid; /* Sender port ID. */ #[repr(C)] #[derive(Clone, Copy, Eq, PartialEq)] pub struct NlMsgHeader { msg_length: u32, nl_type: u16, flags: u16, seq: u32, pid: u32, } impl fmt::Debug for NlMsgHeader { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "<NlMsgHeader len={} {:?} flags=[ ", self.msg_length, MsgType::from(self.nl_type))); // output readable flags if self.flags & 1!= 0 { try!(write!(f, "Request ")); } if self.flags & 2!= 0 { try!(write!(f, "Multi ")); } if self.flags & 4!= 0 { try!(write!(f, "Ack ")); } if self.flags & 8!= 0 { try!(write!(f, "Echo ")); } if self.flags >> 4!= 0 { try!(write!(f, "other({:#X})", self.flags)); } try!(write!(f, "] seq={} pid={}>", self.seq, self.pid)); Ok(()) } } impl NlMsgHeader { pub fn user_defined(t: u16, data_length: u32) -> NlMsgHeader { let mut h = NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: t, flags: Flags::Request.into(), seq: 0, pid: 0, }; h.data_length(data_length); h } pub fn request() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Request.into(), flags: Flags::Request.into(), seq: 0, pid: 0, } } pub fn done() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Done.into(), flags: Flags::Multi.into(), seq: 0, pid: 0, } } pub fn error() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_length(nlmsg_header_length() + 4) as u32, // nlmsgerr nl_type: MsgType::Error.into(), flags: 0, seq: 0, pid: 0, } } pub fn from_bytes(bytes: &[u8]) -> io::Result<(NlMsgHeader, usize)> { let mut cursor = Cursor::new(bytes); let len = try!(cursor.read_u32::<NativeEndian>()); let nl_type = try!(cursor.read_u16::<NativeEndian>()); let flags = try!(cursor.read_u16::<NativeEndian>()); let seq = try!(cursor.read_u32::<NativeEndian>()); let pid = try!(cursor.read_u32::<NativeEndian>()); if len < nlmsg_header_length() as u32 { Err(io::Error::new(ErrorKind::InvalidInput, "length smaller than msg header size")) } else { Ok((NlMsgHeader{ msg_length: len, nl_type: nl_type, flags: flags, seq: seq, pid: pid, }, cursor.position() as usize)) } } pub fn bytes(&self) -> &[u8] { let size = size_of::<NlMsgHeader>(); unsafe { let head = self as *const NlMsgHeader as *const u8; from_raw_parts(head, size) } } pub fn msg_type(&self) -> MsgType { self.nl_type.into() } pub fn msg_length(&self) -> u32 { self.msg_length } /// Set message length pub fn data_length(&mut self, len: u32) -> &mut NlMsgHeader { self.msg_length = nlmsg_length(len as usize) as u32; self } /// Multipart message pub fn multipart(&mut self) -> &mut NlMsgHeader { self.flags |= Flags::Multi.into(); self } /// Request acknowledgement pub fn ack(&mut self) -> &mut NlMsgHeader { self.flags |= Flags::Ack.into(); self } /// Echo message pub fn echo(&mut self) -> &mut NlMsgHeader { self.flags |= Flags::Echo.into(); self } /// Set sequence number pub fn seq(&mut self, n: u32) -> &mut NlMsgHeader { self.seq = n; self } /// Set PID number pub fn pid(&mut self, n: u32) -> &mut NlMsgHeader { self.pid = n; self } /// Override existing pub fn replace(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Replace.into(); self } /// Do not touch, if it exists pub fn excl(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Excl.into(); self } /// Create, if it does not exist pub fn create(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Create.into(); self } /// Add to end of list pub fn append(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Append.into(); self } /// specify tree root pub fn root(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Root.into(); self } /// return all matching pub fn match_provided(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Match.into(); self } /// atomic GET pub fn atomic(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Atomic.into(); self } /// (Root|Match) pub fn
(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Dump.into(); self } } /* http://linux.die.net/include/linux/netlink.h /* Flags values */ #define NLM_F_REQUEST 1 /* It is request message. */ #define NLM_F_MULTI 2 /* Multipart message, terminated by NLMSG_DONE */ #define NLM_F_ACK 4 /* Reply with ack, with zero or error code */ #define NLM_F_ECHO 8 /* Echo this request */ /* Modifiers to GET request */ #define NLM_F_ROOT 0x100 /* specify tree root */ #define NLM_F_MATCH 0x200 /* return all matching */ #define NLM_F_ATOMIC 0x400 /* atomic GET */ #define NLM_F_DUMP (NLM_F_ROOT|NLM_F_MATCH) /* Modifiers to NEW request */ #define NLM_F_REPLACE 0x100 /* Override existing */ #define NLM_F_EXCL 0x200 /* Do not touch, if it exists */ #define NLM_F_CREATE 0x400 /* Create, if it does not exist */ #define NLM_F_APPEND 0x800 /* Add to end of list */ /* 4.4BSD ADD NLM_F_CREATE|NLM_F_EXCL 4.4BSD CHANGE NLM_F_REPLACE True CHANGE NLM_F_CREATE|NLM_F_REPLACE Append NLM_F_CREATE Check NLM_F_EXCL */ #define NLMSG_NOOP 0x1 /* Nothing. */ #define NLMSG_ERROR 0x2 /* Error */ #define NLMSG_DONE 0x3 /* End of a dump */ #define NLMSG_OVERRUN 0x4 /* Data lost */ #define NLMSG_MIN_TYPE 0x10 /* < 0x10: reserved control messages */ */ #[cfg(test)] mod tests { use super::*; #[test] fn test_encoding() { // Little endian only right now let expected = [20, 0, 0, 0, 0, 0, 1, 3, 1, 0, 0, 0, 9, 0, 0, 0]; let mut hdr = NlMsgHeader::request(); let bytes = hdr.data_length(4).pid(9).seq(1).dump().bytes(); assert_eq!(bytes, expected); } #[test] fn test_decoding() { // Little endian only right now let bytes = [16, 0, 0, 0, 0, 0, 1, 3, 1, 0, 0, 0, 9, 0, 0, 0, 1, 1, 1]; let mut h = NlMsgHeader::request(); let expected = h.data_length(0).pid(9).seq(1).dump(); let (hdr, n) = NlMsgHeader::from_bytes(&bytes).unwrap(); assert_eq!(hdr, *expected); assert_eq!(n, 16); } #[test] fn test_decoding_error() { // Little endian only right now let bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; let res = NlMsgHeader::from_bytes(&bytes); assert!(res.is_err()); } }
dump
identifier_name
msg.rs
use super::{nlmsg_length, nlmsg_header_length}; use std::fmt; use std::mem::size_of; use std::slice::from_raw_parts; use std::io::{self, ErrorKind, Cursor}; use byteorder::{NativeEndian, ReadBytesExt}; #[derive(Clone, Copy, Debug)] pub enum MsgType { /// Request Request, /// No op Noop, /// Error Error, /// End of a dump Done, /// Data lost Overrun, /// minimum type, below 10 for reserved control messages MinType, /// User defined type, passed to the user UserDefined(u16), } impl Into<u16> for MsgType { fn into(self) -> u16 { use self::MsgType::*; match self { Request => 0, Noop => 1, Error => 2, Done => 3, Overrun => 4, MinType => 10, UserDefined(i) => i, } } } impl From<u16> for MsgType { fn from(t: u16) -> MsgType { use self::MsgType::*; match t { 0 => Request, 1 => Noop, 2 => Error, 3 => Done, 4 => Overrun, 10 => MinType, i => UserDefined(i), } } } #[derive(Clone, Copy, Debug)] enum Flags { /// It is request message. Request, /// Multipart message, terminated by NLMSG_DONE Multi, /// Reply with ack, with zero or error code Ack, /// Echo this request Echo, } impl Into<u16> for Flags { fn into(self) -> u16 { use self::Flags::*; match self { Request => 1, Multi => 2, Ack => 4, Echo => 8, } } } /// Modifiers to GET request #[derive(Clone, Copy, Debug)] enum GetFlags { /// specify tree root Root, /// return all matching Match, /// atomic GET Atomic, /// (Root|Match) Dump, } impl Into<u16> for GetFlags { fn into(self) -> u16 { use self::GetFlags::*; match self { Root => 0x100, Match => 0x200, Atomic => 0x400, Dump => 0x100 | 0x200, } } } /// Modifiers to NEW request #[derive(Clone, Copy, Debug)] enum NewFlags { /// Override existing Replace, /// Do not touch, if it exists Excl, /// Create, if it does not exist Create, /// Add to end of list Append, } impl Into<u16> for NewFlags { fn into(self) -> u16 { use self::NewFlags::*; match self { Replace => 0x100, Excl => 0x200, Create => 0x400, Append => 0x800, } } } // HEADER FORMAT // __u32 nlmsg_len; /* Length of message including header. */ // __u16 nlmsg_type; /* Type of message content. */ // __u16 nlmsg_flags; /* Additional flags. */ // __u32 nlmsg_seq; /* Sequence number. */ // __u32 nlmsg_pid; /* Sender port ID. */ #[repr(C)] #[derive(Clone, Copy, Eq, PartialEq)] pub struct NlMsgHeader { msg_length: u32,
nl_type: u16, flags: u16, seq: u32, pid: u32, } impl fmt::Debug for NlMsgHeader { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "<NlMsgHeader len={} {:?} flags=[ ", self.msg_length, MsgType::from(self.nl_type))); // output readable flags if self.flags & 1!= 0 { try!(write!(f, "Request ")); } if self.flags & 2!= 0 { try!(write!(f, "Multi ")); } if self.flags & 4!= 0 { try!(write!(f, "Ack ")); } if self.flags & 8!= 0 { try!(write!(f, "Echo ")); } if self.flags >> 4!= 0 { try!(write!(f, "other({:#X})", self.flags)); } try!(write!(f, "] seq={} pid={}>", self.seq, self.pid)); Ok(()) } } impl NlMsgHeader { pub fn user_defined(t: u16, data_length: u32) -> NlMsgHeader { let mut h = NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: t, flags: Flags::Request.into(), seq: 0, pid: 0, }; h.data_length(data_length); h } pub fn request() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Request.into(), flags: Flags::Request.into(), seq: 0, pid: 0, } } pub fn done() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Done.into(), flags: Flags::Multi.into(), seq: 0, pid: 0, } } pub fn error() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_length(nlmsg_header_length() + 4) as u32, // nlmsgerr nl_type: MsgType::Error.into(), flags: 0, seq: 0, pid: 0, } } pub fn from_bytes(bytes: &[u8]) -> io::Result<(NlMsgHeader, usize)> { let mut cursor = Cursor::new(bytes); let len = try!(cursor.read_u32::<NativeEndian>()); let nl_type = try!(cursor.read_u16::<NativeEndian>()); let flags = try!(cursor.read_u16::<NativeEndian>()); let seq = try!(cursor.read_u32::<NativeEndian>()); let pid = try!(cursor.read_u32::<NativeEndian>()); if len < nlmsg_header_length() as u32 { Err(io::Error::new(ErrorKind::InvalidInput, "length smaller than msg header size")) } else { Ok((NlMsgHeader{ msg_length: len, nl_type: nl_type, flags: flags, seq: seq, pid: pid, }, cursor.position() as usize)) } } pub fn bytes(&self) -> &[u8] { let size = size_of::<NlMsgHeader>(); unsafe { let head = self as *const NlMsgHeader as *const u8; from_raw_parts(head, size) } } pub fn msg_type(&self) -> MsgType { self.nl_type.into() } pub fn msg_length(&self) -> u32 { self.msg_length } /// Set message length pub fn data_length(&mut self, len: u32) -> &mut NlMsgHeader { self.msg_length = nlmsg_length(len as usize) as u32; self } /// Multipart message pub fn multipart(&mut self) -> &mut NlMsgHeader { self.flags |= Flags::Multi.into(); self } /// Request acknowledgement pub fn ack(&mut self) -> &mut NlMsgHeader { self.flags |= Flags::Ack.into(); self } /// Echo message pub fn echo(&mut self) -> &mut NlMsgHeader { self.flags |= Flags::Echo.into(); self } /// Set sequence number pub fn seq(&mut self, n: u32) -> &mut NlMsgHeader { self.seq = n; self } /// Set PID number pub fn pid(&mut self, n: u32) -> &mut NlMsgHeader { self.pid = n; self } /// Override existing pub fn replace(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Replace.into(); self } /// Do not touch, if it exists pub fn excl(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Excl.into(); self } /// Create, if it does not exist pub fn create(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Create.into(); self } /// Add to end of list pub fn append(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Append.into(); self } /// specify tree root pub fn root(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Root.into(); self } /// return all matching pub fn match_provided(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Match.into(); self } /// atomic GET pub fn atomic(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Atomic.into(); self } /// (Root|Match) pub fn dump(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Dump.into(); self } } /* http://linux.die.net/include/linux/netlink.h /* Flags values */ #define NLM_F_REQUEST 1 /* It is request message. */ #define NLM_F_MULTI 2 /* Multipart message, terminated by NLMSG_DONE */ #define NLM_F_ACK 4 /* Reply with ack, with zero or error code */ #define NLM_F_ECHO 8 /* Echo this request */ /* Modifiers to GET request */ #define NLM_F_ROOT 0x100 /* specify tree root */ #define NLM_F_MATCH 0x200 /* return all matching */ #define NLM_F_ATOMIC 0x400 /* atomic GET */ #define NLM_F_DUMP (NLM_F_ROOT|NLM_F_MATCH) /* Modifiers to NEW request */ #define NLM_F_REPLACE 0x100 /* Override existing */ #define NLM_F_EXCL 0x200 /* Do not touch, if it exists */ #define NLM_F_CREATE 0x400 /* Create, if it does not exist */ #define NLM_F_APPEND 0x800 /* Add to end of list */ /* 4.4BSD ADD NLM_F_CREATE|NLM_F_EXCL 4.4BSD CHANGE NLM_F_REPLACE True CHANGE NLM_F_CREATE|NLM_F_REPLACE Append NLM_F_CREATE Check NLM_F_EXCL */ #define NLMSG_NOOP 0x1 /* Nothing. */ #define NLMSG_ERROR 0x2 /* Error */ #define NLMSG_DONE 0x3 /* End of a dump */ #define NLMSG_OVERRUN 0x4 /* Data lost */ #define NLMSG_MIN_TYPE 0x10 /* < 0x10: reserved control messages */ */ #[cfg(test)] mod tests { use super::*; #[test] fn test_encoding() { // Little endian only right now let expected = [20, 0, 0, 0, 0, 0, 1, 3, 1, 0, 0, 0, 9, 0, 0, 0]; let mut hdr = NlMsgHeader::request(); let bytes = hdr.data_length(4).pid(9).seq(1).dump().bytes(); assert_eq!(bytes, expected); } #[test] fn test_decoding() { // Little endian only right now let bytes = [16, 0, 0, 0, 0, 0, 1, 3, 1, 0, 0, 0, 9, 0, 0, 0, 1, 1, 1]; let mut h = NlMsgHeader::request(); let expected = h.data_length(0).pid(9).seq(1).dump(); let (hdr, n) = NlMsgHeader::from_bytes(&bytes).unwrap(); assert_eq!(hdr, *expected); assert_eq!(n, 16); } #[test] fn test_decoding_error() { // Little endian only right now let bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; let res = NlMsgHeader::from_bytes(&bytes); assert!(res.is_err()); } }
random_line_split
msg.rs
use super::{nlmsg_length, nlmsg_header_length}; use std::fmt; use std::mem::size_of; use std::slice::from_raw_parts; use std::io::{self, ErrorKind, Cursor}; use byteorder::{NativeEndian, ReadBytesExt}; #[derive(Clone, Copy, Debug)] pub enum MsgType { /// Request Request, /// No op Noop, /// Error Error, /// End of a dump Done, /// Data lost Overrun, /// minimum type, below 10 for reserved control messages MinType, /// User defined type, passed to the user UserDefined(u16), } impl Into<u16> for MsgType { fn into(self) -> u16 { use self::MsgType::*; match self { Request => 0, Noop => 1, Error => 2, Done => 3, Overrun => 4, MinType => 10, UserDefined(i) => i, } } } impl From<u16> for MsgType { fn from(t: u16) -> MsgType { use self::MsgType::*; match t { 0 => Request, 1 => Noop, 2 => Error, 3 => Done, 4 => Overrun, 10 => MinType, i => UserDefined(i), } } } #[derive(Clone, Copy, Debug)] enum Flags { /// It is request message. Request, /// Multipart message, terminated by NLMSG_DONE Multi, /// Reply with ack, with zero or error code Ack, /// Echo this request Echo, } impl Into<u16> for Flags { fn into(self) -> u16 { use self::Flags::*; match self { Request => 1, Multi => 2, Ack => 4, Echo => 8, } } } /// Modifiers to GET request #[derive(Clone, Copy, Debug)] enum GetFlags { /// specify tree root Root, /// return all matching Match, /// atomic GET Atomic, /// (Root|Match) Dump, } impl Into<u16> for GetFlags { fn into(self) -> u16 { use self::GetFlags::*; match self { Root => 0x100, Match => 0x200, Atomic => 0x400, Dump => 0x100 | 0x200, } } } /// Modifiers to NEW request #[derive(Clone, Copy, Debug)] enum NewFlags { /// Override existing Replace, /// Do not touch, if it exists Excl, /// Create, if it does not exist Create, /// Add to end of list Append, } impl Into<u16> for NewFlags { fn into(self) -> u16 { use self::NewFlags::*; match self { Replace => 0x100, Excl => 0x200, Create => 0x400, Append => 0x800, } } } // HEADER FORMAT // __u32 nlmsg_len; /* Length of message including header. */ // __u16 nlmsg_type; /* Type of message content. */ // __u16 nlmsg_flags; /* Additional flags. */ // __u32 nlmsg_seq; /* Sequence number. */ // __u32 nlmsg_pid; /* Sender port ID. */ #[repr(C)] #[derive(Clone, Copy, Eq, PartialEq)] pub struct NlMsgHeader { msg_length: u32, nl_type: u16, flags: u16, seq: u32, pid: u32, } impl fmt::Debug for NlMsgHeader { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "<NlMsgHeader len={} {:?} flags=[ ", self.msg_length, MsgType::from(self.nl_type))); // output readable flags if self.flags & 1!= 0 { try!(write!(f, "Request ")); } if self.flags & 2!= 0 { try!(write!(f, "Multi ")); } if self.flags & 4!= 0 { try!(write!(f, "Ack ")); } if self.flags & 8!= 0 { try!(write!(f, "Echo ")); } if self.flags >> 4!= 0 { try!(write!(f, "other({:#X})", self.flags)); } try!(write!(f, "] seq={} pid={}>", self.seq, self.pid)); Ok(()) } } impl NlMsgHeader { pub fn user_defined(t: u16, data_length: u32) -> NlMsgHeader { let mut h = NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: t, flags: Flags::Request.into(), seq: 0, pid: 0, }; h.data_length(data_length); h } pub fn request() -> NlMsgHeader
pub fn done() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Done.into(), flags: Flags::Multi.into(), seq: 0, pid: 0, } } pub fn error() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_length(nlmsg_header_length() + 4) as u32, // nlmsgerr nl_type: MsgType::Error.into(), flags: 0, seq: 0, pid: 0, } } pub fn from_bytes(bytes: &[u8]) -> io::Result<(NlMsgHeader, usize)> { let mut cursor = Cursor::new(bytes); let len = try!(cursor.read_u32::<NativeEndian>()); let nl_type = try!(cursor.read_u16::<NativeEndian>()); let flags = try!(cursor.read_u16::<NativeEndian>()); let seq = try!(cursor.read_u32::<NativeEndian>()); let pid = try!(cursor.read_u32::<NativeEndian>()); if len < nlmsg_header_length() as u32 { Err(io::Error::new(ErrorKind::InvalidInput, "length smaller than msg header size")) } else { Ok((NlMsgHeader{ msg_length: len, nl_type: nl_type, flags: flags, seq: seq, pid: pid, }, cursor.position() as usize)) } } pub fn bytes(&self) -> &[u8] { let size = size_of::<NlMsgHeader>(); unsafe { let head = self as *const NlMsgHeader as *const u8; from_raw_parts(head, size) } } pub fn msg_type(&self) -> MsgType { self.nl_type.into() } pub fn msg_length(&self) -> u32 { self.msg_length } /// Set message length pub fn data_length(&mut self, len: u32) -> &mut NlMsgHeader { self.msg_length = nlmsg_length(len as usize) as u32; self } /// Multipart message pub fn multipart(&mut self) -> &mut NlMsgHeader { self.flags |= Flags::Multi.into(); self } /// Request acknowledgement pub fn ack(&mut self) -> &mut NlMsgHeader { self.flags |= Flags::Ack.into(); self } /// Echo message pub fn echo(&mut self) -> &mut NlMsgHeader { self.flags |= Flags::Echo.into(); self } /// Set sequence number pub fn seq(&mut self, n: u32) -> &mut NlMsgHeader { self.seq = n; self } /// Set PID number pub fn pid(&mut self, n: u32) -> &mut NlMsgHeader { self.pid = n; self } /// Override existing pub fn replace(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Replace.into(); self } /// Do not touch, if it exists pub fn excl(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Excl.into(); self } /// Create, if it does not exist pub fn create(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Create.into(); self } /// Add to end of list pub fn append(&mut self) -> &mut NlMsgHeader { self.flags |= NewFlags::Append.into(); self } /// specify tree root pub fn root(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Root.into(); self } /// return all matching pub fn match_provided(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Match.into(); self } /// atomic GET pub fn atomic(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Atomic.into(); self } /// (Root|Match) pub fn dump(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Dump.into(); self } } /* http://linux.die.net/include/linux/netlink.h /* Flags values */ #define NLM_F_REQUEST 1 /* It is request message. */ #define NLM_F_MULTI 2 /* Multipart message, terminated by NLMSG_DONE */ #define NLM_F_ACK 4 /* Reply with ack, with zero or error code */ #define NLM_F_ECHO 8 /* Echo this request */ /* Modifiers to GET request */ #define NLM_F_ROOT 0x100 /* specify tree root */ #define NLM_F_MATCH 0x200 /* return all matching */ #define NLM_F_ATOMIC 0x400 /* atomic GET */ #define NLM_F_DUMP (NLM_F_ROOT|NLM_F_MATCH) /* Modifiers to NEW request */ #define NLM_F_REPLACE 0x100 /* Override existing */ #define NLM_F_EXCL 0x200 /* Do not touch, if it exists */ #define NLM_F_CREATE 0x400 /* Create, if it does not exist */ #define NLM_F_APPEND 0x800 /* Add to end of list */ /* 4.4BSD ADD NLM_F_CREATE|NLM_F_EXCL 4.4BSD CHANGE NLM_F_REPLACE True CHANGE NLM_F_CREATE|NLM_F_REPLACE Append NLM_F_CREATE Check NLM_F_EXCL */ #define NLMSG_NOOP 0x1 /* Nothing. */ #define NLMSG_ERROR 0x2 /* Error */ #define NLMSG_DONE 0x3 /* End of a dump */ #define NLMSG_OVERRUN 0x4 /* Data lost */ #define NLMSG_MIN_TYPE 0x10 /* < 0x10: reserved control messages */ */ #[cfg(test)] mod tests { use super::*; #[test] fn test_encoding() { // Little endian only right now let expected = [20, 0, 0, 0, 0, 0, 1, 3, 1, 0, 0, 0, 9, 0, 0, 0]; let mut hdr = NlMsgHeader::request(); let bytes = hdr.data_length(4).pid(9).seq(1).dump().bytes(); assert_eq!(bytes, expected); } #[test] fn test_decoding() { // Little endian only right now let bytes = [16, 0, 0, 0, 0, 0, 1, 3, 1, 0, 0, 0, 9, 0, 0, 0, 1, 1, 1]; let mut h = NlMsgHeader::request(); let expected = h.data_length(0).pid(9).seq(1).dump(); let (hdr, n) = NlMsgHeader::from_bytes(&bytes).unwrap(); assert_eq!(hdr, *expected); assert_eq!(n, 16); } #[test] fn test_decoding_error() { // Little endian only right now let bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; let res = NlMsgHeader::from_bytes(&bytes); assert!(res.is_err()); } }
{ NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Request.into(), flags: Flags::Request.into(), seq: 0, pid: 0, } }
identifier_body
main.rs
error::Error; use std::fs; use std::path::{Path,PathBuf}; use metadata::MetaObject; use history::Restorable; macro_rules! err_write { ($s: tt) => { writeln!(std::io::stderr(), $s).ok().unwrap_or(())}; ($s: tt, $($e: expr),*) => { writeln!(std::io::stderr(), $s, $($e,)*).ok().unwrap_or(())} } #[allow(dead_code)] struct GlobalOptions { data_dir: PathBuf, keystore: keys::Keystore, cfg: config::Config, verbose: bool, quiet: bool } fn fail_error<E: Error>(msg: &str, err: E) { writeln!(std::io::stderr(), "bkp: {}: {}", msg, err).unwrap(); std::process::exit(1); } trait UnwrapOrFail<T> { /// Unwrap the result or fail with the given error message fn unwrap_or_fail(self, msg: &str) -> T; } impl<T, E: Error> UnwrapOrFail<T> for Result<T, E> { fn unwrap_or_fail(self, msg: &str) -> T { match self { Err(e) => { fail_error(msg, e); unreachable!() }, Ok(x) => x } } } fn connect_backend(name: String, opts: &GlobalOptions) -> Result<Box<remote::Backend>, remote::BackendError> { use remote::BackendError; if let Some(t) = opts.cfg.find_target(&name) { remote::connect_tgt(t, &opts.cfg.node_name, &opts.keystore) } else if let Some(g) = opts.cfg.find_group(&name) { // bind names to actual targets let tgts = g.members.iter() .map(|ref n| opts.cfg.find_target(&n) .ok_or(BackendError::InvalidOption)) .collect::<Result<Vec<&config::BackupTarget>, BackendError>>()?; // connect all of them remote::connect_group(tgts, &opts.cfg.node_name, &opts.keystore) } else { Err(BackendError::InvalidOption) } } fn do_dest(args: &clap::ArgMatches, opts: &mut GlobalOptions) { match args.subcommand() { ("add", Some(m)) => { // add a destination let name = m.value_of("name").unwrap(); let url = m.value_of("url").unwrap(); let user = m.value_of("user"); let password = m.value_of("password"); // make sure the specified destination doesn't already exist if opts.cfg.targets.iter().any(|t| {t.name == name}) { err_write!("bkp: Destination '{}' already exists", name); std::process::exit(1); } // parse the target URL let url = Url::parse(&url) .unwrap_or_fail("Cannot parse given URL"); // build the new target let tgt = config::BackupTarget { name: name.to_owned(), url: url, user: user.map(String::from), password: password.map(String::from), key_file: None, options: config::TargetOptions { reliable: true, upload_cost: 1, download_cost: 1 } }; opts.cfg.targets.push(tgt); opts.cfg.save().unwrap_or_fail("Failed to save config file"); }, (s, _) if (s == "list") || s.is_empty() => { // list destinations let max_left_col = opts.cfg.targets.iter() .map(|ref x| x.name.len()) .max().unwrap_or(0); for t in opts.cfg.targets.iter() { println!("{1:0$} {2}", max_left_col, t.name, t.url.as_str()); } }, ("remove", Some(m)) => { // remove destinations unimplemented!() }, ("test", Some(m)) => { // test destination connectivity let mut has_errs = false; let max_col = m.values_of("name").unwrap() .map(|ref x| x.len()).max().unwrap_or(0); for name in m.values_of("name").unwrap() { let tgt = connect_backend(name.to_owned(), &opts); match tgt { Ok(_) => println!("{1:0$}: successful", max_col, name), Err(e) => { println!("{1:0$}: {2}", max_col, name, e); has_errs = true; } } } if has_errs { std::process::exit(1); } }, (_, _) => panic!("No subcommand handler found") } } fn do_test(args: &clap::ArgMatches, opts: &GlobalOptions) { let profile = match args.value_of("profile").unwrap() { "quick" => history::IntegrityTestMode::Quick, "normal" => history::IntegrityTestMode::Normal, "slow" => history::IntegrityTestMode::Slow, "exhaustive" => history::IntegrityTestMode::Exhaustive, _ => panic!("unexpected test mode string") }; let names = opts.cfg.targets.iter().map(|x| {x.name.clone()}) .chain(opts.cfg.target_groups.iter().map(|x| {x.name.clone()})); for t in names { let b = connect_backend(t.clone(), opts); if let Err(e) = b { println!("bkp: skipping destination '{}': {}", t, e); continue; } // construct a history object let mut b = b.unwrap(); let hist = history::History::new(&mut b); if let Err(e) = hist { println!("bkp: skipping destination '{}': {}", t, e); continue; } // run the check match hist.unwrap().check(profile) { Err(e) => { println!("bkp: skipping destination '{}': {}", t, e); continue; }, Ok(true) => println!("{}: okay", t), Ok(false) => println!("{}: failed", t), } } } fn
(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_clean(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_snap(args: &clap::ArgMatches, opts: &GlobalOptions) { let remote = args.value_of("remote").unwrap().to_owned(); let snap_paths: Vec<&str> = args.values_of("local").unwrap().collect(); let mut remote = connect_backend(remote, opts) .unwrap_or_fail("backend connection failed"); // construct a history object let mut history = history::History::new(&mut remote) .unwrap_or_fail("failed to configure history layer"); // update paths let new_tree = history.update_paths(snap_paths) .unwrap_or_fail("failed to write modified trees"); // build a new snapshot let snap = history.new_snapshot(new_tree) .unwrap_or_fail("failed to create snapshot"); println!("snapshot created."); } fn do_restore(args: &clap::ArgMatches, opts: &GlobalOptions) { let remote = args.value_of("remote").unwrap().to_owned(); // TODO: avoid specifying remote by searching for all remotes with a file let objects: Vec<&Path> = args.values_of("local").unwrap() .map(Path::new).collect(); let mut remote = connect_backend(remote, opts) .unwrap_or_fail("backend connection failed"); let mut history = history::History::new(&mut remote) .unwrap_or_fail("failed to configure history layer"); // TODO: figure out the target time, if any // find the requested snapshot // TODO: add command for recovering backups with broken head snapshot let mut snapshot = history.get_snapshot() .unwrap_or_fail("failed to read root snapshot"); if snapshot.is_none() { eprintln!("bkp: cannot restore from empty target"); std::process::exit(1); } let snapshot = loop { match snapshot { None => { eprintln!("bkp: no matching snapshot"); // TODO: show most recent one? std::process::exit(1); }, Some(snap) => { // TODO: Add target time check here if true { break snap; } snapshot = snap.parent() .unwrap_or_fail("failed to read snapshot"); } } }; // retrieve the objects we're interested in let objects: history::Result<Vec<_>> = objects.into_iter() .map(|obj| snapshot.get(&obj).map(|r| (obj, r))) .collect(); let objects = objects.unwrap_or_fail("cannot read stored objects"); // warn about missing files, if any if objects.iter().any(|x| x.1.is_none()) { println!("The following paths could not be found:"); for p in objects.iter().filter(|x| x.1.is_none()) { println!("\t{}", p.0.to_str().unwrap_or("<unprintable path>")); } println!(""); use std::ascii::AsciiExt; let abort = loop { print!("Do you want to continue restoring? (y/n) "); std::io::stdout().flush().unwrap(); let mut response = String::new(); std::io::stdin().read_line(&mut response).unwrap(); match response.chars().next().map(|x| x.to_ascii_lowercase()) { Some('y') => break false, // no abort Some('n') => break true, // abort _ => {}, // ask again } }; if abort { println!("aborted"); return; } } let objects: Vec<_> = objects.into_iter() .filter_map(|(p,o)| o.map(|v| (p, v))) .collect(); // actually reconstruct them let base_path = Path::new(args.value_of("into").unwrap_or("/")); let options = history::RestoreOptions::new() .overwrite(args.is_present("overwrite")) .ignore_permissions(args.is_present("no_perms")); for (path, obj) in objects { match obj.restore(&base_path, &options) { Ok(()) => {}, Err(history::Error::InvalidArgument) => { eprintln!("bkp: possible integrity violation found!"); eprintln!(" invalid object type at path: {}", path.to_str().unwrap_or("<unprintable>")); }, Err(e) => fail_error("cannot restore object", e) } } } fn load_config(pth: &Path) -> config::Config { let cfg = config::Config::load(&pth); if let Err(e) = cfg { if let config::ConfigErr::IOError(ref err) = e { if err.kind() == std::io::ErrorKind::NotFound { err_write!("Creating new configuration file"); // try to create a new config let cfg = config::Config::default(); cfg.save().ok().unwrap_or(()); return cfg } } let errstr = match e { config::ConfigErr::ParseError(x) => x, config::ConfigErr::IOError(x) => String::from(x.description()) }; writeln!(std::io::stderr(), "bkp: Cannot load config file: {}", errstr).unwrap(); std::process::exit(1); } return cfg.unwrap(); } fn main() { let opt_matches = clap_app!(bkp => (version: "0.1") (author: "Noah Zentzis <[email protected]>") (about: "Automated system backup utility") (@arg CONFIG: -c --config +takes_value "Specifies a config file to use") (@arg DATADIR: -D --data-dir +takes_value "Specify the local data path") (@arg BACKEND: -t --target +takes_value "Override the default destination") (@arg VERBOSE: -v --verbose "Enable verbose terminal output") (@arg QUIET: -q --quiet "Silence non-error terminal output") (@subcommand dest => (about: "Query and modify available backup destinations") (@subcommand add => (about: "Create a new destination") (@arg name: +required "The name of the new destination") (@arg url: +required {|s| {Url::parse(&s).map(|_| ()) .map_err(|_| String::from("Not a valid URL"))}} "The new destination's URL" ) (@arg user: -u --user +takes_value "Set the associated username") (@arg password: -p --password +takes_value "Set the associated password")) (@subcommand list => (about: "List the available destinations") (@arg no_groups: -n --("no-groups") "Don't show grouped destinations")) (@subcommand remove => (about: "Remove an existing destination") (@arg name: +required "The destination name to remove") (@arg scrub: -S --scrub "Remove existing backups from the target")) (@subcommand test => (about: "Test connectivity to a destination") (@arg name: +required * "The destination to test"))) (@subcommand test => (about: "Test integrity of existing backups") (@arg profile: +takes_value possible_values(&["quick", "normal", "slow", "exhaustive"]) default_value("normal") "The test profile to run") (@arg all: -a --all "Test backups from all machines rather than just this one")) (@subcommand stat => (about: "Show backup statistics") (@arg dest: +takes_value... "Only show data about the given destinations") (@arg remote: -r --remote "Query remote servers, bypassing local caches")) (@subcommand clean => (about: "Remove backup data matching specific criteria. \ All given predicates must match in order for data to be removed.") (@arg dest: +takes_value... "Only remove data from the given destinations") (@arg dry_run: -n --("dry-run") "Don't remove anything, just show what would be done") (@group predicates => (@attributes +multiple +required) (@arg snap_type: -t --type +takes_value possible_values(&["diff", "full"]) "Match data in snapshots with type") (@arg older_than: -o --("older-than") +takes_value "Match data older than a certain age") (@arg newer_than: -N --("newer-than") +takes_value "Match data newer than a certain age") (@arg exists: -e --exists +takes_value possible_values(&["yes", "no"]) "Match data based on whether it exists on the host"))) (@subcommand snap => (about: "Take a snapshot of local files") (@arg remote: +takes_value "Remote to store data in") (@arg local: +takes_value... "Files or directories to snapshot") (@arg no_trust_mtime: -T --("no-trust-mtime") "Use content hashes to check for file changes rather than FS's mtime")) (@subcommand restore => (about: "Restore local files from backup") (@arg remote: +required "Remote to restore from") (@arg local:... min_values(1) "Files or directories to restore") (@arg as_of: -t --time +takes_value "Restore to most recent snapshot before given date/time") (@arg overwrite: -o --overwrite "Overwrite existing local files") (@arg from: -f --from +takes_value "Restore data from another machine") (@arg no_perms: -p --("no-perms") "Don't restore filesystem permissions") (@arg no_attrs: -a --("no-attrs") "Don't restore file metadata") (@arg into: -i --into conflicts_with[overwrite] +takes_value "Restore to a given path") ) ).get_matches(); // load a config file let config_path = opt_matches .value_of("CONFIG") .map(Path::new) .map(Path::to_path_buf) .unwrap_or(std::env::home_dir().unwrap().join(".bkprc")); let cfg = load_config(&config_path); // create the data dir if needed let data_dir = opt_matches.value_of("DATADIR").map(Path::new) .map(Path::to_path_buf) .unwrap_or(std::env::home_dir().unwrap().join(".bkp")); if let Err(e) = fs::metadata(&data_dir) { if e.kind() == std::io::ErrorKind::NotFound { if fs::create_dir(&data_dir).is_err() { writeln!(std::io::stderr(), "bkp: Cannot create directory: {}", data_dir.display()).unwrap(); std::process::exit(1); } } else { writeln!(std::io::stderr(), "bkp: Cannot access directory: {}", data_dir.display()).unwrap(); std::process::exit(1); } } // open the key store let kspath = data_dir.join("keystore"); let ks = match fs::metadata(&kspath) { Ok(_) => match keys::Keystore::open(&kspath) { Ok(k) => k, Err(e) => { err_write!("bkp: Cannot open keystore: {}", e.description()); std::process::exit(1); } }, Err(e) => if e.kind() == std::io::ErrorKind::NotFound { match keys::Keystore::create(&kspath) { Ok(k) => k, Err(e) => { err_write!("bkp: Cannot create keystore: {}", e.description()); std::process::exit(1); } } } else { writeln!(std::io::stderr(), "bkp: Cannot access keystore: {}", kspath.display()).unwrap(); std::process::exit(1); } }; // parse global flags let mut global_flags = GlobalOptions { cfg: cfg, verbose: opt_matches.is_present("VERBOSE"), quiet: opt_matches.is_present("QUIET"), data_dir: data_dir, keystore: ks
do_stat
identifier_name
main.rs
quiet: bool } fn fail_error<E: Error>(msg: &str, err: E) { writeln!(std::io::stderr(), "bkp: {}: {}", msg, err).unwrap(); std::process::exit(1); } trait UnwrapOrFail<T> { /// Unwrap the result or fail with the given error message fn unwrap_or_fail(self, msg: &str) -> T; } impl<T, E: Error> UnwrapOrFail<T> for Result<T, E> { fn unwrap_or_fail(self, msg: &str) -> T { match self { Err(e) => { fail_error(msg, e); unreachable!() }, Ok(x) => x } } } fn connect_backend(name: String, opts: &GlobalOptions) -> Result<Box<remote::Backend>, remote::BackendError> { use remote::BackendError; if let Some(t) = opts.cfg.find_target(&name) { remote::connect_tgt(t, &opts.cfg.node_name, &opts.keystore) } else if let Some(g) = opts.cfg.find_group(&name) { // bind names to actual targets let tgts = g.members.iter() .map(|ref n| opts.cfg.find_target(&n) .ok_or(BackendError::InvalidOption)) .collect::<Result<Vec<&config::BackupTarget>, BackendError>>()?; // connect all of them remote::connect_group(tgts, &opts.cfg.node_name, &opts.keystore) } else { Err(BackendError::InvalidOption) } } fn do_dest(args: &clap::ArgMatches, opts: &mut GlobalOptions) { match args.subcommand() { ("add", Some(m)) => { // add a destination let name = m.value_of("name").unwrap(); let url = m.value_of("url").unwrap(); let user = m.value_of("user"); let password = m.value_of("password"); // make sure the specified destination doesn't already exist if opts.cfg.targets.iter().any(|t| {t.name == name}) { err_write!("bkp: Destination '{}' already exists", name); std::process::exit(1); } // parse the target URL let url = Url::parse(&url) .unwrap_or_fail("Cannot parse given URL"); // build the new target let tgt = config::BackupTarget { name: name.to_owned(), url: url, user: user.map(String::from), password: password.map(String::from), key_file: None, options: config::TargetOptions { reliable: true, upload_cost: 1, download_cost: 1 } }; opts.cfg.targets.push(tgt); opts.cfg.save().unwrap_or_fail("Failed to save config file"); }, (s, _) if (s == "list") || s.is_empty() => { // list destinations let max_left_col = opts.cfg.targets.iter() .map(|ref x| x.name.len()) .max().unwrap_or(0); for t in opts.cfg.targets.iter() { println!("{1:0$} {2}", max_left_col, t.name, t.url.as_str()); } }, ("remove", Some(m)) => { // remove destinations unimplemented!() }, ("test", Some(m)) => { // test destination connectivity let mut has_errs = false; let max_col = m.values_of("name").unwrap() .map(|ref x| x.len()).max().unwrap_or(0); for name in m.values_of("name").unwrap() { let tgt = connect_backend(name.to_owned(), &opts); match tgt { Ok(_) => println!("{1:0$}: successful", max_col, name), Err(e) => { println!("{1:0$}: {2}", max_col, name, e); has_errs = true; } } } if has_errs { std::process::exit(1); } }, (_, _) => panic!("No subcommand handler found") } } fn do_test(args: &clap::ArgMatches, opts: &GlobalOptions) { let profile = match args.value_of("profile").unwrap() { "quick" => history::IntegrityTestMode::Quick, "normal" => history::IntegrityTestMode::Normal, "slow" => history::IntegrityTestMode::Slow, "exhaustive" => history::IntegrityTestMode::Exhaustive, _ => panic!("unexpected test mode string") }; let names = opts.cfg.targets.iter().map(|x| {x.name.clone()}) .chain(opts.cfg.target_groups.iter().map(|x| {x.name.clone()})); for t in names { let b = connect_backend(t.clone(), opts); if let Err(e) = b { println!("bkp: skipping destination '{}': {}", t, e); continue; } // construct a history object let mut b = b.unwrap(); let hist = history::History::new(&mut b); if let Err(e) = hist { println!("bkp: skipping destination '{}': {}", t, e); continue; } // run the check match hist.unwrap().check(profile) { Err(e) => { println!("bkp: skipping destination '{}': {}", t, e); continue; }, Ok(true) => println!("{}: okay", t), Ok(false) => println!("{}: failed", t), } } } fn do_stat(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_clean(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_snap(args: &clap::ArgMatches, opts: &GlobalOptions) { let remote = args.value_of("remote").unwrap().to_owned(); let snap_paths: Vec<&str> = args.values_of("local").unwrap().collect(); let mut remote = connect_backend(remote, opts) .unwrap_or_fail("backend connection failed"); // construct a history object let mut history = history::History::new(&mut remote) .unwrap_or_fail("failed to configure history layer"); // update paths let new_tree = history.update_paths(snap_paths) .unwrap_or_fail("failed to write modified trees"); // build a new snapshot let snap = history.new_snapshot(new_tree) .unwrap_or_fail("failed to create snapshot"); println!("snapshot created."); } fn do_restore(args: &clap::ArgMatches, opts: &GlobalOptions) { let remote = args.value_of("remote").unwrap().to_owned(); // TODO: avoid specifying remote by searching for all remotes with a file let objects: Vec<&Path> = args.values_of("local").unwrap() .map(Path::new).collect(); let mut remote = connect_backend(remote, opts) .unwrap_or_fail("backend connection failed"); let mut history = history::History::new(&mut remote) .unwrap_or_fail("failed to configure history layer"); // TODO: figure out the target time, if any // find the requested snapshot // TODO: add command for recovering backups with broken head snapshot let mut snapshot = history.get_snapshot() .unwrap_or_fail("failed to read root snapshot"); if snapshot.is_none() { eprintln!("bkp: cannot restore from empty target"); std::process::exit(1); } let snapshot = loop { match snapshot { None => { eprintln!("bkp: no matching snapshot"); // TODO: show most recent one? std::process::exit(1); }, Some(snap) => { // TODO: Add target time check here if true { break snap; } snapshot = snap.parent() .unwrap_or_fail("failed to read snapshot"); } } }; // retrieve the objects we're interested in let objects: history::Result<Vec<_>> = objects.into_iter() .map(|obj| snapshot.get(&obj).map(|r| (obj, r))) .collect(); let objects = objects.unwrap_or_fail("cannot read stored objects"); // warn about missing files, if any if objects.iter().any(|x| x.1.is_none()) { println!("The following paths could not be found:"); for p in objects.iter().filter(|x| x.1.is_none()) { println!("\t{}", p.0.to_str().unwrap_or("<unprintable path>")); } println!(""); use std::ascii::AsciiExt; let abort = loop { print!("Do you want to continue restoring? (y/n) "); std::io::stdout().flush().unwrap(); let mut response = String::new(); std::io::stdin().read_line(&mut response).unwrap(); match response.chars().next().map(|x| x.to_ascii_lowercase()) { Some('y') => break false, // no abort Some('n') => break true, // abort _ => {}, // ask again } }; if abort { println!("aborted"); return; } } let objects: Vec<_> = objects.into_iter() .filter_map(|(p,o)| o.map(|v| (p, v))) .collect(); // actually reconstruct them let base_path = Path::new(args.value_of("into").unwrap_or("/")); let options = history::RestoreOptions::new() .overwrite(args.is_present("overwrite")) .ignore_permissions(args.is_present("no_perms")); for (path, obj) in objects { match obj.restore(&base_path, &options) { Ok(()) => {}, Err(history::Error::InvalidArgument) => { eprintln!("bkp: possible integrity violation found!"); eprintln!(" invalid object type at path: {}", path.to_str().unwrap_or("<unprintable>")); }, Err(e) => fail_error("cannot restore object", e) } } } fn load_config(pth: &Path) -> config::Config { let cfg = config::Config::load(&pth); if let Err(e) = cfg { if let config::ConfigErr::IOError(ref err) = e { if err.kind() == std::io::ErrorKind::NotFound { err_write!("Creating new configuration file"); // try to create a new config let cfg = config::Config::default(); cfg.save().ok().unwrap_or(()); return cfg } } let errstr = match e { config::ConfigErr::ParseError(x) => x, config::ConfigErr::IOError(x) => String::from(x.description()) }; writeln!(std::io::stderr(), "bkp: Cannot load config file: {}", errstr).unwrap(); std::process::exit(1); } return cfg.unwrap(); } fn main() { let opt_matches = clap_app!(bkp => (version: "0.1") (author: "Noah Zentzis <[email protected]>") (about: "Automated system backup utility") (@arg CONFIG: -c --config +takes_value "Specifies a config file to use") (@arg DATADIR: -D --data-dir +takes_value "Specify the local data path") (@arg BACKEND: -t --target +takes_value "Override the default destination") (@arg VERBOSE: -v --verbose "Enable verbose terminal output") (@arg QUIET: -q --quiet "Silence non-error terminal output") (@subcommand dest => (about: "Query and modify available backup destinations") (@subcommand add => (about: "Create a new destination") (@arg name: +required "The name of the new destination") (@arg url: +required {|s| {Url::parse(&s).map(|_| ()) .map_err(|_| String::from("Not a valid URL"))}} "The new destination's URL" ) (@arg user: -u --user +takes_value "Set the associated username") (@arg password: -p --password +takes_value "Set the associated password")) (@subcommand list => (about: "List the available destinations") (@arg no_groups: -n --("no-groups") "Don't show grouped destinations")) (@subcommand remove => (about: "Remove an existing destination") (@arg name: +required "The destination name to remove") (@arg scrub: -S --scrub "Remove existing backups from the target")) (@subcommand test => (about: "Test connectivity to a destination") (@arg name: +required * "The destination to test"))) (@subcommand test => (about: "Test integrity of existing backups") (@arg profile: +takes_value possible_values(&["quick", "normal", "slow", "exhaustive"]) default_value("normal") "The test profile to run") (@arg all: -a --all "Test backups from all machines rather than just this one")) (@subcommand stat => (about: "Show backup statistics") (@arg dest: +takes_value... "Only show data about the given destinations") (@arg remote: -r --remote "Query remote servers, bypassing local caches")) (@subcommand clean => (about: "Remove backup data matching specific criteria. \ All given predicates must match in order for data to be removed.") (@arg dest: +takes_value... "Only remove data from the given destinations") (@arg dry_run: -n --("dry-run") "Don't remove anything, just show what would be done") (@group predicates => (@attributes +multiple +required) (@arg snap_type: -t --type +takes_value possible_values(&["diff", "full"]) "Match data in snapshots with type") (@arg older_than: -o --("older-than") +takes_value "Match data older than a certain age") (@arg newer_than: -N --("newer-than") +takes_value "Match data newer than a certain age") (@arg exists: -e --exists +takes_value possible_values(&["yes", "no"]) "Match data based on whether it exists on the host"))) (@subcommand snap => (about: "Take a snapshot of local files") (@arg remote: +takes_value "Remote to store data in") (@arg local: +takes_value... "Files or directories to snapshot") (@arg no_trust_mtime: -T --("no-trust-mtime") "Use content hashes to check for file changes rather than FS's mtime")) (@subcommand restore => (about: "Restore local files from backup") (@arg remote: +required "Remote to restore from") (@arg local:... min_values(1) "Files or directories to restore") (@arg as_of: -t --time +takes_value "Restore to most recent snapshot before given date/time") (@arg overwrite: -o --overwrite "Overwrite existing local files") (@arg from: -f --from +takes_value "Restore data from another machine") (@arg no_perms: -p --("no-perms") "Don't restore filesystem permissions") (@arg no_attrs: -a --("no-attrs") "Don't restore file metadata") (@arg into: -i --into conflicts_with[overwrite] +takes_value "Restore to a given path") ) ).get_matches(); // load a config file let config_path = opt_matches .value_of("CONFIG") .map(Path::new) .map(Path::to_path_buf) .unwrap_or(std::env::home_dir().unwrap().join(".bkprc")); let cfg = load_config(&config_path); // create the data dir if needed let data_dir = opt_matches.value_of("DATADIR").map(Path::new) .map(Path::to_path_buf) .unwrap_or(std::env::home_dir().unwrap().join(".bkp")); if let Err(e) = fs::metadata(&data_dir) { if e.kind() == std::io::ErrorKind::NotFound { if fs::create_dir(&data_dir).is_err() { writeln!(std::io::stderr(), "bkp: Cannot create directory: {}", data_dir.display()).unwrap(); std::process::exit(1); } } else { writeln!(std::io::stderr(), "bkp: Cannot access directory: {}", data_dir.display()).unwrap(); std::process::exit(1); } } // open the key store let kspath = data_dir.join("keystore"); let ks = match fs::metadata(&kspath) { Ok(_) => match keys::Keystore::open(&kspath) { Ok(k) => k, Err(e) => { err_write!("bkp: Cannot open keystore: {}", e.description()); std::process::exit(1); } }, Err(e) => if e.kind() == std::io::ErrorKind::NotFound { match keys::Keystore::create(&kspath) { Ok(k) => k, Err(e) => { err_write!("bkp: Cannot create keystore: {}", e.description()); std::process::exit(1); } } } else { writeln!(std::io::stderr(), "bkp: Cannot access keystore: {}", kspath.display()).unwrap(); std::process::exit(1); } }; // parse global flags let mut global_flags = GlobalOptions { cfg: cfg, verbose: opt_matches.is_present("VERBOSE"), quiet: opt_matches.is_present("QUIET"), data_dir: data_dir, keystore: ks }; // figure out what to do match opt_matches.subcommand() { ("", _) => { println!("bkp: No subcommand specified"); }, ("dest", Some(m)) => do_dest(m, &mut global_flags), ("test", Some(m)) => do_test(m, &global_flags), ("stat", Some(m)) => do_stat(m, &global_flags), ("clean", Some(m)) => do_clean(m, &global_flags), ("snap", Some(m)) => do_snap(m, &global_flags),
random_line_split
main.rs
error::Error; use std::fs; use std::path::{Path,PathBuf}; use metadata::MetaObject; use history::Restorable; macro_rules! err_write { ($s: tt) => { writeln!(std::io::stderr(), $s).ok().unwrap_or(())}; ($s: tt, $($e: expr),*) => { writeln!(std::io::stderr(), $s, $($e,)*).ok().unwrap_or(())} } #[allow(dead_code)] struct GlobalOptions { data_dir: PathBuf, keystore: keys::Keystore, cfg: config::Config, verbose: bool, quiet: bool } fn fail_error<E: Error>(msg: &str, err: E) { writeln!(std::io::stderr(), "bkp: {}: {}", msg, err).unwrap(); std::process::exit(1); } trait UnwrapOrFail<T> { /// Unwrap the result or fail with the given error message fn unwrap_or_fail(self, msg: &str) -> T; } impl<T, E: Error> UnwrapOrFail<T> for Result<T, E> { fn unwrap_or_fail(self, msg: &str) -> T { match self { Err(e) => { fail_error(msg, e); unreachable!() }, Ok(x) => x } } } fn connect_backend(name: String, opts: &GlobalOptions) -> Result<Box<remote::Backend>, remote::BackendError> { use remote::BackendError; if let Some(t) = opts.cfg.find_target(&name) { remote::connect_tgt(t, &opts.cfg.node_name, &opts.keystore) } else if let Some(g) = opts.cfg.find_group(&name) { // bind names to actual targets let tgts = g.members.iter() .map(|ref n| opts.cfg.find_target(&n) .ok_or(BackendError::InvalidOption)) .collect::<Result<Vec<&config::BackupTarget>, BackendError>>()?; // connect all of them remote::connect_group(tgts, &opts.cfg.node_name, &opts.keystore) } else { Err(BackendError::InvalidOption) } } fn do_dest(args: &clap::ArgMatches, opts: &mut GlobalOptions) { match args.subcommand() { ("add", Some(m)) => { // add a destination let name = m.value_of("name").unwrap(); let url = m.value_of("url").unwrap(); let user = m.value_of("user"); let password = m.value_of("password"); // make sure the specified destination doesn't already exist if opts.cfg.targets.iter().any(|t| {t.name == name}) { err_write!("bkp: Destination '{}' already exists", name); std::process::exit(1); } // parse the target URL let url = Url::parse(&url) .unwrap_or_fail("Cannot parse given URL"); // build the new target let tgt = config::BackupTarget { name: name.to_owned(), url: url, user: user.map(String::from), password: password.map(String::from), key_file: None, options: config::TargetOptions { reliable: true, upload_cost: 1, download_cost: 1 } }; opts.cfg.targets.push(tgt); opts.cfg.save().unwrap_or_fail("Failed to save config file"); }, (s, _) if (s == "list") || s.is_empty() => { // list destinations let max_left_col = opts.cfg.targets.iter() .map(|ref x| x.name.len()) .max().unwrap_or(0); for t in opts.cfg.targets.iter() { println!("{1:0$} {2}", max_left_col, t.name, t.url.as_str()); } }, ("remove", Some(m)) => { // remove destinations unimplemented!() }, ("test", Some(m)) => { // test destination connectivity let mut has_errs = false; let max_col = m.values_of("name").unwrap() .map(|ref x| x.len()).max().unwrap_or(0); for name in m.values_of("name").unwrap() { let tgt = connect_backend(name.to_owned(), &opts); match tgt { Ok(_) => println!("{1:0$}: successful", max_col, name), Err(e) => { println!("{1:0$}: {2}", max_col, name, e); has_errs = true; } } } if has_errs { std::process::exit(1); } }, (_, _) => panic!("No subcommand handler found") } } fn do_test(args: &clap::ArgMatches, opts: &GlobalOptions) { let profile = match args.value_of("profile").unwrap() { "quick" => history::IntegrityTestMode::Quick, "normal" => history::IntegrityTestMode::Normal, "slow" => history::IntegrityTestMode::Slow, "exhaustive" => history::IntegrityTestMode::Exhaustive, _ => panic!("unexpected test mode string") }; let names = opts.cfg.targets.iter().map(|x| {x.name.clone()}) .chain(opts.cfg.target_groups.iter().map(|x| {x.name.clone()})); for t in names { let b = connect_backend(t.clone(), opts); if let Err(e) = b { println!("bkp: skipping destination '{}': {}", t, e); continue; } // construct a history object let mut b = b.unwrap(); let hist = history::History::new(&mut b); if let Err(e) = hist { println!("bkp: skipping destination '{}': {}", t, e); continue; } // run the check match hist.unwrap().check(profile) { Err(e) => { println!("bkp: skipping destination '{}': {}", t, e); continue; }, Ok(true) => println!("{}: okay", t), Ok(false) => println!("{}: failed", t), } } } fn do_stat(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_clean(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_snap(args: &clap::ArgMatches, opts: &GlobalOptions) { let remote = args.value_of("remote").unwrap().to_owned(); let snap_paths: Vec<&str> = args.values_of("local").unwrap().collect(); let mut remote = connect_backend(remote, opts) .unwrap_or_fail("backend connection failed"); // construct a history object let mut history = history::History::new(&mut remote) .unwrap_or_fail("failed to configure history layer"); // update paths let new_tree = history.update_paths(snap_paths) .unwrap_or_fail("failed to write modified trees"); // build a new snapshot let snap = history.new_snapshot(new_tree) .unwrap_or_fail("failed to create snapshot"); println!("snapshot created."); } fn do_restore(args: &clap::ArgMatches, opts: &GlobalOptions) { let remote = args.value_of("remote").unwrap().to_owned(); // TODO: avoid specifying remote by searching for all remotes with a file let objects: Vec<&Path> = args.values_of("local").unwrap() .map(Path::new).collect(); let mut remote = connect_backend(remote, opts) .unwrap_or_fail("backend connection failed"); let mut history = history::History::new(&mut remote) .unwrap_or_fail("failed to configure history layer"); // TODO: figure out the target time, if any // find the requested snapshot // TODO: add command for recovering backups with broken head snapshot let mut snapshot = history.get_snapshot() .unwrap_or_fail("failed to read root snapshot"); if snapshot.is_none() { eprintln!("bkp: cannot restore from empty target"); std::process::exit(1); } let snapshot = loop { match snapshot { None => { eprintln!("bkp: no matching snapshot"); // TODO: show most recent one? std::process::exit(1); }, Some(snap) => { // TODO: Add target time check here if true { break snap; } snapshot = snap.parent() .unwrap_or_fail("failed to read snapshot"); } } }; // retrieve the objects we're interested in let objects: history::Result<Vec<_>> = objects.into_iter() .map(|obj| snapshot.get(&obj).map(|r| (obj, r))) .collect(); let objects = objects.unwrap_or_fail("cannot read stored objects"); // warn about missing files, if any if objects.iter().any(|x| x.1.is_none()) { println!("The following paths could not be found:"); for p in objects.iter().filter(|x| x.1.is_none()) { println!("\t{}", p.0.to_str().unwrap_or("<unprintable path>")); } println!(""); use std::ascii::AsciiExt; let abort = loop { print!("Do you want to continue restoring? (y/n) "); std::io::stdout().flush().unwrap(); let mut response = String::new(); std::io::stdin().read_line(&mut response).unwrap(); match response.chars().next().map(|x| x.to_ascii_lowercase()) { Some('y') => break false, // no abort Some('n') => break true, // abort _ => {}, // ask again } }; if abort { println!("aborted"); return; } } let objects: Vec<_> = objects.into_iter() .filter_map(|(p,o)| o.map(|v| (p, v))) .collect(); // actually reconstruct them let base_path = Path::new(args.value_of("into").unwrap_or("/")); let options = history::RestoreOptions::new() .overwrite(args.is_present("overwrite")) .ignore_permissions(args.is_present("no_perms")); for (path, obj) in objects { match obj.restore(&base_path, &options) { Ok(()) => {}, Err(history::Error::InvalidArgument) => { eprintln!("bkp: possible integrity violation found!"); eprintln!(" invalid object type at path: {}", path.to_str().unwrap_or("<unprintable>")); }, Err(e) => fail_error("cannot restore object", e) } } } fn load_config(pth: &Path) -> config::Config { let cfg = config::Config::load(&pth); if let Err(e) = cfg { if let config::ConfigErr::IOError(ref err) = e { if err.kind() == std::io::ErrorKind::NotFound { err_write!("Creating new configuration file"); // try to create a new config let cfg = config::Config::default(); cfg.save().ok().unwrap_or(()); return cfg } } let errstr = match e { config::ConfigErr::ParseError(x) => x, config::ConfigErr::IOError(x) => String::from(x.description()) }; writeln!(std::io::stderr(), "bkp: Cannot load config file: {}", errstr).unwrap(); std::process::exit(1); } return cfg.unwrap(); } fn main()
(@arg password: -p --password +takes_value "Set the associated password")) (@subcommand list => (about: "List the available destinations") (@arg no_groups: -n --("no-groups") "Don't show grouped destinations")) (@subcommand remove => (about: "Remove an existing destination") (@arg name: +required "The destination name to remove") (@arg scrub: -S --scrub "Remove existing backups from the target")) (@subcommand test => (about: "Test connectivity to a destination") (@arg name: +required * "The destination to test"))) (@subcommand test => (about: "Test integrity of existing backups") (@arg profile: +takes_value possible_values(&["quick", "normal", "slow", "exhaustive"]) default_value("normal") "The test profile to run") (@arg all: -a --all "Test backups from all machines rather than just this one")) (@subcommand stat => (about: "Show backup statistics") (@arg dest: +takes_value... "Only show data about the given destinations") (@arg remote: -r --remote "Query remote servers, bypassing local caches")) (@subcommand clean => (about: "Remove backup data matching specific criteria. \ All given predicates must match in order for data to be removed.") (@arg dest: +takes_value... "Only remove data from the given destinations") (@arg dry_run: -n --("dry-run") "Don't remove anything, just show what would be done") (@group predicates => (@attributes +multiple +required) (@arg snap_type: -t --type +takes_value possible_values(&["diff", "full"]) "Match data in snapshots with type") (@arg older_than: -o --("older-than") +takes_value "Match data older than a certain age") (@arg newer_than: -N --("newer-than") +takes_value "Match data newer than a certain age") (@arg exists: -e --exists +takes_value possible_values(&["yes", "no"]) "Match data based on whether it exists on the host"))) (@subcommand snap => (about: "Take a snapshot of local files") (@arg remote: +takes_value "Remote to store data in") (@arg local: +takes_value... "Files or directories to snapshot") (@arg no_trust_mtime: -T --("no-trust-mtime") "Use content hashes to check for file changes rather than FS's mtime")) (@subcommand restore => (about: "Restore local files from backup") (@arg remote: +required "Remote to restore from") (@arg local:... min_values(1) "Files or directories to restore") (@arg as_of: -t --time +takes_value "Restore to most recent snapshot before given date/time") (@arg overwrite: -o --overwrite "Overwrite existing local files") (@arg from: -f --from +takes_value "Restore data from another machine") (@arg no_perms: -p --("no-perms") "Don't restore filesystem permissions") (@arg no_attrs: -a --("no-attrs") "Don't restore file metadata") (@arg into: -i --into conflicts_with[overwrite] +takes_value "Restore to a given path") ) ).get_matches(); // load a config file let config_path = opt_matches .value_of("CONFIG") .map(Path::new) .map(Path::to_path_buf) .unwrap_or(std::env::home_dir().unwrap().join(".bkprc")); let cfg = load_config(&config_path); // create the data dir if needed let data_dir = opt_matches.value_of("DATADIR").map(Path::new) .map(Path::to_path_buf) .unwrap_or(std::env::home_dir().unwrap().join(".bkp")); if let Err(e) = fs::metadata(&data_dir) { if e.kind() == std::io::ErrorKind::NotFound { if fs::create_dir(&data_dir).is_err() { writeln!(std::io::stderr(), "bkp: Cannot create directory: {}", data_dir.display()).unwrap(); std::process::exit(1); } } else { writeln!(std::io::stderr(), "bkp: Cannot access directory: {}", data_dir.display()).unwrap(); std::process::exit(1); } } // open the key store let kspath = data_dir.join("keystore"); let ks = match fs::metadata(&kspath) { Ok(_) => match keys::Keystore::open(&kspath) { Ok(k) => k, Err(e) => { err_write!("bkp: Cannot open keystore: {}", e.description()); std::process::exit(1); } }, Err(e) => if e.kind() == std::io::ErrorKind::NotFound { match keys::Keystore::create(&kspath) { Ok(k) => k, Err(e) => { err_write!("bkp: Cannot create keystore: {}", e.description()); std::process::exit(1); } } } else { writeln!(std::io::stderr(), "bkp: Cannot access keystore: {}", kspath.display()).unwrap(); std::process::exit(1); } }; // parse global flags let mut global_flags = GlobalOptions { cfg: cfg, verbose: opt_matches.is_present("VERBOSE"), quiet: opt_matches.is_present("QUIET"), data_dir: data_dir, keystore: ks };
{ let opt_matches = clap_app!(bkp => (version: "0.1") (author: "Noah Zentzis <[email protected]>") (about: "Automated system backup utility") (@arg CONFIG: -c --config +takes_value "Specifies a config file to use") (@arg DATADIR: -D --data-dir +takes_value "Specify the local data path") (@arg BACKEND: -t --target +takes_value "Override the default destination") (@arg VERBOSE: -v --verbose "Enable verbose terminal output") (@arg QUIET: -q --quiet "Silence non-error terminal output") (@subcommand dest => (about: "Query and modify available backup destinations") (@subcommand add => (about: "Create a new destination") (@arg name: +required "The name of the new destination") (@arg url: +required {|s| {Url::parse(&s).map(|_| ()) .map_err(|_| String::from("Not a valid URL"))}} "The new destination's URL" ) (@arg user: -u --user +takes_value "Set the associated username")
identifier_body
indexed_set.rs
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use array_vec::ArrayVec; use std::fmt; use std::iter; use std::marker::PhantomData; use std::mem; use std::slice; use bitslice::{BitSlice, Word}; use bitslice::{bitwise, Union, Subtract, Intersect}; use indexed_vec::Idx; use rustc_serialize; /// This is implemented by all the index sets so that IdxSet::union() can be /// passed any type of index set. pub trait UnionIntoIdxSet<T: Idx> { // Performs `other = other | self`. fn union_into(&self, other: &mut IdxSet<T>) -> bool; } /// This is implemented by all the index sets so that IdxSet::subtract() can be /// passed any type of index set. pub trait SubtractFromIdxSet<T: Idx> { // Performs `other = other - self`. fn subtract_from(&self, other: &mut IdxSet<T>) -> bool; } /// Represents a set of some element type E, where each E is identified by some /// unique index type `T`. /// /// In other words, `T` is the type used to index into the bitvector /// this type uses to represent the set of object it holds. /// /// The representation is dense, using one bit per possible element. #[derive(Eq, PartialEq)] pub struct IdxSet<T: Idx> { _pd: PhantomData<fn(&T)>, bits: Vec<Word>, } impl<T: Idx> Clone for IdxSet<T> { fn clone(&self) -> Self { IdxSet { _pd: PhantomData, bits: self.bits.clone() } } } impl<T: Idx> rustc_serialize::Encodable for IdxSet<T> { fn encode<E: rustc_serialize::Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> { self.bits.encode(encoder) } } impl<T: Idx> rustc_serialize::Decodable for IdxSet<T> { fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<IdxSet<T>, D::Error> { let words: Vec<Word> = rustc_serialize::Decodable::decode(d)?; Ok(IdxSet { _pd: PhantomData, bits: words, }) } } const BITS_PER_WORD: usize = mem::size_of::<Word>() * 8; impl<T: Idx> fmt::Debug for IdxSet<T> { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { w.debug_list() .entries(self.iter()) .finish() } } impl<T: Idx> IdxSet<T> { fn new(init: Word, domain_size: usize) -> Self { let num_words = (domain_size + (BITS_PER_WORD - 1)) / BITS_PER_WORD; IdxSet { _pd: Default::default(), bits: vec![init; num_words], } } /// Creates set holding every element whose index falls in range 0..domain_size. pub fn new_filled(domain_size: usize) -> Self { let mut result = Self::new(!0, domain_size); result.trim_to(domain_size); result } /// Creates set holding no elements. pub fn new_empty(domain_size: usize) -> Self { Self::new(0, domain_size) } /// Duplicates as a hybrid set. pub fn to_hybrid(&self) -> HybridIdxSet<T> { // This domain_size may be slightly larger than the one specified // upon creation, due to rounding up to a whole word. That's ok. let domain_size = self.bits.len() * BITS_PER_WORD; // Note: we currently don't bother trying to make a Sparse set. HybridIdxSet::Dense(self.to_owned(), domain_size) } /// Removes all elements pub fn clear(&mut self) { for b in &mut self.bits { *b = 0; } } /// Sets all elements up to `domain_size` pub fn set_up_to(&mut self, domain_size: usize) { for b in &mut self.bits { *b =!0; } self.trim_to(domain_size); } /// Clear all elements above `domain_size`. fn trim_to(&mut self, domain_size: usize) { // `trim_block` is the first block where some bits have // to be cleared. let trim_block = domain_size / BITS_PER_WORD; // all the blocks above it have to be completely cleared. if trim_block < self.bits.len() { for b in &mut self.bits[trim_block+1..] { *b = 0; } // at that block, the `domain_size % BITS_PER_WORD` LSBs // should remain. let remaining_bits = domain_size % BITS_PER_WORD; let mask = (1<<remaining_bits)-1; self.bits[trim_block] &= mask; } } /// Removes `elem` from the set `self`; returns true iff this changed `self`. pub fn remove(&mut self, elem: &T) -> bool { self.bits.clear_bit(elem.index()) } /// Adds `elem` to the set `self`; returns true iff this changed `self`. pub fn add(&mut self, elem: &T) -> bool { self.bits.set_bit(elem.index()) } /// Returns true iff set `self` contains `elem`. pub fn contains(&self, elem: &T) -> bool { self.bits.get_bit(elem.index()) } pub fn words(&self) -> &[Word] { &self.bits } pub fn words_mut(&mut self) -> &mut [Word] { &mut self.bits } /// Efficiently overwrite `self` with `other`. Panics if `self` and `other` /// don't have the same length. pub fn overwrite(&mut self, other: &IdxSet<T>) { self.words_mut().clone_from_slice(other.words()); } /// Set `self = self | other` and return true if `self` changed /// (i.e., if new bits were added). pub fn union(&mut self, other: &impl UnionIntoIdxSet<T>) -> bool { other.union_into(self) } /// Set `self = self - other` and return true if `self` changed. /// (i.e., if any bits were removed). pub fn subtract(&mut self, other: &impl SubtractFromIdxSet<T>) -> bool { other.subtract_from(self) } /// Set `self = self & other` and return true if `self` changed. /// (i.e., if any bits were removed). pub fn intersect(&mut self, other: &IdxSet<T>) -> bool { bitwise(self.words_mut(), other.words(), &Intersect) } pub fn iter(&self) -> Iter<T> { Iter { cur: None, iter: self.words().iter().enumerate(), _pd: PhantomData, } } } impl<T: Idx> UnionIntoIdxSet<T> for IdxSet<T> { fn union_into(&self, other: &mut IdxSet<T>) -> bool { bitwise(other.words_mut(), self.words(), &Union) } } impl<T: Idx> SubtractFromIdxSet<T> for IdxSet<T> { fn subtract_from(&self, other: &mut IdxSet<T>) -> bool { bitwise(other.words_mut(), self.words(), &Subtract) } } pub struct Iter<'a, T: Idx> { cur: Option<(Word, usize)>, iter: iter::Enumerate<slice::Iter<'a, Word>>, _pd: PhantomData<fn(&T)>, } impl<'a, T: Idx> Iterator for Iter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { loop { if let Some((ref mut word, offset)) = self.cur { let bit_pos = word.trailing_zeros() as usize; if bit_pos!= BITS_PER_WORD { let bit = 1 << bit_pos; *word ^= bit; return Some(T::new(bit_pos + offset)) } } let (i, word) = self.iter.next()?; self.cur = Some((*word, BITS_PER_WORD * i)); } } } const SPARSE_MAX: usize = 8; /// A sparse index set with a maximum of SPARSE_MAX elements. Used by /// HybridIdxSet; do not use directly. /// /// The elements are stored as an unsorted vector with no duplicates. #[derive(Clone, Debug)] pub struct SparseIdxSet<T: Idx>(ArrayVec<[T; SPARSE_MAX]>); impl<T: Idx> SparseIdxSet<T> { fn new() -> Self { SparseIdxSet(ArrayVec::new()) } fn len(&self) -> usize { self.0.len() } fn contains(&self, elem: &T) -> bool { self.0.contains(elem) } fn add(&mut self, elem: &T) -> bool { // Ensure there are no duplicates. if self.0.contains(elem) { false } else { self.0.push(*elem); true } } fn remove(&mut self, elem: &T) -> bool { if let Some(i) = self.0.iter().position(|e| e == elem) { // Swap the found element to the end, then pop it. let len = self.0.len(); self.0.swap(i, len - 1); self.0.pop(); true } else { false } } fn to_dense(&self, domain_size: usize) -> IdxSet<T> { let mut dense = IdxSet::new_empty(domain_size); for elem in self.0.iter() { dense.add(elem); } dense } fn iter(&self) -> SparseIter<T> { SparseIter { iter: self.0.iter(), } } } impl<T: Idx> UnionIntoIdxSet<T> for SparseIdxSet<T> { fn union_into(&self, other: &mut IdxSet<T>) -> bool { let mut changed = false; for elem in self.iter() { changed |= other.add(&elem); } changed } } impl<T: Idx> SubtractFromIdxSet<T> for SparseIdxSet<T> { fn subtract_from(&self, other: &mut IdxSet<T>) -> bool { let mut changed = false; for elem in self.iter() { changed |= other.remove(&elem); } changed } } pub struct SparseIter<'a, T: Idx> { iter: slice::Iter<'a, T>, } impl<'a, T: Idx> Iterator for SparseIter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { self.iter.next().map(|e| *e) } } /// Like IdxSet, but with a hybrid representation: sparse when there are few /// elements in the set, but dense when there are many. It's especially /// efficient for sets that typically have a small number of elements, but a /// large `domain_size`, and are cleared frequently. #[derive(Clone, Debug)] pub enum HybridIdxSet<T: Idx> { Sparse(SparseIdxSet<T>, usize), Dense(IdxSet<T>, usize), } impl<T: Idx> HybridIdxSet<T> { pub fn
(domain_size: usize) -> Self { HybridIdxSet::Sparse(SparseIdxSet::new(), domain_size) } pub fn clear(&mut self) { let domain_size = match *self { HybridIdxSet::Sparse(_, size) => size, HybridIdxSet::Dense(_, size) => size, }; *self = HybridIdxSet::new_empty(domain_size); } /// Returns true iff set `self` contains `elem`. pub fn contains(&self, elem: &T) -> bool { match self { HybridIdxSet::Sparse(sparse, _) => sparse.contains(elem), HybridIdxSet::Dense(dense, _) => dense.contains(elem), } } /// Adds `elem` to the set `self`. pub fn add(&mut self, elem: &T) -> bool { match self { HybridIdxSet::Sparse(sparse, _) if sparse.len() < SPARSE_MAX => { // The set is sparse and has space for `elem`. sparse.add(elem) } HybridIdxSet::Sparse(sparse, _) if sparse.contains(elem) => { // The set is sparse and does not have space for `elem`, but // that doesn't matter because `elem` is already present. false } HybridIdxSet::Sparse(_, _) => { // The set is sparse and full. Convert to a dense set. // // FIXME: This code is awful, but I can't work out how else to // appease the borrow checker. let dummy = HybridIdxSet::Sparse(SparseIdxSet::new(), 0); match mem::replace(self, dummy) { HybridIdxSet::Sparse(sparse, domain_size) => { let mut dense = sparse.to_dense(domain_size); let changed = dense.add(elem); assert!(changed); mem::replace(self, HybridIdxSet::Dense(dense, domain_size)); changed } _ => panic!("impossible"), } } HybridIdxSet::Dense(dense, _) => dense.add(elem), } } /// Removes `elem` from the set `self`. pub fn remove(&mut self, elem: &T) -> bool { // Note: we currently don't bother going from Dense back to Sparse. match self { HybridIdxSet::Sparse(sparse, _) => sparse.remove(elem), HybridIdxSet::Dense(dense, _) => dense.remove(elem), } } /// Converts to a dense set, consuming itself in the process. pub fn to_dense(self) -> IdxSet<T> { match self { HybridIdxSet::Sparse(sparse, domain_size) => sparse.to_dense(domain_size), HybridIdxSet::Dense(dense, _) => dense, } } /// Iteration order is unspecified. pub fn iter(&self) -> HybridIter<T> { match self { HybridIdxSet::Sparse(sparse, _) => HybridIter::Sparse(sparse.iter()), HybridIdxSet::Dense(dense, _) => HybridIter::Dense(dense.iter()), } } } impl<T: Idx> UnionIntoIdxSet<T> for HybridIdxSet<T> { fn union_into(&self, other: &mut IdxSet<T>) -> bool { match self { HybridIdxSet::Sparse(sparse, _) => sparse.union_into(other), HybridIdxSet::Dense(dense, _) => dense.union_into(other), } } } impl<T: Idx> SubtractFromIdxSet<T> for HybridIdxSet<T> { fn subtract_from(&self, other: &mut IdxSet<T>) -> bool { match self { HybridIdxSet::Sparse(sparse, _) => sparse.subtract_from(other), HybridIdxSet::Dense(dense, _) => dense.subtract_from(other), } } } pub enum HybridIter<'a, T: Idx> { Sparse(SparseIter<'a, T>), Dense(Iter<'a, T>), } impl<'a, T: Idx> Iterator for HybridIter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { match self { HybridIter::Sparse(sparse) => sparse.next(), HybridIter::Dense(dense) => dense.next(), } } } #[test] fn test_trim_to() { use std::cmp; for i in 0..256 { let mut idx_buf: IdxSet<usize> = IdxSet::new_filled(128); idx_buf.trim_to(i); let elems: Vec<usize> = idx_buf.iter().collect(); let expected: Vec<usize> = (0..cmp::min(i, 128)).collect(); assert_eq!(elems, expected); } } #[test] fn test_set_up_to() { for i in 0..128 { for mut idx_buf in vec![IdxSet::new_empty(128), IdxSet::new_filled(128)] .into_iter() { idx_buf.set_up_to(i); let elems: Vec<usize> = idx_buf.iter().collect(); let expected: Vec<usize> = (0..i).collect(); assert_eq!(elems, expected); } } } #[test] fn test_new_filled() { for i in 0..128 { let idx_buf = IdxSet::new_filled(i); let elems: Vec<usize> = idx_buf.iter().collect(); let expected: Vec<usize> = (0..i).collect(); assert_eq!(elems, expected); } }
new_empty
identifier_name
indexed_set.rs
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use array_vec::ArrayVec; use std::fmt; use std::iter; use std::marker::PhantomData; use std::mem; use std::slice; use bitslice::{BitSlice, Word}; use bitslice::{bitwise, Union, Subtract, Intersect}; use indexed_vec::Idx; use rustc_serialize; /// This is implemented by all the index sets so that IdxSet::union() can be /// passed any type of index set. pub trait UnionIntoIdxSet<T: Idx> { // Performs `other = other | self`. fn union_into(&self, other: &mut IdxSet<T>) -> bool; } /// This is implemented by all the index sets so that IdxSet::subtract() can be /// passed any type of index set. pub trait SubtractFromIdxSet<T: Idx> { // Performs `other = other - self`. fn subtract_from(&self, other: &mut IdxSet<T>) -> bool; } /// Represents a set of some element type E, where each E is identified by some /// unique index type `T`. /// /// In other words, `T` is the type used to index into the bitvector /// this type uses to represent the set of object it holds. /// /// The representation is dense, using one bit per possible element. #[derive(Eq, PartialEq)] pub struct IdxSet<T: Idx> { _pd: PhantomData<fn(&T)>, bits: Vec<Word>, } impl<T: Idx> Clone for IdxSet<T> { fn clone(&self) -> Self { IdxSet { _pd: PhantomData, bits: self.bits.clone() } } } impl<T: Idx> rustc_serialize::Encodable for IdxSet<T> { fn encode<E: rustc_serialize::Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> { self.bits.encode(encoder) } } impl<T: Idx> rustc_serialize::Decodable for IdxSet<T> { fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<IdxSet<T>, D::Error> { let words: Vec<Word> = rustc_serialize::Decodable::decode(d)?; Ok(IdxSet { _pd: PhantomData, bits: words, }) } } const BITS_PER_WORD: usize = mem::size_of::<Word>() * 8; impl<T: Idx> fmt::Debug for IdxSet<T> { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { w.debug_list() .entries(self.iter()) .finish() } } impl<T: Idx> IdxSet<T> { fn new(init: Word, domain_size: usize) -> Self { let num_words = (domain_size + (BITS_PER_WORD - 1)) / BITS_PER_WORD; IdxSet { _pd: Default::default(), bits: vec![init; num_words], } } /// Creates set holding every element whose index falls in range 0..domain_size. pub fn new_filled(domain_size: usize) -> Self { let mut result = Self::new(!0, domain_size); result.trim_to(domain_size); result } /// Creates set holding no elements. pub fn new_empty(domain_size: usize) -> Self { Self::new(0, domain_size) } /// Duplicates as a hybrid set. pub fn to_hybrid(&self) -> HybridIdxSet<T> { // This domain_size may be slightly larger than the one specified // upon creation, due to rounding up to a whole word. That's ok. let domain_size = self.bits.len() * BITS_PER_WORD; // Note: we currently don't bother trying to make a Sparse set. HybridIdxSet::Dense(self.to_owned(), domain_size) } /// Removes all elements pub fn clear(&mut self) { for b in &mut self.bits { *b = 0; } } /// Sets all elements up to `domain_size` pub fn set_up_to(&mut self, domain_size: usize) { for b in &mut self.bits { *b =!0; } self.trim_to(domain_size); } /// Clear all elements above `domain_size`. fn trim_to(&mut self, domain_size: usize) { // `trim_block` is the first block where some bits have // to be cleared. let trim_block = domain_size / BITS_PER_WORD; // all the blocks above it have to be completely cleared. if trim_block < self.bits.len() { for b in &mut self.bits[trim_block+1..] { *b = 0; } // at that block, the `domain_size % BITS_PER_WORD` LSBs // should remain. let remaining_bits = domain_size % BITS_PER_WORD; let mask = (1<<remaining_bits)-1; self.bits[trim_block] &= mask; } } /// Removes `elem` from the set `self`; returns true iff this changed `self`. pub fn remove(&mut self, elem: &T) -> bool { self.bits.clear_bit(elem.index()) } /// Adds `elem` to the set `self`; returns true iff this changed `self`. pub fn add(&mut self, elem: &T) -> bool { self.bits.set_bit(elem.index()) } /// Returns true iff set `self` contains `elem`. pub fn contains(&self, elem: &T) -> bool { self.bits.get_bit(elem.index()) } pub fn words(&self) -> &[Word] { &self.bits } pub fn words_mut(&mut self) -> &mut [Word] { &mut self.bits } /// Efficiently overwrite `self` with `other`. Panics if `self` and `other` /// don't have the same length. pub fn overwrite(&mut self, other: &IdxSet<T>) { self.words_mut().clone_from_slice(other.words()); } /// Set `self = self | other` and return true if `self` changed /// (i.e., if new bits were added). pub fn union(&mut self, other: &impl UnionIntoIdxSet<T>) -> bool { other.union_into(self) } /// Set `self = self - other` and return true if `self` changed. /// (i.e., if any bits were removed). pub fn subtract(&mut self, other: &impl SubtractFromIdxSet<T>) -> bool { other.subtract_from(self) } /// Set `self = self & other` and return true if `self` changed. /// (i.e., if any bits were removed). pub fn intersect(&mut self, other: &IdxSet<T>) -> bool { bitwise(self.words_mut(), other.words(), &Intersect) } pub fn iter(&self) -> Iter<T> { Iter { cur: None, iter: self.words().iter().enumerate(), _pd: PhantomData, } } } impl<T: Idx> UnionIntoIdxSet<T> for IdxSet<T> { fn union_into(&self, other: &mut IdxSet<T>) -> bool { bitwise(other.words_mut(), self.words(), &Union) } } impl<T: Idx> SubtractFromIdxSet<T> for IdxSet<T> { fn subtract_from(&self, other: &mut IdxSet<T>) -> bool { bitwise(other.words_mut(), self.words(), &Subtract) } } pub struct Iter<'a, T: Idx> { cur: Option<(Word, usize)>, iter: iter::Enumerate<slice::Iter<'a, Word>>, _pd: PhantomData<fn(&T)>, } impl<'a, T: Idx> Iterator for Iter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { loop { if let Some((ref mut word, offset)) = self.cur { let bit_pos = word.trailing_zeros() as usize; if bit_pos!= BITS_PER_WORD { let bit = 1 << bit_pos; *word ^= bit; return Some(T::new(bit_pos + offset)) } } let (i, word) = self.iter.next()?; self.cur = Some((*word, BITS_PER_WORD * i)); } } } const SPARSE_MAX: usize = 8; /// A sparse index set with a maximum of SPARSE_MAX elements. Used by /// HybridIdxSet; do not use directly. /// /// The elements are stored as an unsorted vector with no duplicates. #[derive(Clone, Debug)] pub struct SparseIdxSet<T: Idx>(ArrayVec<[T; SPARSE_MAX]>); impl<T: Idx> SparseIdxSet<T> { fn new() -> Self { SparseIdxSet(ArrayVec::new()) } fn len(&self) -> usize { self.0.len() } fn contains(&self, elem: &T) -> bool { self.0.contains(elem) } fn add(&mut self, elem: &T) -> bool { // Ensure there are no duplicates. if self.0.contains(elem) { false } else { self.0.push(*elem); true } } fn remove(&mut self, elem: &T) -> bool { if let Some(i) = self.0.iter().position(|e| e == elem) { // Swap the found element to the end, then pop it. let len = self.0.len(); self.0.swap(i, len - 1); self.0.pop(); true } else { false } } fn to_dense(&self, domain_size: usize) -> IdxSet<T> { let mut dense = IdxSet::new_empty(domain_size); for elem in self.0.iter() { dense.add(elem); } dense } fn iter(&self) -> SparseIter<T> { SparseIter { iter: self.0.iter(), } } } impl<T: Idx> UnionIntoIdxSet<T> for SparseIdxSet<T> { fn union_into(&self, other: &mut IdxSet<T>) -> bool { let mut changed = false; for elem in self.iter() { changed |= other.add(&elem); } changed } } impl<T: Idx> SubtractFromIdxSet<T> for SparseIdxSet<T> { fn subtract_from(&self, other: &mut IdxSet<T>) -> bool { let mut changed = false; for elem in self.iter() { changed |= other.remove(&elem); } changed } } pub struct SparseIter<'a, T: Idx> { iter: slice::Iter<'a, T>, } impl<'a, T: Idx> Iterator for SparseIter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { self.iter.next().map(|e| *e) } } /// Like IdxSet, but with a hybrid representation: sparse when there are few /// elements in the set, but dense when there are many. It's especially /// efficient for sets that typically have a small number of elements, but a /// large `domain_size`, and are cleared frequently. #[derive(Clone, Debug)] pub enum HybridIdxSet<T: Idx> { Sparse(SparseIdxSet<T>, usize), Dense(IdxSet<T>, usize), } impl<T: Idx> HybridIdxSet<T> { pub fn new_empty(domain_size: usize) -> Self { HybridIdxSet::Sparse(SparseIdxSet::new(), domain_size) } pub fn clear(&mut self) { let domain_size = match *self { HybridIdxSet::Sparse(_, size) => size, HybridIdxSet::Dense(_, size) => size, }; *self = HybridIdxSet::new_empty(domain_size); } /// Returns true iff set `self` contains `elem`. pub fn contains(&self, elem: &T) -> bool { match self { HybridIdxSet::Sparse(sparse, _) => sparse.contains(elem), HybridIdxSet::Dense(dense, _) => dense.contains(elem), } } /// Adds `elem` to the set `self`. pub fn add(&mut self, elem: &T) -> bool { match self { HybridIdxSet::Sparse(sparse, _) if sparse.len() < SPARSE_MAX => { // The set is sparse and has space for `elem`. sparse.add(elem) } HybridIdxSet::Sparse(sparse, _) if sparse.contains(elem) => { // The set is sparse and does not have space for `elem`, but // that doesn't matter because `elem` is already present. false } HybridIdxSet::Sparse(_, _) => { // The set is sparse and full. Convert to a dense set. // // FIXME: This code is awful, but I can't work out how else to // appease the borrow checker. let dummy = HybridIdxSet::Sparse(SparseIdxSet::new(), 0); match mem::replace(self, dummy) { HybridIdxSet::Sparse(sparse, domain_size) => { let mut dense = sparse.to_dense(domain_size); let changed = dense.add(elem); assert!(changed); mem::replace(self, HybridIdxSet::Dense(dense, domain_size)); changed } _ => panic!("impossible"), } } HybridIdxSet::Dense(dense, _) => dense.add(elem), } } /// Removes `elem` from the set `self`. pub fn remove(&mut self, elem: &T) -> bool { // Note: we currently don't bother going from Dense back to Sparse. match self { HybridIdxSet::Sparse(sparse, _) => sparse.remove(elem), HybridIdxSet::Dense(dense, _) => dense.remove(elem), } } /// Converts to a dense set, consuming itself in the process. pub fn to_dense(self) -> IdxSet<T> { match self { HybridIdxSet::Sparse(sparse, domain_size) => sparse.to_dense(domain_size), HybridIdxSet::Dense(dense, _) => dense, } } /// Iteration order is unspecified. pub fn iter(&self) -> HybridIter<T> { match self { HybridIdxSet::Sparse(sparse, _) => HybridIter::Sparse(sparse.iter()), HybridIdxSet::Dense(dense, _) => HybridIter::Dense(dense.iter()), } } } impl<T: Idx> UnionIntoIdxSet<T> for HybridIdxSet<T> { fn union_into(&self, other: &mut IdxSet<T>) -> bool { match self { HybridIdxSet::Sparse(sparse, _) => sparse.union_into(other), HybridIdxSet::Dense(dense, _) => dense.union_into(other), } } } impl<T: Idx> SubtractFromIdxSet<T> for HybridIdxSet<T> { fn subtract_from(&self, other: &mut IdxSet<T>) -> bool { match self { HybridIdxSet::Sparse(sparse, _) => sparse.subtract_from(other), HybridIdxSet::Dense(dense, _) => dense.subtract_from(other), } } } pub enum HybridIter<'a, T: Idx> { Sparse(SparseIter<'a, T>), Dense(Iter<'a, T>), } impl<'a, T: Idx> Iterator for HybridIter<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { match self { HybridIter::Sparse(sparse) => sparse.next(), HybridIter::Dense(dense) => dense.next(), } } } #[test] fn test_trim_to() { use std::cmp; for i in 0..256 { let mut idx_buf: IdxSet<usize> = IdxSet::new_filled(128); idx_buf.trim_to(i); let elems: Vec<usize> = idx_buf.iter().collect(); let expected: Vec<usize> = (0..cmp::min(i, 128)).collect(); assert_eq!(elems, expected); } } #[test] fn test_set_up_to() { for i in 0..128 { for mut idx_buf in vec![IdxSet::new_empty(128), IdxSet::new_filled(128)] .into_iter() { idx_buf.set_up_to(i); let elems: Vec<usize> = idx_buf.iter().collect(); let expected: Vec<usize> = (0..i).collect();
#[test] fn test_new_filled() { for i in 0..128 { let idx_buf = IdxSet::new_filled(i); let elems: Vec<usize> = idx_buf.iter().collect(); let expected: Vec<usize> = (0..i).collect(); assert_eq!(elems, expected); } }
assert_eq!(elems, expected); } } }
random_line_split
source_contributions.rs
extern crate clap; extern crate csv; extern crate reqwest; extern crate serde; extern crate failure; #[macro_use] extern crate failure_derive; use clap::{App, Arg}; use csv::StringRecord; use reqwest::{Client, Url}; use serde::de::DeserializeOwned; use serde::Deserialize; use std::{thread, time}; use std::collections::HashSet; use std::env; use std::fs::{File, OpenOptions}; use std::io::Write; enum HttpMethod { Get, } #[derive(Debug, Fail)] enum AppError { // Returned when we couldn't extract an owner and a repo from the repository URL. #[fail(display = "Couldn't extract project metadata for {}", repo_url)] MetadataExtractionFailed { repo_url: String }, // Returned in case of generic I/O error. #[fail(display = "i/o error when reading/writing on the CSV file {}", _0)] IOError(std::io::Error), // Returned when the OSRANK_GITHUB_TOKEN is not present as an env var. #[fail(display = "Couldn't find OSRANK_GITHUB_TOKEN in your env vars: {}", _0)] GithubTokenNotFound(std::env::VarError), // Returned when we failed to issue the HTTP request. #[fail(display = "Request to Github failed: {}", _0)] GithubAPIRequestFailed(reqwest::Error), // Returned when the Github API returned a non-2xx status code. #[fail(display = "Github returned non-200 {} with body {}", _0, _1)] GithubAPINotOK(reqwest::StatusCode, String), // Returned when the parsing of the http URL to query Github failed. #[fail(display = "Github URL failed parsing into a valid HTTP URL: {}", _0)] GithubUrlParsingFailed(reqwest::UrlError), // Returned when the Github API returned a non-2xx status code. #[fail(display = "Couldn't deserialise the JSON returned by Github: {}", _0)] DeserialisationFailure(reqwest::Error), // Returned when the Github API returned a non-2xx status code. #[fail(display = "No more retries.")] NoRetriesLeft, } impl From<std::io::Error> for AppError { fn from(err: std::io::Error) -> AppError { AppError::IOError(err) } } impl From<std::env::VarError> for AppError { fn from(err: std::env::VarError) -> AppError { AppError::GithubTokenNotFound(err) } } impl From<reqwest::Error> for AppError { fn from(err: reqwest::Error) -> AppError { AppError::GithubAPIRequestFailed(err) } } impl From<reqwest::UrlError> for AppError { fn from(err: reqwest::UrlError) -> AppError { AppError::GithubUrlParsingFailed(err) } } // The order of the fields must be the same of the input file. #[derive(Debug)] struct Project<'a> { id: u32, platform: &'a str, project_name: &'a str, repository_url: &'a str, repository_fork: bool, repository_display_name: &'a str, } struct Retries { retries_num: u8, } impl Retries { fn new(retries_num: u8) -> Self { Retries { retries_num } } } #[derive(Debug, Deserialize)] struct GithubContribution { total: u64, author: GithubUser, weeks: Vec<GithubWeek>, } #[derive(Debug, Deserialize)] struct GithubWeek { // Unix timestamp of the beginning of this week. w: u64, } #[derive(Debug, Deserialize)] struct GithubUser { login: String, id: u64, } type UniqueProjects = HashSet<String>; /// Calls the Github API using the given HttpMethod and url_path. Due to the /// fact some endpoints like the statistics one use cached information and /// might return a 202 with an empty JSON as the stats are computed, we need /// to wait a little bit and retry, up to a certain number of times. fn call_github<T>( http_client: &Client, http_method: HttpMethod, token: &str, url_path: &str, retries: Retries, ) -> Result<T, AppError> where T: DeserializeOwned, { let retries_left = retries.retries_num; if retries_left == 0 { Err(AppError::NoRetriesLeft) } else { let bearer = format!("Bearer {}", token); match http_method { HttpMethod::Get => { let url: Url = format!("{}{}", GITHUB_BASE_URL, url_path) .as_str() .parse()?; let mut res = http_client .get(url) .header(reqwest::header::AUTHORIZATION, bearer.as_str()) .send()?; match res.status() { reqwest::StatusCode::OK => res .json() .or_else(|e| Err(AppError::DeserialisationFailure(e))), // Github needs a bit more time to compute the stats. // We retry. reqwest::StatusCode::ACCEPTED => { println!("Retrying, only {} retries left...", retries_left); thread::sleep(time::Duration::from_secs(1)); call_github( http_client, http_method, token, url_path, Retries::new(retries_left - 1), ) } err => { let body = res.text()?; Err(AppError::GithubAPINotOK(err, body)) } } } } } } fn deserialise_project(sr: &StringRecord) -> Option<Project> { if let Some(Ok(pid)) = sr.get(0).map(|s: &str| s.parse::<u32>()) { let platform = sr.get(1); let project_name = sr.get(2); let repository_url = sr.get(9); let repository_fork = sr.get(24).and_then(|s: &str| match s { "0" => Some(false), "1" => Some(true), "t" => Some(true), "f" => Some(false), "true" => Some(true), "false" => Some(false), _ => None, }); let repository_display_name = sr.get(54); match ( platform, project_name, repository_url, repository_fork, repository_display_name, ) { (Some(pl), Some(pn), Some(ru), Some(rf), Some(dn)) => Some(Project { id: pid, platform: pl, project_name: pn, repository_url: ru, repository_fork: rf, repository_display_name: dn, }), _ => None, } } else { None } } fn source_contributors( github_token: &str, path: &str, platform: &str, resume_from: Option<&str>, ) -> Result<(), AppError> { let projects_file = File::open(path)?; // Build the CSV reader and iterate over each record. let mut rdr = csv::ReaderBuilder::new() .flexible(true) .from_reader(projects_file); let mut contributions = OpenOptions::new() .append(resume_from.is_some()) .write(resume_from.is_none()) .create_new(resume_from.is_none()) // Allow re-opening if we need to resume. .open(format!("data/{}_contributions.csv", platform.to_lowercase()).as_str())?; let mut unique_projects = HashSet::new(); let http_client = reqwest::Client::new(); let mut skip_resumed_record = resume_from.is_some(); //Write the header (if we are not resuming) if resume_from.is_none() { contributions.write_all(b"ID,MAINTAINER,REPO,CONTRIBUTIONS,NAME\n")?; } for result in rdr .records() .filter_map(|e| e.ok()) .filter(by_platform(platform)) .skip_while(resumes(resume_from)) { // As we cannot know which is the /next/ element we need to process // and we are resuming from the last (known) one, we need to skip it // in order to not create a dupe. if skip_resumed_record { skip_resumed_record = false; continue; } if let Some(project) = deserialise_project(&result) { extract_contribution( &http_client, &mut contributions, &mut unique_projects, project, github_token, )?; } } Ok(()) } fn
(repo_url: &str) -> Result<(&str, &str), AppError> { match repo_url.split('/').collect::<Vec<&str>>().as_slice() { [_, "", "github.com", owner, repo] => Ok((owner, repo)), _ => Err(AppError::MetadataExtractionFailed { repo_url: repo_url.to_string(), }), } } // Extract the contribution relative to this project. For now only GitHub is // supported. fn extract_contribution( http_client: &Client, contributions: &mut File, unique_projects: &mut UniqueProjects, project: Project, auth_token: &str, ) -> Result<(), AppError> { // If this is an authentic project and not a fork, proceed. if!project.repository_fork && unique_projects.get(project.project_name) == None { match extract_github_owner_and_repo(project.repository_url) { Err(err) => { println!("Skipping {} due to {:#?}", &project.repository_url, err); Ok(()) } Ok((owner, name)) => { unique_projects.insert(String::from(project.project_name)); println!("Processing {} ({}/{})", project.project_name, owner, name); let res: Result<Vec<GithubContribution>, AppError> = call_github( &http_client, HttpMethod::Get, auth_token, format!("/repos/{}/{}/stats/contributors", owner, name).as_str(), Retries::new(5), ); match res { Err(err) => { println!("Skipping {} due to {:#?}", &project.repository_url, err); } Ok(stats) => { let stats_len = stats.len(); for contribution in stats { if is_maintainer(&owner, &contribution, stats_len) { contributions.write_all( format!( "{},github@{},{},{},{}\n", project.id, contribution.author.login, project.repository_url, contribution.total, project.project_name ) .as_bytes(), )?; } } } } // Wait 800 ms to not overload Github and not hit the quota limit. // GH allows us 5000 requests per hour. If we wait 800ms, we // aim for the theoretical limit, while preserving a certain // slack. let delay = time::Duration::from_millis(800); thread::sleep(delay); Ok(()) } } } else { Ok(()) } } // FIXME(adn) Totally arbitrary choice: consider a maintainer // for a project a user that has been contributed for more // than 6 months. Furthermore, it needs to have a somewhat steady contribution // history. fn is_maintainer(owner: &str, stat: &GithubContribution, stats_len: usize) -> bool { // Users are considered a contributor if one of the following occur: // 1. The owner of the repo is equal to their username; // 2. They have at least 50 contributions // 3. They are the only contributor to the repo. stat.author.login == owner || { stat.total > 50 } || stats_len as u32 == 1 } fn by_platform<'a>(platform: &'a str) -> Box<dyn FnMut(&StringRecord) -> bool + 'a> { Box::new(move |e| e[1] == *platform) } // Returns false if the user didn't ask to resume the process from a particular // project URL. If the user supplied a project, it skips StringRecord entries // until it matches the input URL. fn resumes<'a>(resume_from: Option<&'a str>) -> Box<dyn FnMut(&StringRecord) -> bool + 'a> { Box::new(move |e| match resume_from { None => false, Some(repo_url) => Some(repo_url)!= e.get(9), }) } const GITHUB_BASE_URL: &str = "https://api.github.com"; fn main() -> Result<(), AppError> { let github_token = env::var("OSRANK_GITHUB_TOKEN")?; let input_help = r###"Where to read the data from. Example: ~/Downloads/libraries-1.4.0-2018-12-22/projects_with_repository_fields-1.4.0-2018-12-22.csv"###; let matches = App::new("Source contributions from Github") .arg( Arg::with_name("input") .short("i") .long("input") .help(input_help) .index(1) .required(true), ) .arg( Arg::with_name("platform") .short("p") .long("platform") .help("Example: Rust,NPM,Rubygems,..") .index(2) .required(true), ) .arg( Arg::with_name("resume-from") .long("resume-from") .help("which repository URL to resume from.") .takes_value(true) .required(false), ) .get_matches(); source_contributors( &github_token, matches .value_of("input") .expect("input parameter wasn't given."), matches .value_of("platform") .expect("platform parameter wasn't given."), matches.value_of("resume-from"), ) } #[test] fn test_rncryptor_deserialise() { let input:String = String::from(r###" 2084361,Cargo,rncryptor,2016-12-23 09:57:46 UTC,2018-01-03 08:59:05 UTC,Rust implementation of the RNCryptor AES file format,"",http://rncryptor.github.io/,MIT,https://github.com/RNCryptor/rncryptor-rs,1,0,2016-12-23 09:57:29 UTC,0.1.0,,0,Rust,,2018-01-03 08:59:02 UTC,0,17362897,GitHub,RNCryptor/rncryptor-rs,Pure Rust implementation of the RNCryptor cryptographic format by Rob Napier,false,2016-12-18 17:37:39 UTC,2016-12-30 02:04:24 UTC,2016-12-26 17:33:32 UTC,,58,4,Rust,true,true,false,0,,1,master,0,76797122,,MIT,0,"","","","","","","",,2016-12-18 17:38:00 UTC,2,GitHub,,git,,,"" "###); let mut rdr = csv::ReaderBuilder::new() .flexible(true) .from_reader(input.as_bytes()); for result in rdr.records() { let r = result.expect("impossible"); assert_eq!(deserialise_project(&r).is_some(), true) } } #[test] fn skip_while_ok() { let a = [1, -1i32, 0, 1]; let mut iter = a.into_iter().skip_while(|x| x.is_negative()); assert_eq!(iter.next(), Some(&1)); }
extract_github_owner_and_repo
identifier_name
source_contributions.rs
extern crate clap; extern crate csv; extern crate reqwest; extern crate serde; extern crate failure; #[macro_use] extern crate failure_derive; use clap::{App, Arg}; use csv::StringRecord; use reqwest::{Client, Url}; use serde::de::DeserializeOwned; use serde::Deserialize; use std::{thread, time}; use std::collections::HashSet; use std::env; use std::fs::{File, OpenOptions}; use std::io::Write; enum HttpMethod { Get, } #[derive(Debug, Fail)] enum AppError { // Returned when we couldn't extract an owner and a repo from the repository URL. #[fail(display = "Couldn't extract project metadata for {}", repo_url)] MetadataExtractionFailed { repo_url: String }, // Returned in case of generic I/O error. #[fail(display = "i/o error when reading/writing on the CSV file {}", _0)] IOError(std::io::Error), // Returned when the OSRANK_GITHUB_TOKEN is not present as an env var. #[fail(display = "Couldn't find OSRANK_GITHUB_TOKEN in your env vars: {}", _0)] GithubTokenNotFound(std::env::VarError), // Returned when we failed to issue the HTTP request. #[fail(display = "Request to Github failed: {}", _0)] GithubAPIRequestFailed(reqwest::Error), // Returned when the Github API returned a non-2xx status code. #[fail(display = "Github returned non-200 {} with body {}", _0, _1)] GithubAPINotOK(reqwest::StatusCode, String), // Returned when the parsing of the http URL to query Github failed. #[fail(display = "Github URL failed parsing into a valid HTTP URL: {}", _0)] GithubUrlParsingFailed(reqwest::UrlError), // Returned when the Github API returned a non-2xx status code. #[fail(display = "Couldn't deserialise the JSON returned by Github: {}", _0)] DeserialisationFailure(reqwest::Error), // Returned when the Github API returned a non-2xx status code. #[fail(display = "No more retries.")] NoRetriesLeft, } impl From<std::io::Error> for AppError { fn from(err: std::io::Error) -> AppError { AppError::IOError(err) } } impl From<std::env::VarError> for AppError { fn from(err: std::env::VarError) -> AppError { AppError::GithubTokenNotFound(err) } } impl From<reqwest::Error> for AppError { fn from(err: reqwest::Error) -> AppError { AppError::GithubAPIRequestFailed(err) } } impl From<reqwest::UrlError> for AppError { fn from(err: reqwest::UrlError) -> AppError { AppError::GithubUrlParsingFailed(err) } } // The order of the fields must be the same of the input file. #[derive(Debug)] struct Project<'a> { id: u32, platform: &'a str, project_name: &'a str, repository_url: &'a str, repository_fork: bool, repository_display_name: &'a str, } struct Retries { retries_num: u8, } impl Retries { fn new(retries_num: u8) -> Self { Retries { retries_num } } } #[derive(Debug, Deserialize)] struct GithubContribution { total: u64, author: GithubUser, weeks: Vec<GithubWeek>, } #[derive(Debug, Deserialize)] struct GithubWeek { // Unix timestamp of the beginning of this week. w: u64, } #[derive(Debug, Deserialize)] struct GithubUser { login: String, id: u64, } type UniqueProjects = HashSet<String>; /// Calls the Github API using the given HttpMethod and url_path. Due to the /// fact some endpoints like the statistics one use cached information and /// might return a 202 with an empty JSON as the stats are computed, we need /// to wait a little bit and retry, up to a certain number of times. fn call_github<T>( http_client: &Client, http_method: HttpMethod, token: &str, url_path: &str, retries: Retries, ) -> Result<T, AppError> where T: DeserializeOwned,
// We retry. reqwest::StatusCode::ACCEPTED => { println!("Retrying, only {} retries left...", retries_left); thread::sleep(time::Duration::from_secs(1)); call_github( http_client, http_method, token, url_path, Retries::new(retries_left - 1), ) } err => { let body = res.text()?; Err(AppError::GithubAPINotOK(err, body)) } } } } } } fn deserialise_project(sr: &StringRecord) -> Option<Project> { if let Some(Ok(pid)) = sr.get(0).map(|s: &str| s.parse::<u32>()) { let platform = sr.get(1); let project_name = sr.get(2); let repository_url = sr.get(9); let repository_fork = sr.get(24).and_then(|s: &str| match s { "0" => Some(false), "1" => Some(true), "t" => Some(true), "f" => Some(false), "true" => Some(true), "false" => Some(false), _ => None, }); let repository_display_name = sr.get(54); match ( platform, project_name, repository_url, repository_fork, repository_display_name, ) { (Some(pl), Some(pn), Some(ru), Some(rf), Some(dn)) => Some(Project { id: pid, platform: pl, project_name: pn, repository_url: ru, repository_fork: rf, repository_display_name: dn, }), _ => None, } } else { None } } fn source_contributors( github_token: &str, path: &str, platform: &str, resume_from: Option<&str>, ) -> Result<(), AppError> { let projects_file = File::open(path)?; // Build the CSV reader and iterate over each record. let mut rdr = csv::ReaderBuilder::new() .flexible(true) .from_reader(projects_file); let mut contributions = OpenOptions::new() .append(resume_from.is_some()) .write(resume_from.is_none()) .create_new(resume_from.is_none()) // Allow re-opening if we need to resume. .open(format!("data/{}_contributions.csv", platform.to_lowercase()).as_str())?; let mut unique_projects = HashSet::new(); let http_client = reqwest::Client::new(); let mut skip_resumed_record = resume_from.is_some(); //Write the header (if we are not resuming) if resume_from.is_none() { contributions.write_all(b"ID,MAINTAINER,REPO,CONTRIBUTIONS,NAME\n")?; } for result in rdr .records() .filter_map(|e| e.ok()) .filter(by_platform(platform)) .skip_while(resumes(resume_from)) { // As we cannot know which is the /next/ element we need to process // and we are resuming from the last (known) one, we need to skip it // in order to not create a dupe. if skip_resumed_record { skip_resumed_record = false; continue; } if let Some(project) = deserialise_project(&result) { extract_contribution( &http_client, &mut contributions, &mut unique_projects, project, github_token, )?; } } Ok(()) } fn extract_github_owner_and_repo(repo_url: &str) -> Result<(&str, &str), AppError> { match repo_url.split('/').collect::<Vec<&str>>().as_slice() { [_, "", "github.com", owner, repo] => Ok((owner, repo)), _ => Err(AppError::MetadataExtractionFailed { repo_url: repo_url.to_string(), }), } } // Extract the contribution relative to this project. For now only GitHub is // supported. fn extract_contribution( http_client: &Client, contributions: &mut File, unique_projects: &mut UniqueProjects, project: Project, auth_token: &str, ) -> Result<(), AppError> { // If this is an authentic project and not a fork, proceed. if!project.repository_fork && unique_projects.get(project.project_name) == None { match extract_github_owner_and_repo(project.repository_url) { Err(err) => { println!("Skipping {} due to {:#?}", &project.repository_url, err); Ok(()) } Ok((owner, name)) => { unique_projects.insert(String::from(project.project_name)); println!("Processing {} ({}/{})", project.project_name, owner, name); let res: Result<Vec<GithubContribution>, AppError> = call_github( &http_client, HttpMethod::Get, auth_token, format!("/repos/{}/{}/stats/contributors", owner, name).as_str(), Retries::new(5), ); match res { Err(err) => { println!("Skipping {} due to {:#?}", &project.repository_url, err); } Ok(stats) => { let stats_len = stats.len(); for contribution in stats { if is_maintainer(&owner, &contribution, stats_len) { contributions.write_all( format!( "{},github@{},{},{},{}\n", project.id, contribution.author.login, project.repository_url, contribution.total, project.project_name ) .as_bytes(), )?; } } } } // Wait 800 ms to not overload Github and not hit the quota limit. // GH allows us 5000 requests per hour. If we wait 800ms, we // aim for the theoretical limit, while preserving a certain // slack. let delay = time::Duration::from_millis(800); thread::sleep(delay); Ok(()) } } } else { Ok(()) } } // FIXME(adn) Totally arbitrary choice: consider a maintainer // for a project a user that has been contributed for more // than 6 months. Furthermore, it needs to have a somewhat steady contribution // history. fn is_maintainer(owner: &str, stat: &GithubContribution, stats_len: usize) -> bool { // Users are considered a contributor if one of the following occur: // 1. The owner of the repo is equal to their username; // 2. They have at least 50 contributions // 3. They are the only contributor to the repo. stat.author.login == owner || { stat.total > 50 } || stats_len as u32 == 1 } fn by_platform<'a>(platform: &'a str) -> Box<dyn FnMut(&StringRecord) -> bool + 'a> { Box::new(move |e| e[1] == *platform) } // Returns false if the user didn't ask to resume the process from a particular // project URL. If the user supplied a project, it skips StringRecord entries // until it matches the input URL. fn resumes<'a>(resume_from: Option<&'a str>) -> Box<dyn FnMut(&StringRecord) -> bool + 'a> { Box::new(move |e| match resume_from { None => false, Some(repo_url) => Some(repo_url)!= e.get(9), }) } const GITHUB_BASE_URL: &str = "https://api.github.com"; fn main() -> Result<(), AppError> { let github_token = env::var("OSRANK_GITHUB_TOKEN")?; let input_help = r###"Where to read the data from. Example: ~/Downloads/libraries-1.4.0-2018-12-22/projects_with_repository_fields-1.4.0-2018-12-22.csv"###; let matches = App::new("Source contributions from Github") .arg( Arg::with_name("input") .short("i") .long("input") .help(input_help) .index(1) .required(true), ) .arg( Arg::with_name("platform") .short("p") .long("platform") .help("Example: Rust,NPM,Rubygems,..") .index(2) .required(true), ) .arg( Arg::with_name("resume-from") .long("resume-from") .help("which repository URL to resume from.") .takes_value(true) .required(false), ) .get_matches(); source_contributors( &github_token, matches .value_of("input") .expect("input parameter wasn't given."), matches .value_of("platform") .expect("platform parameter wasn't given."), matches.value_of("resume-from"), ) } #[test] fn test_rncryptor_deserialise() { let input:String = String::from(r###" 2084361,Cargo,rncryptor,2016-12-23 09:57:46 UTC,2018-01-03 08:59:05 UTC,Rust implementation of the RNCryptor AES file format,"",http://rncryptor.github.io/,MIT,https://github.com/RNCryptor/rncryptor-rs,1,0,2016-12-23 09:57:29 UTC,0.1.0,,0,Rust,,2018-01-03 08:59:02 UTC,0,17362897,GitHub,RNCryptor/rncryptor-rs,Pure Rust implementation of the RNCryptor cryptographic format by Rob Napier,false,2016-12-18 17:37:39 UTC,2016-12-30 02:04:24 UTC,2016-12-26 17:33:32 UTC,,58,4,Rust,true,true,false,0,,1,master,0,76797122,,MIT,0,"","","","","","","",,2016-12-18 17:38:00 UTC,2,GitHub,,git,,,"" "###); let mut rdr = csv::ReaderBuilder::new() .flexible(true) .from_reader(input.as_bytes()); for result in rdr.records() { let r = result.expect("impossible"); assert_eq!(deserialise_project(&r).is_some(), true) } } #[test] fn skip_while_ok() { let a = [1, -1i32, 0, 1]; let mut iter = a.into_iter().skip_while(|x| x.is_negative()); assert_eq!(iter.next(), Some(&1)); }
{ let retries_left = retries.retries_num; if retries_left == 0 { Err(AppError::NoRetriesLeft) } else { let bearer = format!("Bearer {}", token); match http_method { HttpMethod::Get => { let url: Url = format!("{}{}", GITHUB_BASE_URL, url_path) .as_str() .parse()?; let mut res = http_client .get(url) .header(reqwest::header::AUTHORIZATION, bearer.as_str()) .send()?; match res.status() { reqwest::StatusCode::OK => res .json() .or_else(|e| Err(AppError::DeserialisationFailure(e))), // Github needs a bit more time to compute the stats.
identifier_body