Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial run at a Rust executor with tests #610

Draft
wants to merge 1 commit into
base: trunk
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ fluent-langneg = "0.14"
fluent-syntax = "0.11"
fluent-templates = "0.13"
http = "1.2"
hyper-util = "0.1.10"
icu_locid = "1.5"
indoc = "2.0"
parse_link_header = "0.4"
Expand Down
3 changes: 3 additions & 0 deletions wp_api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,20 @@ base64 = { workspace = true }
chrono = { workspace = true, features = [ "serde" ] }
futures = { workspace = true }
http = { workspace = true }
hyper-util = { workspace = true }
indoc = { workspace = true }
url = { workspace = true }
parse_link_header = { workspace = true }
paste = { workspace = true }
regex = { workspace = true }
reqwest = { workspace = true, features = ["json"] }
scraper = { workspace = true }
serde = { workspace = true, features = [ "derive", "rc" ] }
serde_json = { workspace = true }
strum = { workspace = true }
strum_macros = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
uniffi = { workspace = true }
uuid = { workspace = true, features = [ "v4" ] }
wp_contextual = { path = "../wp_contextual" }
Expand Down
30 changes: 30 additions & 0 deletions wp_api/src/api_error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::login::url_discovery::AutoDiscoveryAttemptFailure;
use crate::request::{HttpAuthMethod, HttpAuthMethodParsingError};
use crate::{
request::{request_or_response_body_as_string, WpRedirect},
Expand All @@ -14,6 +15,16 @@ where
fn as_parse_error(reason: String, response: String) -> Self;
}

#[derive(Debug, PartialEq, Eq, thiserror::Error, uniffi::Error)]
pub enum UrlDiscoveryError {
#[error("{}", reason)]
Transparent { reason: String },
#[error("{}", error)]
ApiError { error: WpApiError },
#[error("{}", reason)]
RequestExecutionError { reason: RequestExecutionErrorReason },
}

#[derive(Debug, PartialEq, Eq, thiserror::Error, uniffi::Error)]
pub enum WpApiError {
#[error("Status code ({}) is not valid", status_code)]
Expand Down Expand Up @@ -538,3 +549,22 @@ impl From<HttpAuthMethodParsingError> for WpApiError {
}
}
}

impl TryFrom<AutoDiscoveryAttemptFailure> for WpApiError {
type Error = AutoDiscoveryAttemptFailure;

fn try_from(value: AutoDiscoveryAttemptFailure) -> Result<Self, Self::Error> {
match value {
AutoDiscoveryAttemptFailure::FetchApiRootUrl {
parsed_site_url: _,
error,
} => Ok(error.into()),
AutoDiscoveryAttemptFailure::FetchApiDetails {
parsed_site_url: _,
api_root_url: _,
error,
} => Ok(error.into()),
_ => Err(value),
}
}
}
1 change: 1 addition & 0 deletions wp_api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub mod plugins;
pub mod post_types;
pub mod posts;
pub mod request;
pub mod request_executor;
pub mod search_results;
pub mod site_settings;
pub mod tags;
Expand Down
29 changes: 22 additions & 7 deletions wp_api/src/login/url_discovery.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use super::WpApiDetails;
use crate::{
login::KnownApplicationPasswordBlockingPlugin, request::WpNetworkHeaderMap,
request::WpRedirect, ParseUrlError, ParsedUrl, RequestExecutionError,
RequestExecutionErrorReason,
login::KnownApplicationPasswordBlockingPlugin,
request::{WpNetworkHeaderMap, WpRedirect},
ParseUrlError, ParsedUrl, RequestExecutionError, RequestExecutionErrorReason,
};
use scraper::{Html, Selector};
use serde::Deserialize;
Expand Down Expand Up @@ -109,6 +109,11 @@ impl AutoDiscoveryResult {
.expect("User input url is always attempted")
}

pub fn auto_discovery_attempt(&self) -> &AutoDiscoveryAttemptResult {
self.get_attempt(&AutoDiscoveryAttemptType::AutoHttps)
.expect("Auto discovery url is always attempted")
}

pub fn get_attempt(
&self,
attempt_type: &AutoDiscoveryAttemptType,
Expand Down Expand Up @@ -137,7 +142,7 @@ impl AutoDiscoveryAttemptResult {
self.attempt_site_url.clone()
}

fn error_message(&self) -> Option<String> {
pub fn error_message(&self) -> Option<String> {
match &self.api_discovery_result {
Ok(_) => None,
Err(error) => Some(error.to_string()),
Expand Down Expand Up @@ -220,6 +225,16 @@ impl AutoDiscoveryAttemptResult {
}
}

impl AutoDiscoveryAttemptResult {
pub fn error(&self) -> Option<AutoDiscoveryAttemptFailure> {
if let Err(error) = &self.api_discovery_result {
Some(error.clone())
} else {
None
}
}
}

// Does the given URL look like it's on a local development environment for the purposes of the Login Spec?
pub fn is_local_dev_environment_url(parsed_site_url: &ParsedUrl) -> bool {
if let Some(hostname) = parsed_site_url.inner.host_str() {
Expand Down Expand Up @@ -446,10 +461,10 @@ impl ApplicationPasswordsNotSupportedReason {
fn error_message(&self, parsed_site_url: impl Display) -> String {
match self {
Self::ApplicationPasswordBlockedByPlugin { plugin } => format!("Unable to login to {} – the {} plugin might have disabled Application Passwords. Please visit {} to learn more", parsed_site_url, plugin.name, plugin.support_url),
Self::ApplicationPasswordBlockedByMultiplePlugins => format!("Unable to login to {} – there are multiple installed plugins that might have disabled Application Passwords. Please disable them and try again.", parsed_site_url),
Self::ApplicationPasswordBlockedByMultiplePlugins => format!("Unable to login to {} – there are multiple installed plugins that might have disabled Application Passwords. Please disable them and try again.", parsed_site_url),
Self::SiteIsLocalDevelopmentEnvironment => "This site is a local development environment. You'll need to enable application passwords to connect to it with the app.".to_string(),
Self::ApplicationPasswordsDisabledForHttpSite => "Application Passwords is not enabled for this site – this is likely because we can't establish a secure connection to it. Please add an SSL certificate to this site and try again.".to_string(),
}
Self::ApplicationPasswordsDisabledForHttpSite => "Application Passwords is not enabled for this site – this is likely because we can't establish a secure connection to it. Please add an SSL certificate to this site and try again.".to_string(),
}
}
}

Expand Down
6 changes: 6 additions & 0 deletions wp_api/src/request/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ uniffi::custom_newtype!(WpEndpointUrl, String);
#[derive(Debug, Clone)]
pub struct WpEndpointUrl(pub String);

impl WpEndpointUrl {
pub fn url(&self) -> Url {
Url::parse(self.0.as_str()).expect("The request should be a valid URL")
}
}

impl From<Url> for WpEndpointUrl {
fn from(url: Url) -> Self {
Self(url.to_string())
Expand Down
129 changes: 129 additions & 0 deletions wp_api/src/request_executor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
use crate::api_error::{MediaUploadRequestExecutionError, RequestExecutionError};
use crate::request::endpoint::media_endpoint::MediaUploadRequest;
use crate::request::{
RequestExecutor, RequestMethod, WpNetworkHeaderMap, WpNetworkRequest, WpNetworkResponse,
};
use crate::RequestExecutionErrorReason;
use std::error::Error;
use std::sync::Arc;

#[derive(Debug, Default)]

pub struct WpRequestExecutor {}

#[async_trait::async_trait]
impl RequestExecutor for WpRequestExecutor {
async fn execute(
&self,
request: Arc<WpNetworkRequest>,
) -> Result<WpNetworkResponse, RequestExecutionError> {
let response = reqwest::Client::new()
.request(request.method().into(), request.url().url())
.headers(request.header_map().to_header_map())
.body(request.body_as_string().unwrap_or_default())
.send()
.await?;

// println!("Response: {:?}", response.extensions().len());
// println!("HTTP Info: {:?}", response.extensions().get::<HttpInfo>());

let status_code = response.status().into();
let header_map = Arc::new(response.headers().into());
let body = response.bytes().await?.to_vec();

Ok(WpNetworkResponse {
body,
status_code,
header_map,
})
}

async fn upload_media(
&self,
_media_upload_request: Arc<MediaUploadRequest>,
) -> Result<WpNetworkResponse, MediaUploadRequestExecutionError> {
todo!()
}
}

impl From<RequestMethod> for reqwest::Method {
fn from(method: RequestMethod) -> Self {
match method {
RequestMethod::GET => reqwest::Method::GET,
RequestMethod::POST => reqwest::Method::POST,
RequestMethod::PUT => reqwest::Method::PUT,
RequestMethod::DELETE => reqwest::Method::DELETE,
RequestMethod::HEAD => reqwest::Method::HEAD,
}
}
}

impl From<&http::HeaderMap> for WpNetworkHeaderMap {
fn from(header_map: &http::HeaderMap) -> Self {
WpNetworkHeaderMap::new(header_map.clone())
}
}

impl From<reqwest::Error> for RequestExecutionError {
fn from(error: reqwest::Error) -> Self {
// println!("Error: {:?}", error);
// println!("Error: {:?}", error.source());

if error.is_an_internal_connect_error() {
if let Some(error_kind) = error.get_connect_error_kind() {
match error_kind {
std::io::ErrorKind::ConnectionRefused => {
return RequestExecutionError::RequestExecutionFailed {
status_code: None,
redirects: None,
reason: RequestExecutionErrorReason::NonExistentSiteError {
error_message: Some("Connection refused".to_string()),
suggested_action: None,
},
};
}
_ => {}
}
}
}

RequestExecutionError::RequestExecutionFailed {
status_code: None,
redirects: None,
reason: RequestExecutionErrorReason::GenericError {
error_message: error.to_string(),
},
}
}
}

trait ExaminableError {
fn is_an_internal_connect_error(&self) -> bool;
fn get_connect_error_kind(&self) -> Option<std::io::ErrorKind>;
}

impl ExaminableError for reqwest::Error {
fn is_an_internal_connect_error(&self) -> bool {
self.source()
.expect("There should be a source")
.is::<hyper_util::client::legacy::Error>()
}

fn get_connect_error_kind(&self) -> Option<std::io::ErrorKind> {
if let Some(error) = self
.source()
.unwrap()
.downcast_ref::<hyper_util::client::legacy::Error>()
{
if let Some(source) = error.source() {
if let Some(os_error) = source.source() {
if let Some(io_error) = os_error.downcast_ref::<std::io::Error>() {
return Some(io_error.kind());
}
}
}
}

None
}
}
Loading