diff --git a/components/fxa-client/Cargo.toml b/components/fxa-client/Cargo.toml index b975ea452c..5f81a0c47d 100644 --- a/components/fxa-client/Cargo.toml +++ b/components/fxa-client/Cargo.toml @@ -1,8 +1,7 @@ [package] name = "fxa-client" -edition = "2021" +edition = "2024" version = "0.1.0" -authors = ["Edouard Oger "] license = "MPL-2.0" exclude = ["/android", "/ios"] diff --git a/components/fxa-client/src/device.rs b/components/fxa-client/src/device.rs index c4b95d3a8d..44852acc70 100644 --- a/components/fxa-client/src/device.rs +++ b/components/fxa-client/src/device.rs @@ -198,7 +198,7 @@ impl FirefoxAccount { #[derive(Clone, Debug, PartialEq, Eq)] pub struct DeviceConfig { pub name: String, - pub device_type: sync15::DeviceType, + pub device_type: DeviceType, pub capabilities: Vec, } @@ -207,7 +207,7 @@ pub struct DeviceConfig { pub struct LocalDevice { pub id: String, pub display_name: String, - pub device_type: sync15::DeviceType, + pub device_type: DeviceType, pub capabilities: Vec, pub push_subscription: Option, pub push_endpoint_expired: bool, @@ -222,7 +222,7 @@ pub struct LocalDevice { pub struct Device { pub id: String, pub display_name: String, - pub device_type: sync15::DeviceType, + pub device_type: DeviceType, pub capabilities: Vec, pub push_subscription: Option, pub push_endpoint_expired: bool, diff --git a/components/fxa-client/src/internal/close_tabs.rs b/components/fxa-client/src/internal/close_tabs.rs index d95de442fa..dd1ef9ae26 100644 --- a/components/fxa-client/src/internal/close_tabs.rs +++ b/components/fxa-client/src/internal/close_tabs.rs @@ -7,15 +7,17 @@ use std::mem; use payload_support::Fit; use super::{ + FirefoxAccount, commands::{ + IncomingDeviceCommand, PrivateCommandKeys, close_tabs::{self, CloseTabsPayload}, - decrypt_command, encrypt_command, IncomingDeviceCommand, PrivateCommandKeys, + decrypt_command, encrypt_command, }, device::COMMAND_MAX_PAYLOAD_SIZE, http_client::GetDeviceResponse, - scopes, telemetry, FirefoxAccount, + scopes, telemetry, }; -use crate::{warn, CloseTabsResult, Error, Result}; +use crate::{CloseTabsResult, Error, Result, warn}; impl FirefoxAccount { pub fn close_tabs(&mut self, target_device_id: &str, urls: Vec) -> Result @@ -119,7 +121,9 @@ impl FirefoxAccount { Ok(IncomingDeviceCommand::TabsClosed { sender, payload }) } Err(e) => { - warn!("Could not decrypt Close Remote Tabs payload. Diagnosing then resetting the Close Tabs keys."); + warn!( + "Could not decrypt Close Remote Tabs payload. Diagnosing then resetting the Close Tabs keys." + ); self.clear_close_tabs_keys(); self.reregister_current_capabilities()?; Err(e) @@ -168,11 +172,11 @@ mod tests { use serde_json::json; use crate::{ + ScopedKey, internal::{ - commands::PublicCommandKeys, config::Config, http_client::MockFxAClient, - oauth::RefreshToken, util, CachedResponse, FirefoxAccount, + CachedResponse, FirefoxAccount, commands::PublicCommandKeys, config::Config, + http_client::MockFxAClient, oauth::RefreshToken, util, }, - ScopedKey, }; /// An RAII helper that overrides the maximum command payload size diff --git a/components/fxa-client/src/internal/commands/keys.rs b/components/fxa-client/src/internal/commands/keys.rs index 1e3e4dfd0c..6800af703f 100644 --- a/components/fxa-client/src/internal/commands/keys.rs +++ b/components/fxa-client/src/internal/commands/keys.rs @@ -4,12 +4,12 @@ // All commands share the same structs for their crypto-keys. -use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; use super::super::device::Device; use super::super::scopes; use crate::{Error, Result, ScopedKey}; -use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use rc_crypto::ece::{self, EcKeyComponents}; use sync15::{EncryptedPayload, KeyBundle}; diff --git a/components/fxa-client/src/internal/commands/mod.rs b/components/fxa-client/src/internal/commands/mod.rs index 1a800acce6..7ff446ceaa 100644 --- a/components/fxa-client/src/internal/commands/mod.rs +++ b/components/fxa-client/src/internal/commands/mod.rs @@ -10,7 +10,7 @@ pub use close_tabs::CloseTabsPayload; pub use send_tab::SendTabPayload; pub(crate) use keys::{ - decrypt_command, encrypt_command, get_public_keys, PrivateCommandKeys, PublicCommandKeys, + PrivateCommandKeys, PublicCommandKeys, decrypt_command, encrypt_command, get_public_keys, }; use super::device::Device; diff --git a/components/fxa-client/src/internal/config.rs b/components/fxa-client/src/internal/config.rs index 25d3483a48..6ade8977c9 100644 --- a/components/fxa-client/src/internal/config.rs +++ b/components/fxa-client/src/internal/config.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use super::http_client; -use crate::{internal::util, FxaConfig, Result}; +use crate::{FxaConfig, Result, internal::util}; use serde_derive::{Deserialize, Serialize}; use std::{cell::RefCell, sync::Arc}; use url::Url; diff --git a/components/fxa-client/src/internal/device.rs b/components/fxa-client/src/internal/device.rs index 48552e95f7..5776b42f4b 100644 --- a/components/fxa-client/src/internal/device.rs +++ b/components/fxa-client/src/internal/device.rs @@ -9,13 +9,14 @@ use std::{ pub use super::http_client::{GetDeviceResponse as Device, PushSubscription}; use super::{ + CachedResponse, FirefoxAccount, commands::{self, IncomingDeviceCommand, PrivateCommandKeys, PublicCommandKeys}, http_client::{ DeviceUpdateRequest, DeviceUpdateRequestBuilder, PendingCommand, UpdateDeviceResponse, }, - scopes, telemetry, util, CachedResponse, FirefoxAccount, + scopes, telemetry, util, }; -use crate::{info, warn, DeviceCapability, Error, LocalDevice, Result}; +use crate::{DeviceCapability, Error, LocalDevice, Result, info, warn}; use sync15::DeviceType; // An devices response is considered fresh for `DEVICES_FRESHNESS_THRESHOLD` ms. @@ -434,10 +435,10 @@ impl TryFrom for crate::Device { #[cfg(test)] mod tests { use super::*; + use crate::ScopedKey; + use crate::internal::Config; use crate::internal::http_client::*; use crate::internal::oauth::RefreshToken; - use crate::internal::Config; - use crate::ScopedKey; use mockall::predicate::always; use mockall::predicate::eq; use nss::ensure_initialized; diff --git a/components/fxa-client/src/internal/http_client.rs b/components/fxa-client/src/internal/http_client.rs index 069ded7503..86c9a50774 100644 --- a/components/fxa-client/src/internal/http_client.rs +++ b/components/fxa-client/src/internal/http_client.rs @@ -26,7 +26,7 @@ use std::{ }; use sync15::DeviceType; use url::Url; -use viaduct::{header_names, status_codes, Method, Request, Response}; +use viaduct::{Method, Request, Response, header_names, status_codes}; const HAWK_HKDF_SALT: [u8; 32] = [0b0; 32]; const HAWK_KEY_LENGTH: usize = 32; @@ -987,14 +987,20 @@ mod tests { code_verifier: "bobo".to_owned(), ttl: None, }; - assert_eq!("{\"grant_type\":\"authorization_code\",\"client_id\":\"bar\",\"code\":\"foo\",\"code_verifier\":\"bobo\"}", serde_json::to_string(&using_code).unwrap()); + assert_eq!( + "{\"grant_type\":\"authorization_code\",\"client_id\":\"bar\",\"code\":\"foo\",\"code_verifier\":\"bobo\"}", + serde_json::to_string(&using_code).unwrap() + ); let using_code = OAauthTokenRequest::UsingRefreshToken { client_id: "bar".to_owned(), refresh_token: "foo".to_owned(), scope: Some("bobo".to_owned()), ttl: Some(123), }; - assert_eq!("{\"grant_type\":\"refresh_token\",\"client_id\":\"bar\",\"refresh_token\":\"foo\",\"scope\":\"bobo\",\"ttl\":123}", serde_json::to_string(&using_code).unwrap()); + assert_eq!( + "{\"grant_type\":\"refresh_token\",\"client_id\":\"bar\",\"refresh_token\":\"foo\",\"scope\":\"bobo\",\"ttl\":123}", + serde_json::to_string(&using_code).unwrap() + ); } #[test] diff --git a/components/fxa-client/src/internal/mod.rs b/components/fxa-client/src/internal/mod.rs index e8e42160fc..d8bd88763a 100644 --- a/components/fxa-client/src/internal/mod.rs +++ b/components/fxa-client/src/internal/mod.rs @@ -6,7 +6,7 @@ use self::{ config::Config, - oauth::{AuthCircuitBreaker, OAuthFlow, OAUTH_WEBCHANNEL_REDIRECT}, + oauth::{AuthCircuitBreaker, OAUTH_WEBCHANNEL_REDIRECT, OAuthFlow}, state_manager::StateManager, state_persistence::PersistedState, telemetry::FxaTelemetry, diff --git a/components/fxa-client/src/internal/oauth.rs b/components/fxa-client/src/internal/oauth.rs index 2853a5fce9..f6f1392de6 100644 --- a/components/fxa-client/src/internal/oauth.rs +++ b/components/fxa-client/src/internal/oauth.rs @@ -5,15 +5,16 @@ pub mod attached_clients; use super::scopes; use super::{ + FirefoxAccount, http_client::{ AuthorizationRequestParameters, IntrospectResponse as IntrospectInfo, OAuthTokenResponse, }, scoped_keys::ScopedKeysFlow, - util, FirefoxAccount, + util, }; use crate::auth::UserData; -use crate::{warn, AuthorizationParameters, Error, FxaServer, Result, ScopedKey}; -use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use crate::{AuthorizationParameters, Error, FxaServer, Result, ScopedKey, warn}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use jwcrypto::{EncryptionAlgorithm, EncryptionParameters}; use rate_limiter::RateLimiter; use rc_crypto::digest; @@ -350,7 +351,11 @@ impl FirefoxAccount { "fxaclient-scoped-key", "Sync scope granted, but no sync scoped key (scope granted: {}, key scopes: {})", resp.scope, - scoped_keys.keys().map(|s| s.as_ref()).collect::>().join(", ") + scoped_keys + .keys() + .map(|s| s.as_ref()) + .collect::>() + .join(", ") ); } scoped_keys @@ -591,7 +596,7 @@ impl From for crate::AuthorizationInfo { #[cfg(test)] mod tests { - use super::super::{http_client::*, Config}; + use super::super::{Config, http_client::*}; use super::*; use mockall::predicate::always; use mockall::predicate::eq; @@ -965,7 +970,9 @@ mod tests { assert_eq!(code, 400); assert_eq!(errno, 163); // Requested scopes not allowed } else { - panic!("Should return an error from the server specifying that the requested scopes are not allowed"); + panic!( + "Should return an error from the server specifying that the requested scopes are not allowed" + ); } } diff --git a/components/fxa-client/src/internal/oauth/attached_clients.rs b/components/fxa-client/src/internal/oauth/attached_clients.rs index ee408cf2e9..6ec2071aae 100644 --- a/components/fxa-client/src/internal/oauth/attached_clients.rs +++ b/components/fxa-client/src/internal/oauth/attached_clients.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub use super::super::http_client::GetAttachedClientResponse as AttachedClient; -use super::super::{util, CachedResponse, FirefoxAccount}; +use super::super::{CachedResponse, FirefoxAccount, util}; use crate::{Error, Result}; // An attached clients response is considered fresh for `ATTACHED_CLIENTS_FRESHNESS_THRESHOLD` ms. diff --git a/components/fxa-client/src/internal/profile.rs b/components/fxa-client/src/internal/profile.rs index 80a84ea153..315517bad7 100644 --- a/components/fxa-client/src/internal/profile.rs +++ b/components/fxa-client/src/internal/profile.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub use super::http_client::ProfileResponse as Profile; -use super::{scopes, util, CachedResponse, FirefoxAccount}; +use super::{CachedResponse, FirefoxAccount, scopes, util}; use crate::{Error, Result}; // A cached profile response is considered fresh for `PROFILE_FRESHNESS_THRESHOLD` ms. @@ -86,9 +86,9 @@ impl FirefoxAccount { mod tests { use super::*; use crate::internal::{ + Config, http_client::*, oauth::{AccessTokenInfo, RefreshToken}, - Config, }; use mockall::predicate::always; use mockall::predicate::eq; diff --git a/components/fxa-client/src/internal/push.rs b/components/fxa-client/src/internal/push.rs index 14f2352fe2..19b4935455 100644 --- a/components/fxa-client/src/internal/push.rs +++ b/components/fxa-client/src/internal/push.rs @@ -5,7 +5,7 @@ use std::convert::TryInto; use super::FirefoxAccount; -use crate::{info, AccountEvent, Error, Result}; +use crate::{AccountEvent, Error, Result, info}; use serde_derive::Deserialize; impl FirefoxAccount { @@ -138,11 +138,11 @@ pub struct AccountDestroyedPushPayload { #[cfg(test)] mod tests { use super::*; + use crate::internal::CachedResponse; + use crate::internal::Config; use crate::internal::http_client::IntrospectResponse; use crate::internal::http_client::MockFxAClient; use crate::internal::oauth::RefreshToken; - use crate::internal::CachedResponse; - use crate::internal::Config; use mockall::predicate::always; use mockall::predicate::eq; use std::sync::Arc; diff --git a/components/fxa-client/src/internal/scoped_keys.rs b/components/fxa-client/src/internal/scoped_keys.rs index 076535ae70..794390adc3 100644 --- a/components/fxa-client/src/internal/scoped_keys.rs +++ b/components/fxa-client/src/internal/scoped_keys.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use jwcrypto::{self, DecryptionParameters, Jwk}; use rc_crypto::{agreement, agreement::EphemeralKeyPair}; @@ -103,6 +103,9 @@ mod tests { let jwe = "eyJhbGciOiJFQ0RILUVTIiwia2lkIjoiNFBKTTl5dGVGeUtsb21ILWd2UUtyWGZ0a0N3ak9HNHRfTmpYVXhLM1VqSSIsImVwayI6eyJrdHkiOiJFQyIsImNydiI6IlAtMjU2IiwieCI6IlB3eG9Na1RjSVZ2TFlKWU4wM2R0Y3o2TEJrR0FHaU1hZWlNQ3lTZXEzb2MiLCJ5IjoiLUYtTllRRDZwNUdSQ2ZoYm1hN3NvNkhxdExhVlNub012S0pFcjFBeWlaSSJ9LCJlbmMiOiJBMjU2R0NNIn0..b9FPhjjpmAmo_rP8.ur9jTry21Y2trvtcanSFmAtiRfF6s6qqyg6ruRal7PCwa7PxDzAuMN6DZW5BiK8UREOH08-FyRcIgdDOm5Zq8KwVAn56PGfcH30aNDGQNkA_mpfjx5Tj2z8kI6ryLWew4PGZb-PsL1g-_eyXhktq7dAhetjNYttKwSREWQFokv7N3nJGpukBqnwL1ost-MjDXlINZLVJKAiMHDcu-q7Epitwid2c2JVGOSCJjbZ4-zbxVmZ4o9xhFb2lbvdiaMygH6bPlrjEK99uT6XKtaIZmyDwftbD6G3x4On-CqA2TNL6ILRaJMtmyX--ctL0IrngUIHg_F0Wz94v.zBD8NACkUcZTPLH0tceGnA"; let keys = flow.decrypt_keys_jwe(jwe).unwrap(); - assert_eq!(keys, "{\"https://identity.mozilla.com/apps/oldsync\":{\"kty\":\"oct\",\"scope\":\"https://identity.mozilla.com/apps/oldsync\",\"k\":\"8ek1VNk4sjrNP0DhGC4crzQtwmpoR64zHuFMHb4Tw-exR70Z2SSIfMSrJDTLEZid9lD05-hbA3n2Q4Esjlu1tA\",\"kid\":\"1526414944666-zgTjf5oXmPmBjxwXWFsDWg\"}}"); + assert_eq!( + keys, + "{\"https://identity.mozilla.com/apps/oldsync\":{\"kty\":\"oct\",\"scope\":\"https://identity.mozilla.com/apps/oldsync\",\"k\":\"8ek1VNk4sjrNP0DhGC4crzQtwmpoR64zHuFMHb4Tw-exR70Z2SSIfMSrJDTLEZid9lD05-hbA3n2Q4Esjlu1tA\",\"kid\":\"1526414944666-zgTjf5oXmPmBjxwXWFsDWg\"}}" + ); } } diff --git a/components/fxa-client/src/internal/send_tab.rs b/components/fxa-client/src/internal/send_tab.rs index 3267843fbb..063856d852 100644 --- a/components/fxa-client/src/internal/send_tab.rs +++ b/components/fxa-client/src/internal/send_tab.rs @@ -3,14 +3,14 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use super::{ + FirefoxAccount, commands::{ - decrypt_command, encrypt_command, get_public_keys, - send_tab::{self, SendTabPayload}, IncomingDeviceCommand, PrivateCommandKeys as PrivateSendTabKeys, - PublicCommandKeys as PublicSendTabKeys, + PublicCommandKeys as PublicSendTabKeys, decrypt_command, encrypt_command, get_public_keys, + send_tab::{self, SendTabPayload}, }, http_client::GetDeviceResponse, - scopes, telemetry, FirefoxAccount, + scopes, telemetry, }; use crate::{Error, Result}; @@ -85,7 +85,9 @@ impl FirefoxAccount { // It also seems like it might be possible to recover - ie, one // of the reasons is that there are key mismatches. Doesn't that // mean the "other" key might work? - crate::warn!("Could not decrypt Send Tab payload. Diagnosing then resetting the Send Tab keys."); + crate::warn!( + "Could not decrypt Send Tab payload. Diagnosing then resetting the Send Tab keys." + ); match self.diagnose_remote_keys(send_tab_key) { Ok(_) => { error_support::report_error!( diff --git a/components/fxa-client/src/internal/state_manager.rs b/components/fxa-client/src/internal/state_manager.rs index d42a0656ee..c820450ea1 100644 --- a/components/fxa-client/src/internal/state_manager.rs +++ b/components/fxa-client/src/internal/state_manager.rs @@ -5,13 +5,13 @@ use std::collections::{HashMap, HashSet}; use crate::{ + DeviceCapability, FxaRustAuthState, LocalDevice, Result, ScopedKey, internal::{ + CachedResponse, Config, OAuthFlow, PersistedState, oauth::{AccessTokenInfo, RefreshToken}, profile::Profile, state_persistence::state_to_json, - CachedResponse, Config, OAuthFlow, PersistedState, }, - DeviceCapability, FxaRustAuthState, LocalDevice, Result, ScopedKey, }; /// Stores and manages the current state of the FxA client diff --git a/components/fxa-client/src/internal/state_persistence.rs b/components/fxa-client/src/internal/state_persistence.rs index 8f37087764..adffd798b0 100644 --- a/components/fxa-client/src/internal/state_persistence.rs +++ b/components/fxa-client/src/internal/state_persistence.rs @@ -33,10 +33,10 @@ use serde_derive::*; use std::collections::{HashMap, HashSet}; use super::{ + CachedResponse, Result, config::Config, oauth::{AccessTokenInfo, RefreshToken}, profile::Profile, - CachedResponse, Result, }; use crate::{DeviceCapability, LocalDevice, ScopedKey}; diff --git a/components/fxa-client/src/internal/telemetry.rs b/components/fxa-client/src/internal/telemetry.rs index 00b7463f89..a9bbffa071 100644 --- a/components/fxa-client/src/internal/telemetry.rs +++ b/components/fxa-client/src/internal/telemetry.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::{commands, FirefoxAccount}; +use super::{FirefoxAccount, commands}; use crate::Result; use serde_derive::*; use sync_guid::Guid; diff --git a/components/fxa-client/src/internal/util.rs b/components/fxa-client/src/internal/util.rs index 4370ec8a22..c671cbdb82 100644 --- a/components/fxa-client/src/internal/util.rs +++ b/components/fxa-client/src/internal/util.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::{Error, Result}; -use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use rc_crypto::rand; use std::time::{SystemTime, UNIX_EPOCH}; diff --git a/components/fxa-client/src/push.rs b/components/fxa-client/src/push.rs index 2570d2765f..a216d3edc3 100644 --- a/components/fxa-client/src/push.rs +++ b/components/fxa-client/src/push.rs @@ -5,7 +5,7 @@ use error_support::handle_error; use serde::{Deserialize, Serialize}; -use crate::{internal, ApiResult, CloseTabsResult, Device, Error, FirefoxAccount, LocalDevice}; +use crate::{ApiResult, CloseTabsResult, Device, Error, FirefoxAccount, LocalDevice, internal}; impl FirefoxAccount { /// Set or update a push subscription endpoint for this device. diff --git a/components/fxa-client/src/state_machine/display.rs b/components/fxa-client/src/state_machine/display.rs index 99e090016a..301b7eb630 100644 --- a/components/fxa-client/src/state_machine/display.rs +++ b/components/fxa-client/src/state_machine/display.rs @@ -10,7 +10,7 @@ //! Also, they must not use the string "auth" since Sentry will filter that out. //! Use "ath" instead. -use super::{internal_machines, FxaEvent, FxaState}; +use super::{FxaEvent, FxaState, internal_machines}; use std::fmt; impl fmt::Display for FxaState { diff --git a/components/fxa-client/src/state_machine/internal_machines/auth_issues.rs b/components/fxa-client/src/state_machine/internal_machines/auth_issues.rs index 98e2e210a9..bac189cf8e 100644 --- a/components/fxa-client/src/state_machine/internal_machines/auth_issues.rs +++ b/components/fxa-client/src/state_machine/internal_machines/auth_issues.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::{invalid_transition, Event, InternalStateMachine, State}; +use super::{Event, InternalStateMachine, State, invalid_transition}; use crate::{Error, FxaEvent, FxaState, Result}; use error_support::report_error; diff --git a/components/fxa-client/src/state_machine/internal_machines/authenticating.rs b/components/fxa-client/src/state_machine/internal_machines/authenticating.rs index 0b69c31ad1..25ae6e490d 100644 --- a/components/fxa-client/src/state_machine/internal_machines/authenticating.rs +++ b/components/fxa-client/src/state_machine/internal_machines/authenticating.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::{invalid_transition, Event, InternalStateMachine, State}; +use super::{Event, InternalStateMachine, State, invalid_transition}; use crate::{Error, FxaEvent, FxaState, Result}; pub struct AuthenticatingStateMachine; diff --git a/components/fxa-client/src/state_machine/internal_machines/connected.rs b/components/fxa-client/src/state_machine/internal_machines/connected.rs index d635d02f2e..69bd07cf12 100644 --- a/components/fxa-client/src/state_machine/internal_machines/connected.rs +++ b/components/fxa-client/src/state_machine/internal_machines/connected.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::{invalid_transition, Event, InternalStateMachine, State}; +use super::{Event, InternalStateMachine, State, invalid_transition}; use crate::{Error, FxaEvent, FxaState, Result}; use error_support::report_error; diff --git a/components/fxa-client/src/state_machine/internal_machines/disconnected.rs b/components/fxa-client/src/state_machine/internal_machines/disconnected.rs index 9d99f1686c..f673349b7b 100644 --- a/components/fxa-client/src/state_machine/internal_machines/disconnected.rs +++ b/components/fxa-client/src/state_machine/internal_machines/disconnected.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::{invalid_transition, Event, InternalStateMachine, State}; +use super::{Event, InternalStateMachine, State, invalid_transition}; use crate::{Error, FxaEvent, FxaState, Result}; pub struct DisconnectedStateMachine; diff --git a/components/fxa-client/src/state_machine/internal_machines/mod.rs b/components/fxa-client/src/state_machine/internal_machines/mod.rs index f7d200653f..efb3ed84e8 100644 --- a/components/fxa-client/src/state_machine/internal_machines/mod.rs +++ b/components/fxa-client/src/state_machine/internal_machines/mod.rs @@ -11,8 +11,8 @@ mod disconnected; mod uninitialized; use crate::{ - internal::FirefoxAccount, DeviceConfig, Error, FxaError, FxaEvent, FxaRustAuthState, FxaState, - Result, + DeviceConfig, Error, FxaError, FxaEvent, FxaRustAuthState, FxaState, Result, + internal::FirefoxAccount, }; pub use auth_issues::AuthIssuesStateMachine; pub use authenticating::AuthenticatingStateMachine; @@ -167,7 +167,7 @@ impl State { state => { return Err(Error::StateMachineLogicError(format!( "process_call: Don't know how to handle {state}" - ))) + ))); } }) } diff --git a/components/fxa-client/src/state_machine/internal_machines/uninitialized.rs b/components/fxa-client/src/state_machine/internal_machines/uninitialized.rs index ff1f55a2e1..74dc451197 100644 --- a/components/fxa-client/src/state_machine/internal_machines/uninitialized.rs +++ b/components/fxa-client/src/state_machine/internal_machines/uninitialized.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::{invalid_transition, Event, InternalStateMachine, State}; +use super::{Event, InternalStateMachine, State, invalid_transition}; use crate::{Error, FxaEvent, FxaRustAuthState, FxaState, Result}; pub struct UninitializedStateMachine; diff --git a/components/fxa-client/src/state_machine/mod.rs b/components/fxa-client/src/state_machine/mod.rs index 231118c4db..97c3414b85 100644 --- a/components/fxa-client/src/state_machine/mod.rs +++ b/components/fxa-client/src/state_machine/mod.rs @@ -8,7 +8,7 @@ use error_support::breadcrumb; -use crate::{internal::FirefoxAccount, DeviceConfig, Error, FxaEvent, FxaState, Result}; +use crate::{DeviceConfig, Error, FxaEvent, FxaState, Result, internal::FirefoxAccount}; mod display; mod internal_machines; diff --git a/components/fxa-client/src/storage.rs b/components/fxa-client/src/storage.rs index eef9249550..23dd772a63 100644 --- a/components/fxa-client/src/storage.rs +++ b/components/fxa-client/src/storage.rs @@ -17,7 +17,7 @@ //! the modified account state and persist the resulting string in application //! settings. -use crate::{internal, ApiResult, Error, FirefoxAccount}; +use crate::{ApiResult, Error, FirefoxAccount, internal}; use error_support::handle_error; use parking_lot::Mutex; diff --git a/components/logins/Cargo.toml b/components/logins/Cargo.toml index 56f87886bf..31005e041b 100644 --- a/components/logins/Cargo.toml +++ b/components/logins/Cargo.toml @@ -1,8 +1,7 @@ [package] name = "logins" -edition = "2021" +edition = "2024" version = "0.1.0" -authors = ["Thom Chiovoloni "] license = "MPL-2.0" exclude = ["/android", "/ios"] @@ -11,9 +10,7 @@ default = [] keydb = ["nss/keydb", "dep:async-trait", "dep:futures"] [dependencies] -# TODO: we've enabled the "standalone-sync" feature - see the description -# of this feature in sync15's Cargo.toml for what we should do instead. -sync15 = { path = "../sync15", features=["standalone-sync"] } +sync15 = { path = "../sync15", features = ["sync-client"] } serde = "1" serde_derive = "1" serde_json = "1" diff --git a/components/logins/src/db.rs b/components/logins/src/db.rs index 1d0fade2e7..6d51dcdd3f 100644 --- a/components/logins/src/db.rs +++ b/components/logins/src/db.rs @@ -31,9 +31,8 @@ use crate::util; use interrupt_support::{SqlInterruptHandle, SqlInterruptScope}; use lazy_static::lazy_static; use rusqlite::{ - named_params, + Connection, named_params, types::{FromSql, ToSql}, - Connection, }; use sql_support::ConnExt; use std::ops::Deref; @@ -516,7 +515,8 @@ impl LoginDb { let has_form_action_origin = entry.form_action_origin.is_some(); report_error!( "logins-duplicate-in-update", - "(mirror: {has_mirror_row}, realm: {has_http_realm}, form_origin: {has_form_action_origin})"); + "(mirror: {has_mirror_row}, realm: {has_http_realm}, form_origin: {has_form_action_origin})" + ); } // Note: This fail with NoSuchRecord if the record doesn't exist. @@ -936,9 +936,9 @@ lazy_static! { #[cfg(test)] pub mod test_utils { use super::*; + use crate::SecureLoginFields; use crate::encryption::test_utils::decrypt_struct; use crate::login::test_utils::enc_login; - use crate::SecureLoginFields; use sync15::ServerTimestamp; // Insert a login into the local and/or mirror tables. @@ -1861,8 +1861,8 @@ mod tests { fn test_invalid_login() { ensure_initialized(); let db = LoginDb::open_in_memory(); - assert!(db - .find_login_to_update( + assert!( + db.find_login_to_update( LoginEntry { http_realm: None, form_action_origin: None, @@ -1870,7 +1870,8 @@ mod tests { }, &*TEST_ENCDEC ) - .is_err()); + .is_err() + ); } #[test] diff --git a/components/logins/src/encryption.rs b/components/logins/src/encryption.rs index a3b99cc995..743b2e9ccb 100644 --- a/components/logins/src/encryption.rs +++ b/components/logins/src/encryption.rs @@ -338,7 +338,7 @@ pub fn create_key() -> ApiResult { #[cfg(test)] pub mod test_utils { use super::*; - use serde::{de::DeserializeOwned, Serialize}; + use serde::{Serialize, de::DeserializeOwned}; lazy_static::lazy_static! { pub static ref TEST_ENCRYPTION_KEY: String = serde_json::to_string(&jwcrypto::Jwk::new_direct_key(Some("test-key".to_string())).unwrap()).unwrap(); diff --git a/components/logins/src/login.rs b/components/logins/src/login.rs index 812b4d55ac..c03ecc7120 100644 --- a/components/logins/src/login.rs +++ b/components/logins/src/login.rs @@ -1064,8 +1064,7 @@ mod tests { TestCase { login: login_without_form_submit_or_http_realm, should_err: true, - expected_err: - "Invalid login: Neither `formActionOrigin` or `httpRealm` are present", + expected_err: "Invalid login: Neither `formActionOrigin` or `httpRealm` are present", }, TestCase { login: login_with_null_http_realm, @@ -1090,14 +1089,12 @@ mod tests { TestCase { login: login_with_newline_realm, should_err: true, - expected_err: - "Invalid login: Login has illegal field: `http_realm` contains newline", + expected_err: "Invalid login: Login has illegal field: `http_realm` contains newline", }, TestCase { login: login_with_newline_username_field, should_err: true, - expected_err: - "Invalid login: Login has illegal field: `username_field` contains newline", + expected_err: "Invalid login: Login has illegal field: `username_field` contains newline", }, TestCase { login: login_with_newline_password, @@ -1107,8 +1104,7 @@ mod tests { TestCase { login: login_with_period_username_field, should_err: true, - expected_err: - "Invalid login: Login has illegal field: `username_field` is a period", + expected_err: "Invalid login: Login has illegal field: `username_field` is a period", }, TestCase { login: login_with_period_form_action_origin, diff --git a/components/logins/src/schema.rs b/components/logins/src/schema.rs index 38aa7f277a..9f7c9a2b8d 100644 --- a/components/logins/src/schema.rs +++ b/components/logins/src/schema.rs @@ -256,8 +256,8 @@ pub(crate) fn create(db: &Connection) -> Result<()> { #[cfg(test)] mod tests { use super::*; - use crate::encryption::test_utils::TEST_ENCDEC; use crate::LoginDb; + use crate::encryption::test_utils::TEST_ENCDEC; use nss::ensure_initialized; use rusqlite::Connection; diff --git a/components/logins/src/store.rs b/components/logins/src/store.rs index 7f707df9cc..6dbe13bd21 100644 --- a/components/logins/src/store.rs +++ b/components/logins/src/store.rs @@ -1,19 +1,19 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use crate::LoginsSyncEngine; use crate::db::{LoginDb, LoginsDeletionMetrics}; use crate::encryption::EncryptorDecryptor; use crate::error::*; use crate::login::{BulkResultEntry, EncryptedLogin, Login, LoginEntry, LoginEntryWithMeta}; use crate::schema; -use crate::LoginsSyncEngine; use parking_lot::Mutex; use sql_support::run_maintenance; use std::path::Path; use std::sync::{Arc, Weak}; use sync15::{ - engine::{EngineSyncAssociation, SyncEngine, SyncEngineId}, ServerTimestamp, + engine::{EngineSyncAssociation, SyncEngine, SyncEngineId}, }; #[derive(uniffi::Enum)] @@ -65,7 +65,9 @@ fn map_bulk_result_entry( Ok(enc_login) => match enc_login.decrypt(encdec) { Ok(login) => BulkResultEntry::Success { login }, Err(error) => { - warn!("Login could not be decrypted. This indicates a fundamental problem with the encryption key."); + warn!( + "Login could not be decrypted. This indicates a fundamental problem with the encryption key." + ); BulkResultEntry::Error { message: error.to_string(), } @@ -409,10 +411,12 @@ mod test { assert_eq!(list, expect); store.delete(&a_id).expect("Successful delete"); - assert!(store - .get(&a_id) - .expect("get after delete should still work") - .is_none()); + assert!( + store + .get(&a_id) + .expect("get after delete should still work") + .is_none() + ); let list = store.list().expect("Grabbing list to work"); assert_eq!(list.len(), 1); diff --git a/components/logins/src/sync/engine.rs b/components/logins/src/sync/engine.rs index 69d8bd2ae4..9b6114bd18 100644 --- a/components/logins/src/sync/engine.rs +++ b/components/logins/src/sync/engine.rs @@ -2,17 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use super::SyncStatus; use super::merge::{LocalLogin, MirrorLogin, SyncLoginData}; use super::update_plan::UpdatePlan; -use super::SyncStatus; +use crate::LoginDb; +use crate::LoginStore; use crate::db::CLONE_ENTIRE_MIRROR_SQL; use crate::encryption::EncryptorDecryptor; use crate::error::*; use crate::login::EncryptedLogin; use crate::schema; use crate::util; -use crate::LoginDb; -use crate::LoginStore; use interrupt_support::SqlInterruptScope; use rusqlite::named_params; use sql_support::ConnExt; @@ -20,10 +20,10 @@ use std::cell::RefCell; use std::collections::HashSet; use std::sync::Arc; use std::time::{Duration, UNIX_EPOCH}; +use sync_guid::Guid; use sync15::bso::{IncomingBso, OutgoingBso, OutgoingEnvelope}; use sync15::engine::{CollSyncIds, CollectionRequest, EngineSyncAssociation, SyncEngine}; -use sync15::{telemetry, ServerTimestamp}; -use sync_guid::Guid; +use sync15::{ServerTimestamp, telemetry}; // The sync engine. pub struct LoginsSyncEngine { @@ -299,7 +299,7 @@ impl LoginsSyncEngine { pub fn set_global_state(&self, state: &Option) -> Result<()> { let to_write = match state { - Some(ref s) => s, + Some(s) => s, None => "", }; let db = self.store.lock_db()?; @@ -942,10 +942,12 @@ mod tests { Some("https://something-else.com".into()), None, ); - assert!(engine - .find_dupe_login(&to_find) - .expect("should work") - .is_none()); + assert!( + engine + .find_dupe_login(&to_find) + .expect("should work") + .is_none() + ); let to_find = make_enc_login( "test1", @@ -969,10 +971,12 @@ mod tests { Some("https://www.example1.com".into()), None, ); - assert!(engine - .find_dupe_login(&to_find) - .expect("should work") - .is_none()); + assert!( + engine + .find_dupe_login(&to_find) + .expect("should work") + .is_none() + ); // no form origin. let to_find = make_enc_login("test1", "test1", None, Some("http://some-realm.com".into())); @@ -1126,19 +1130,23 @@ mod tests { // Reset the engine - this wipes the mirror. engine.reset(&EngineSyncAssociation::Disconnected).unwrap(); // But the local record does still exist. - assert!(engine - .store - .get("dummy_000001") - .expect("should work") - .is_some()); + assert!( + engine + .store + .get("dummy_000001") + .expect("should work") + .is_some() + ); // Delete the local record. engine.store.delete("dummy_000001").unwrap(); - assert!(engine - .store - .get("dummy_000001") - .expect("should work") - .is_none()); + assert!( + engine + .store + .get("dummy_000001") + .expect("should work") + .is_none() + ); // double-check our test preconditions - should now have 1 in LoginsL and 0 in LoginsM assert_eq!(count(&engine, "LoginsL"), 1); @@ -1161,11 +1169,13 @@ mod tests { // Desktop semantics here are that a local tombstone is treated as though it doesn't exist at all. // ie, the remote record should be taken whether it is newer or older than the tombstone. - assert!(engine - .store - .get("dummy_000001") - .expect("should work") - .is_some()); + assert!( + engine + .store + .get("dummy_000001") + .expect("should work") + .is_some() + ); // and there should never be an outgoing record. // XXX - but there is! But this is exceedingly rare, we // should fix it :) diff --git a/components/logins/src/sync/merge.rs b/components/logins/src/sync/merge.rs index 2786d64e7f..a269fd8b63 100644 --- a/components/logins/src/sync/merge.rs +++ b/components/logins/src/sync/merge.rs @@ -10,9 +10,9 @@ use crate::login::EncryptedLogin; use crate::util; use rusqlite::Row; use std::time::SystemTime; -use sync15::bso::{IncomingBso, IncomingKind}; -use sync15::ServerTimestamp; use sync_guid::Guid; +use sync15::ServerTimestamp; +use sync15::bso::{IncomingBso, IncomingKind}; #[derive(Clone, Debug)] pub(crate) struct MirrorLogin { diff --git a/components/logins/src/sync/payload.rs b/components/logins/src/sync/payload.rs index a10a634b94..a8f30413f6 100644 --- a/components/logins/src/sync/payload.rs +++ b/components/logins/src/sync/payload.rs @@ -7,14 +7,14 @@ // This struct is used for fetching/sending login records to the server. There are a number // of differences between this and the top-level Login struct; some fields are renamed, some are // locally encrypted, etc. +use crate::SecureLoginFields; use crate::encryption::EncryptorDecryptor; use crate::error::*; use crate::login::ValidateAndFixup; -use crate::SecureLoginFields; use crate::{EncryptedLogin, LoginEntry, LoginFields, LoginMeta}; use serde_derive::*; -use sync15::bso::OutgoingBso; use sync_guid::Guid; +use sync15::bso::OutgoingBso; type UnknownFields = serde_json::Map; @@ -221,7 +221,7 @@ where #[cfg(test)] mod tests { use super::*; - use crate::encryption::test_utils::{encrypt_struct, TEST_ENCDEC}; + use crate::encryption::test_utils::{TEST_ENCDEC, encrypt_struct}; use crate::sync::merge::SyncLoginData; use crate::{EncryptedLogin, LoginFields, LoginMeta, SecureLoginFields}; use sync15::bso::IncomingBso; diff --git a/components/logins/src/sync/update_plan.rs b/components/logins/src/sync/update_plan.rs index 122a2f7d40..83bc364de4 100644 --- a/components/logins/src/sync/update_plan.rs +++ b/components/logins/src/sync/update_plan.rs @@ -8,10 +8,10 @@ use crate::encryption::EncryptorDecryptor; use crate::error::*; use crate::util; use interrupt_support::SqlInterruptScope; -use rusqlite::{named_params, Connection}; +use rusqlite::{Connection, named_params}; use std::time::SystemTime; -use sync15::ServerTimestamp; use sync_guid::Guid; +use sync15::ServerTimestamp; #[derive(Default, Debug)] pub(super) struct UpdatePlan { @@ -320,11 +320,11 @@ mod tests { use std::time::Duration; use super::*; + use crate::db::LoginDb; use crate::db::test_utils::{ check_local_login, check_mirror_login, get_local_guids, get_mirror_guids, get_server_modified, insert_encrypted_login, insert_login, }; - use crate::db::LoginDb; use crate::encryption::test_utils::TEST_ENCDEC; use crate::login::test_utils::enc_login; diff --git a/components/places/Cargo.toml b/components/places/Cargo.toml index f891c03175..80d43a7602 100644 --- a/components/places/Cargo.toml +++ b/components/places/Cargo.toml @@ -1,8 +1,7 @@ [package] name = "places" -edition = "2021" +edition = "2024" version = "0.1.0" -authors = ["Sync Team "] license = "MPL-2.0" exclude = ["/android", "/ios"] @@ -10,9 +9,7 @@ exclude = ["/android", "/ios"] default = [] [dependencies] -# TODO: we've enabled the "standalone-sync" feature - see the description -# of this feature in sync15's Cargo.toml for what we should do instead. -sync15 = { path = "../sync15", features=["standalone-sync"] } +sync15 = { path = "../sync15", features = ["sync-client"] } serde = "1" serde_derive = "1" serde_json = "1" diff --git a/components/places/src/api/matcher.rs b/components/places/src/api/matcher.rs index 0a5206c72c..480eb34f1b 100644 --- a/components/places/src/api/matcher.rs +++ b/components/places/src/api/matcher.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::db::PlacesDb; -use crate::error::{warn, Result}; +use crate::error::{Result, warn}; use crate::ffi::SearchResult as FfiSearchResult; pub use crate::match_impl::{MatchBehavior, SearchBehavior}; use rusqlite::Row; @@ -621,11 +621,13 @@ mod tests { }, ) .expect("Should search by origin"); - assert!(by_origin - .iter() - .any(|result| result.search_string == "example.com" - && result.title == "example.com/" - && result.url.as_str() == "http://example.com/")); + assert!( + by_origin + .iter() + .any(|result| result.search_string == "example.com" + && result.title == "example.com/" + && result.url.as_str() == "http://example.com/") + ); let by_url_without_path = search_frecent( &conn, @@ -635,10 +637,12 @@ mod tests { }, ) .expect("Should search by URL without path"); - assert!(by_url_without_path - .iter() - .any(|result| result.title == "example.com/" - && result.url.as_str() == "http://example.com/")); + assert!( + by_url_without_path + .iter() + .any(|result| result.title == "example.com/" + && result.url.as_str() == "http://example.com/") + ); let by_url_with_path = search_frecent( &conn, @@ -648,10 +652,12 @@ mod tests { }, ) .expect("Should search by URL with path"); - assert!(by_url_with_path - .iter() - .any(|result| result.title == "example.com/123" - && result.url.as_str() == "http://example.com/123")); + assert!( + by_url_with_path + .iter() + .any(|result| result.title == "example.com/123" + && result.url.as_str() == "http://example.com/123") + ); accept_result(&conn, "ample", &url).expect("Should accept input history match"); @@ -663,9 +669,11 @@ mod tests { }, ) .expect("Should search by adaptive input history"); - assert!(by_adaptive - .iter() - .any(|result| result.search_string == "ample" && result.url == url)); + assert!( + by_adaptive + .iter() + .any(|result| result.search_string == "ample" && result.url == url) + ); let with_limit = search_frecent( &conn, @@ -706,11 +714,13 @@ mod tests { }, ) .expect("Should search by URL without path"); - assert!(by_url_without_path - .iter() - // Should we consider un-punycoding the title? (firefox desktop doesn't...) - .any(|result| result.title == "xn--exmple-cua.com/" - && result.url.as_str() == "http://xn--exmple-cua.com/")); + assert!( + by_url_without_path + .iter() + // Should we consider un-punycoding the title? (firefox desktop doesn't...) + .any(|result| result.title == "xn--exmple-cua.com/" + && result.url.as_str() == "http://xn--exmple-cua.com/") + ); let by_url_with_path = search_frecent( &conn, diff --git a/components/places/src/api/places_api.rs b/components/places/src/api/places_api.rs index c471ec6f06..530d06aa33 100644 --- a/components/places/src/api/places_api.rs +++ b/components/places/src/api/places_api.rs @@ -19,12 +19,12 @@ use std::cell::Cell; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::{ - atomic::{AtomicUsize, Ordering}, Arc, Weak, + atomic::{AtomicUsize, Ordering}, }; -use sync15::client::{sync_multiple, MemoryCachedState, Sync15StorageClientInit, SyncResult}; +use sync15::client::{MemoryCachedState, Sync15StorageClientInit, SyncResult, sync_multiple}; use sync15::engine::{EngineSyncAssociation, SyncEngine, SyncEngineId}; -use sync15::{telemetry, KeyBundle}; +use sync15::{KeyBundle, telemetry}; // Not clear if this should be here, but this is the "global sync state" // which is persisted to disk and reused for all engines. @@ -281,7 +281,7 @@ impl PlacesApi { fn set_disk_persisted_state(&self, conn: &PlacesDb, state: &Option) -> Result<()> { match state { - Some(ref s) => put_meta(conn, GLOBAL_STATE_META_KEY, s), + Some(s) => put_meta(conn, GLOBAL_STATE_META_KEY, s), None => delete_meta(conn, GLOBAL_STATE_META_KEY), } } diff --git a/components/places/src/bookmark_sync/engine.rs b/components/places/src/bookmark_sync/engine.rs index d8cdd58ce8..867f8dd162 100644 --- a/components/places/src/bookmark_sync/engine.rs +++ b/components/places/src/bookmark_sync/engine.rs @@ -10,11 +10,11 @@ use super::record::{ use super::{SyncedBookmarkKind, SyncedBookmarkValidity}; use crate::db::{GlobalChangeCounterTracker, PlacesDb, SharedPlacesDb}; use crate::error::*; -use crate::frecency::{calculate_frecency, DEFAULT_FRECENCY_SETTINGS}; +use crate::frecency::{DEFAULT_FRECENCY_SETTINGS, calculate_frecency}; use crate::storage::{ bookmarks::{ - bookmark_sync::{create_synced_bookmark_roots, reset}, BookmarkRootGuid, + bookmark_sync::{create_synced_bookmark_roots, reset}, }, delete_pending_temp_tables, get_meta, put_meta, }; @@ -31,10 +31,10 @@ use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::sync::Arc; +use sync_guid::Guid as SyncGuid; use sync15::bso::{IncomingBso, OutgoingBso}; use sync15::engine::{CollSyncIds, CollectionRequest, EngineSyncAssociation, SyncEngine}; -use sync15::{telemetry, CollectionName, ServerTimestamp}; -use sync_guid::Guid as SyncGuid; +use sync15::{CollectionName, ServerTimestamp, telemetry}; use types::Timestamp; pub const LAST_SYNC_META_KEY: &str = "bookmarks_last_sync_time"; // Note that all engines in this crate should use a *different* meta key @@ -1868,13 +1868,13 @@ impl fmt::Display for RootsFragment<'_> { #[cfg(test)] mod tests { use super::*; - use crate::api::places_api::{test::new_mem_api, ConnectionType, PlacesApi}; + use crate::api::places_api::{ConnectionType, PlacesApi, test::new_mem_api}; use crate::bookmark_sync::tests::SyncedBookmarkItem; use crate::db::PlacesDb; use crate::storage::{ bookmarks::{ - get_raw_bookmark, insert_bookmark, update_bookmark, BookmarkPosition, - InsertableBookmark, UpdatableBookmark, USER_CONTENT_ROOTS, + BookmarkPosition, InsertableBookmark, USER_CONTENT_ROOTS, UpdatableBookmark, + get_raw_bookmark, insert_bookmark, update_bookmark, }, history::frecency_stale_at, tags, @@ -1884,14 +1884,14 @@ mod tests { }; use dogear::{Store as DogearStore, Validity}; use rusqlite::{Error as RusqlError, ErrorCode}; - use serde_json::{json, Value}; + use serde_json::{Value, json}; use std::{ borrow::Cow, time::{Duration, SystemTime}, }; + use sync_guid::Guid; use sync15::bso::{IncomingBso, IncomingKind}; use sync15::engine::CollSyncIds; - use sync_guid::Guid; use url::Url; // A helper type to simplify writing table-driven tests with synced items. diff --git a/components/places/src/bookmark_sync/incoming.rs b/components/places/src/bookmark_sync/incoming.rs index a8c1a412e3..5dd2e70da5 100644 --- a/components/places/src/bookmark_sync/incoming.rs +++ b/components/places/src/bookmark_sync/incoming.rs @@ -9,18 +9,18 @@ use super::record::{ use super::{SyncedBookmarkKind, SyncedBookmarkValidity}; use crate::error::*; use crate::storage::{ - bookmarks::maybe_truncate_title, - tags::{validate_tag, ValidatedTag}, URL_LENGTH_MAX, + bookmarks::maybe_truncate_title, + tags::{ValidatedTag, validate_tag}, }; use crate::types::serialize_unknown_fields; use rusqlite::Connection; use serde_json::Value as JsonValue; use sql_support::{self, ConnExt}; use std::{collections::HashSet, iter}; -use sync15::bso::{IncomingBso, IncomingKind}; -use sync15::ServerTimestamp; use sync_guid::Guid as SyncGuid; +use sync15::ServerTimestamp; +use sync15::bso::{IncomingBso, IncomingKind}; use url::Url; // From Desktop's Ci.nsINavHistoryQueryOptions, but we define it as a str @@ -493,7 +493,7 @@ fn fixup_bookmark_json(json: &mut JsonValue) -> SyncedBookmarkValidity { let mut validity = SyncedBookmarkValidity::Valid; // the json value should always be on object, if not don't try to do any fixups. The result will // be that into_content_with_fixup() returns an IncomingContent with IncomingKind::Malformed. - if let JsonValue::Object(ref mut obj) = json { + if let JsonValue::Object(obj) = json { obj.entry("parentid") .and_modify(|v| fixup_optional_str(v, &mut validity)); obj.entry("title") @@ -567,7 +567,7 @@ fn fixup_optional_keyword(val: &mut JsonValue, validity: &mut SyncedBookmarkVali fn fixup_optional_tags(val: &mut JsonValue, validity: &mut SyncedBookmarkValidity) { match val { - JsonValue::Array(ref tags) => { + JsonValue::Array(tags) => { let mut valid_tags = HashSet::with_capacity(tags.len()); for v in tags { if let JsonValue::String(tag) = v { @@ -617,12 +617,12 @@ fn set_reupload(validity: &mut SyncedBookmarkValidity) { #[cfg(test)] mod tests { use super::*; - use crate::api::places_api::{test::new_mem_api, PlacesApi}; + use crate::api::places_api::{PlacesApi, test::new_mem_api}; use crate::bookmark_sync::record::{BookmarkItemRecord, FolderRecord}; use crate::bookmark_sync::tests::SyncedBookmarkItem; use crate::storage::bookmarks::BookmarkRootGuid; use crate::types::UnknownFields; - use serde_json::{json, Value}; + use serde_json::{Value, json}; fn apply_incoming(api: &PlacesApi, records_json: Value) { let db = api.get_sync_connection().expect("should get a db mutex"); diff --git a/components/places/src/bookmark_sync/mod.rs b/components/places/src/bookmark_sync/mod.rs index 1e7f97a9dd..86528ae914 100644 --- a/components/places/src/bookmark_sync/mod.rs +++ b/components/places/src/bookmark_sync/mod.rs @@ -11,8 +11,8 @@ mod tests; use crate::error::*; pub use engine::BookmarksSyncEngine; -use rusqlite::types::{ToSql, ToSqlOutput}; use rusqlite::Result as RusqliteResult; +use rusqlite::types::{ToSql, ToSqlOutput}; /// Synced item kinds. These are stored in `moz_bookmarks_synced.kind` and match /// the definitions in `mozISyncedBookmarksMerger`. diff --git a/components/places/src/bookmark_sync/record.rs b/components/places/src/bookmark_sync/record.rs index fc8cdcf195..e772cb99ab 100644 --- a/components/places/src/bookmark_sync/record.rs +++ b/components/places/src/bookmark_sync/record.rs @@ -403,7 +403,7 @@ where #[cfg(test)] mod tests { use super::*; - use serde_json::{json, Error}; + use serde_json::{Error, json}; #[test] fn test_invalid_record_type() { diff --git a/components/places/src/bookmark_sync/tests/payload_evolution.rs b/components/places/src/bookmark_sync/tests/payload_evolution.rs index de3e833e0d..4a557977e8 100644 --- a/components/places/src/bookmark_sync/tests/payload_evolution.rs +++ b/components/places/src/bookmark_sync/tests/payload_evolution.rs @@ -5,17 +5,18 @@ //! Tests for sync payload evolution. If we see new fields on incoming sync records, we should //! make sure to roundtrip them when we sync them back. +use crate::PlacesApi; use crate::api::places_api::test::new_mem_api; -use crate::bookmark_sync::record::BookmarkItemRecord; use crate::bookmark_sync::BookmarksSyncEngine; -use crate::storage::bookmarks::{update_bookmark_from_info, BookmarkUpdateInfo}; -use crate::PlacesApi; -use serde_json::{json, Value}; +use crate::bookmark_sync::record::BookmarkItemRecord; +use crate::storage::bookmarks::{BookmarkUpdateInfo, update_bookmark_from_info}; +use serde_json::{Value, json}; use std::collections::HashMap; use sync15::{ + ServerTimestamp, bso::{IncomingBso, IncomingKind, OutgoingBso}, engine::SyncEngine, - telemetry, ServerTimestamp, + telemetry, }; #[test] diff --git a/components/places/src/db/db.rs b/components/places/src/db/db.rs index 873e8e4cd3..27e1a04c40 100644 --- a/components/places/src/db/db.rs +++ b/components/places/src/db/db.rs @@ -10,16 +10,16 @@ use lazy_static::lazy_static; use parking_lot::Mutex; use rusqlite::{self, Connection, Transaction}; use sql_support::{ - open_database::{self, open_database_with_flags, ConnectionInitializer}, ConnExt, + open_database::{self, ConnectionInitializer, open_database_with_flags}, }; use std::collections::HashMap; use std::ops::Deref; use std::path::Path; use std::sync::{ - atomic::{AtomicI64, Ordering}, Arc, RwLock, + atomic::{AtomicI64, Ordering}, }; pub const MAX_VARIABLE_NUMBER: usize = 999; @@ -420,7 +420,7 @@ pub(crate) mod sql_fns { use crate::hash; use crate::match_impl::{AutocompleteMatch, MatchBehavior, SearchBehavior}; use rusqlite::types::Null; - use rusqlite::{functions::Context, types::ValueRef, Error, Result}; + use rusqlite::{Error, Result, functions::Context, types::ValueRef}; use std::sync::atomic::Ordering; use sync_guid::Guid as SyncGuid; use types::Timestamp; diff --git a/components/places/src/db/schema.rs b/components/places/src/db/schema.rs index 502b492e2d..236912d641 100644 --- a/components/places/src/db/schema.rs +++ b/components/places/src/db/schema.rs @@ -357,7 +357,7 @@ pub fn upgrade_from(db: &Connection, from: u32) -> rusqlite::Result<()> { #[cfg(test)] mod tests { use super::*; - use crate::db::{db::PlacesInitializer, PlacesDb}; + use crate::db::{PlacesDb, db::PlacesInitializer}; use crate::error::Result; use sql_support::open_database::test_utils::MigratedDatabaseFile; use std::collections::BTreeSet; diff --git a/components/places/src/ffi.rs b/components/places/src/ffi.rs index 07755236f3..22b65b8bba 100644 --- a/components/places/src/ffi.rs +++ b/components/places/src/ffi.rs @@ -4,13 +4,17 @@ // This module implement the traits that make the FFI code easier to manage. -use crate::api::matcher::{self, search_frecent, SearchParams}; +use crate::ConnectionType; +use crate::VisitObservation; +use crate::VisitType; +use crate::api::matcher::{self, SearchParams, search_frecent}; pub use crate::api::places_api::places_api_new; -pub use crate::error::{warn, Result}; pub use crate::error::{ApiResult, PlacesApiError}; +pub use crate::error::{Result, warn}; pub use crate::import::common::HistoryMigrationResult; use crate::import::import_ios_history; use crate::storage; +pub use crate::storage::RunMaintenanceMetrics; use crate::storage::bookmarks; pub use crate::storage::bookmarks::BookmarkPosition; pub use crate::storage::history_metadata::{ @@ -18,20 +22,16 @@ pub use crate::storage::history_metadata::{ HistoryMetadataObservation, HistoryMetadataPageMissingBehavior, NoteHistoryMetadataObservationOptions, }; -pub use crate::storage::RunMaintenanceMetrics; use crate::storage::{history, history_metadata}; use crate::types::VisitTransitionSet; -use crate::ConnectionType; -use crate::VisitObservation; -use crate::VisitType; use crate::{PlacesApi, PlacesDb}; use error_support::handle_error; -use interrupt_support::register_interrupt; pub use interrupt_support::SqlInterruptHandle; +use interrupt_support::register_interrupt; use parking_lot::Mutex; use std::sync::{Arc, Weak}; -use sync15::client::Sync15StorageClientInit; pub use sync_guid::Guid; +use sync15::client::Sync15StorageClientInit; pub use types::Timestamp as PlacesTimestamp; pub use url::Url; diff --git a/components/places/src/history_sync/engine.rs b/components/places/src/history_sync/engine.rs index f30a1fca92..46ca95d7ed 100644 --- a/components/places/src/history_sync/engine.rs +++ b/components/places/src/history_sync/engine.rs @@ -12,10 +12,10 @@ use sync15::bso::{IncomingBso, OutgoingBso}; use sync15::engine::{ CollSyncIds, CollectionRequest, EngineSyncAssociation, RequestOrder, SyncEngine, }; -use sync15::{telemetry, Guid, ServerTimestamp}; +use sync15::{Guid, ServerTimestamp, telemetry}; -use super::plan::{apply_plan, finish_plan, get_planned_outgoing}; use super::MAX_INCOMING_PLACES; +use super::plan::{apply_plan, finish_plan, get_planned_outgoing}; pub const LAST_SYNC_META_KEY: &str = "history_last_sync_time"; // Note that all engines in this crate should use a *different* meta key diff --git a/components/places/src/history_sync/payload_evolution_tests.rs b/components/places/src/history_sync/payload_evolution_tests.rs index 2b0ff07ec2..75e2980c7e 100644 --- a/components/places/src/history_sync/payload_evolution_tests.rs +++ b/components/places/src/history_sync/payload_evolution_tests.rs @@ -6,18 +6,19 @@ //! functionality from several modules. use crate::{ - api::places_api::{test::new_mem_api, PlacesApi}, - history_sync::{record::HistoryRecord, HistorySyncEngine}, + api::places_api::{PlacesApi, test::new_mem_api}, + history_sync::{HistorySyncEngine, record::HistoryRecord}, observation::VisitObservation, storage::history::apply_observation, types::{UnknownFields, VisitType}, }; -use serde_json::{json, Value}; +use serde_json::{Value, json}; use std::collections::{HashMap, HashSet}; use sync15::{ + ServerTimestamp, bso::{IncomingBso, IncomingKind, OutgoingBso}, engine::SyncEngine, - telemetry, ServerTimestamp, + telemetry, }; // Macro to quickly make `UnknownFields` values. It's like `json!`, but avoids the need to append diff --git a/components/places/src/history_sync/plan.rs b/components/places/src/history_sync/plan.rs index 6b9d3acbbc..03b667137f 100644 --- a/components/places/src/history_sync/plan.rs +++ b/components/places/src/history_sync/plan.rs @@ -10,17 +10,17 @@ use crate::error::*; use crate::storage::{ delete_pending_temp_tables, history::history_sync::{ - apply_synced_deletion, apply_synced_reconciliation, apply_synced_visits, fetch_outgoing, - fetch_visits, finish_outgoing, FetchedVisit, FetchedVisitPage, + FetchedVisit, FetchedVisitPage, apply_synced_deletion, apply_synced_reconciliation, + apply_synced_visits, fetch_outgoing, fetch_visits, finish_outgoing, }, }; use crate::types::{UnknownFields, VisitType}; use interrupt_support::Interruptee; use std::collections::HashSet; use std::time::{SystemTime, UNIX_EPOCH}; +use sync_guid::Guid as SyncGuid; use sync15::bso::{IncomingBso, IncomingKind, OutgoingBso}; use sync15::telemetry; -use sync_guid::Guid as SyncGuid; use types::Timestamp; use url::Url; @@ -291,7 +291,7 @@ pub fn finish_plan(db: &PlacesDb) -> Result<()> { #[cfg(test)] mod tests { use super::*; - use crate::api::matcher::{search_frecent, SearchParams}; + use crate::api::matcher::{SearchParams, search_frecent}; use crate::api::places_api::ConnectionType; use crate::db::PlacesDb; use crate::history_sync::ServerVisitTimestamp; diff --git a/components/places/src/import/common.rs b/components/places/src/import/common.rs index fbf45819b1..96bb34050d 100644 --- a/components/places/src/import/common.rs +++ b/components/places/src/import/common.rs @@ -4,7 +4,7 @@ use crate::db::PlacesDb; use crate::error::*; -use rusqlite::{named_params, Connection}; +use rusqlite::{Connection, named_params}; use serde::Serialize; use sql_support::ConnExt; use types::Timestamp; @@ -25,7 +25,7 @@ lazy_static::lazy_static! { pub mod sql_fns { use crate::import::common::NOW; use crate::storage::URL_LENGTH_MAX; - use rusqlite::{functions::Context, types::ValueRef, Result}; + use rusqlite::{Result, functions::Context, types::ValueRef}; use types::Timestamp; use url::Url; diff --git a/components/places/src/import/ios/history.rs b/components/places/src/import/ios/history.rs index 64be5fd57d..33d996a5b5 100644 --- a/components/places/src/import/ios/history.rs +++ b/components/places/src/import/ios/history.rs @@ -4,13 +4,13 @@ use std::time::Instant; -use crate::error::{info, Result}; +use crate::PlacesDb; +use crate::error::{Result, info}; use crate::history_sync::engine::LAST_SYNC_META_KEY; use crate::import::common::{ - attached_database, define_history_migration_functions, select_count, HistoryMigrationResult, + HistoryMigrationResult, attached_database, define_history_migration_functions, select_count, }; use crate::storage::{put_meta, update_all_frecencies_at_once}; -use crate::PlacesDb; use types::Timestamp; use url::Url; diff --git a/components/places/src/lib.rs b/components/places/src/lib.rs index 3e7ff3df5c..8d2bfde5b3 100644 --- a/components/places/src/lib.rs +++ b/components/places/src/lib.rs @@ -27,7 +27,7 @@ mod util; pub use crate::api::apply_observation; #[cfg(test)] pub use crate::api::places_api::test; -pub use crate::api::places_api::{get_registered_sync_engine, ConnectionType, PlacesApi}; +pub use crate::api::places_api::{ConnectionType, PlacesApi, get_registered_sync_engine}; pub use crate::db::PlacesDb; pub use crate::error::*; diff --git a/components/places/src/storage/bookmarks.rs b/components/places/src/storage/bookmarks.rs index 4f8a7c031d..46eb92d123 100644 --- a/components/places/src/storage/bookmarks.rs +++ b/components/places/src/storage/bookmarks.rs @@ -14,10 +14,10 @@ use crate::types::{BookmarkType, SyncStatus}; use rusqlite::{self, Connection, Row}; #[cfg(test)] use serde_json::{self, json}; -use sql_support::{self, repeat_sql_vars, ConnExt}; +use sql_support::{self, ConnExt, repeat_sql_vars}; use std::cmp::{max, min}; -use sync15::engine::EngineSyncAssociation; use sync_guid::Guid as SyncGuid; +use sync15::engine::EngineSyncAssociation; use types::Timestamp; use url::Url; diff --git a/components/places/src/storage/bookmarks/json_tree.rs b/components/places/src/storage/bookmarks/json_tree.rs index 802ea43352..f04bc89ac4 100644 --- a/components/places/src/storage/bookmarks/json_tree.rs +++ b/components/places/src/storage/bookmarks/json_tree.rs @@ -11,7 +11,7 @@ // and avoid using this if you can! // (We could possibly put this behind a feature flag?) -use crate::error::{warn, Result}; +use crate::error::{Result, warn}; use crate::types::BookmarkType; //#[cfg(test)] use crate::db::PlacesDb; diff --git a/components/places/src/storage/history.rs b/components/places/src/storage/history.rs index f8d80e2cae..22ae181610 100644 --- a/components/places/src/storage/history.rs +++ b/components/places/src/storage/history.rs @@ -4,9 +4,9 @@ mod actions; -use super::{fetch_page_info, new_page_info, PageInfo, RowId}; +use super::{PageInfo, RowId, fetch_page_info, new_page_info}; use crate::db::PlacesDb; -use crate::error::{debug, trace, warn, Result}; +use crate::error::{Result, debug, trace, warn}; use crate::ffi::{HistoryVisitInfo, HistoryVisitInfosWithBound, TopFrecentSiteInfo}; use crate::frecency; use crate::hash; @@ -18,18 +18,18 @@ use crate::storage::{ delete_meta, delete_pending_temp_tables, get_meta, history_metadata, put_meta, }; use crate::types::{ - serialize_unknown_fields, SyncStatus, UnknownFields, VisitTransitionSet, VisitType, + SyncStatus, UnknownFields, VisitTransitionSet, VisitType, serialize_unknown_fields, }; use actions::*; -use rusqlite::types::ToSql; use rusqlite::Result as RusqliteResult; use rusqlite::Row; +use rusqlite::types::ToSql; use sql_support::{self, ConnExt}; use std::collections::HashSet; use std::time::Duration; +use sync_guid::Guid as SyncGuid; use sync15::bso::OutgoingBso; use sync15::engine::EngineSyncAssociation; -use sync_guid::Guid as SyncGuid; use types::Timestamp; use url::Url; @@ -774,8 +774,8 @@ pub mod history_sync { use sync15::bso::OutgoingEnvelope; use super::*; - use crate::history_sync::record::{HistoryRecord, HistoryRecordVisit}; use crate::history_sync::HISTORY_TTL; + use crate::history_sync::record::{HistoryRecord, HistoryRecordVisit}; use std::collections::HashSet; #[derive(Debug, Clone, PartialEq, Eq)] @@ -1546,7 +1546,7 @@ mod tests { use super::history_sync::*; use super::*; use crate::history_sync::record::HistoryRecordVisit; - use crate::storage::bookmarks::{insert_bookmark, InsertableItem}; + use crate::storage::bookmarks::{InsertableItem, insert_bookmark}; use crate::types::VisitTransitionSet; use crate::{api::places_api::ConnectionType, storage::bookmarks::BookmarkRootGuid}; use std::time::{Duration, SystemTime}; @@ -1987,9 +1987,11 @@ mod tests { assert_eq!(pi.page.visit_count_local, 1); // should have removed all the visits to /2 - assert!(fetch_page_info(&conn, &url2) - .expect("should work") - .is_none()); + assert!( + fetch_page_info(&conn, &url2) + .expect("should work") + .is_none() + ); // Should still have the 1 visit to /3 let pi3 = fetch_page_info(&conn, &url3) @@ -1998,9 +2000,11 @@ mod tests { assert_eq!(pi3.page.visit_count_local, 1); // should have removed all the visits to /4 - assert!(fetch_page_info(&conn, &url4) - .expect("should work") - .is_none()); + assert!( + fetch_page_info(&conn, &url4) + .expect("should work") + .is_none() + ); // should be a tombstone for url4 and no others. assert_eq!(get_tombstone_count(&conn), 1); // XXX - test frecency? @@ -2966,14 +2970,16 @@ mod tests { let url1 = Url::parse("https://www.example.com/").unwrap(); // Can observe preview url without an associated visit. - assert!(apply_observation( - &conn, - VisitObservation::new(url1.clone()).with_preview_image_url(Some( - Url::parse("https://www.example.com/image.png").unwrap() - )) - ) - .unwrap() - .is_none()); + assert!( + apply_observation( + &conn, + VisitObservation::new(url1.clone()).with_preview_image_url(Some( + Url::parse("https://www.example.com/image.png").unwrap() + )) + ) + .unwrap() + .is_none() + ); // We don't get a visit id back above, so just assume an id of the corresponding moz_places entry. let mut db_preview_url = conn diff --git a/components/places/src/storage/history/actions.rs b/components/places/src/storage/history/actions.rs index a2c4a8e511..3d1b9a997d 100644 --- a/components/places/src/storage/history/actions.rs +++ b/components/places/src/storage/history/actions.rs @@ -27,7 +27,7 @@ //! Right now, only a couple function use this system, but hopefully we can use it more in the //! future. -use super::{cleanup_pages, PageToClean}; +use super::{PageToClean, cleanup_pages}; use crate::error::Result; use crate::{PlacesDb, RowId}; use rusqlite::Row; @@ -166,7 +166,7 @@ mod tests { use crate::storage::bookmarks::*; use crate::storage::history::apply_observation; use crate::types::VisitType; - use crate::{frecency, ConnectionType, SyncStatus}; + use crate::{ConnectionType, SyncStatus, frecency}; use rusqlite::params; use rusqlite::types::{FromSql, ToSql}; use std::time::Duration; diff --git a/components/places/src/storage/history_metadata.rs b/components/places/src/storage/history_metadata.rs index bfba80fc2a..1958d07211 100644 --- a/components/places/src/storage/history_metadata.rs +++ b/components/places/src/storage/history_metadata.rs @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use crate::RowId; use crate::db::{PlacesDb, PlacesTransaction}; use crate::error::*; -use crate::RowId; use error_support::{breadcrumb, redact_url}; use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use sql_support::ConnExt; @@ -749,7 +749,7 @@ fn insert_metadata_in_tx( let place_id = match (key.place_entry, options.if_page_missing) { (PlaceEntry::Existing(id), _) => id, (PlaceEntry::CreateFor(_, _), HistoryMetadataPageMissingBehavior::IgnoreObservation) => { - return Ok(()) + return Ok(()); } ( ref entry @ PlaceEntry::CreateFor(_, _), @@ -784,11 +784,12 @@ fn insert_metadata_in_tx( #[cfg(test)] mod tests { use super::*; + use crate::VisitTransitionSet; use crate::api::places_api::ConnectionType; use crate::observation::VisitObservation; use crate::storage::bookmarks::{ - get_raw_bookmark, insert_bookmark, BookmarkPosition, BookmarkRootGuid, InsertableBookmark, - InsertableItem, + BookmarkPosition, BookmarkRootGuid, InsertableBookmark, InsertableItem, get_raw_bookmark, + insert_bookmark, }; use crate::storage::fetch_page_info; use crate::storage::history::{ @@ -796,7 +797,6 @@ mod tests { get_visit_count, url_to_guid, }; use crate::types::VisitType; - use crate::VisitTransitionSet; use std::{thread, time}; macro_rules! assert_table_size { @@ -1184,34 +1184,38 @@ mod tests { ); // 48 hrs is clearly a bad view to observe. - assert!(apply_metadata_observation( - &conn, - HistoryMetadataObservation { - url: String::from("https://www.mozilla.org"), - view_time: Some(1000 * 60 * 60 * 24 * 2), - search_term: None, - document_type: None, - referrer_url: None, - title: None - }, - NoteHistoryMetadataObservationOptions::new(), - ) - .is_err()); + assert!( + apply_metadata_observation( + &conn, + HistoryMetadataObservation { + url: String::from("https://www.mozilla.org"), + view_time: Some(1000 * 60 * 60 * 24 * 2), + search_term: None, + document_type: None, + referrer_url: None, + title: None + }, + NoteHistoryMetadataObservationOptions::new(), + ) + .is_err() + ); // 12 hrs is assumed to be "plausible". - assert!(apply_metadata_observation( - &conn, - HistoryMetadataObservation { - url: String::from("https://www.mozilla.org"), - view_time: Some(1000 * 60 * 60 * 12), - search_term: None, - document_type: None, - referrer_url: None, - title: None - }, - NoteHistoryMetadataObservationOptions::new(), - ) - .is_ok()); + assert!( + apply_metadata_observation( + &conn, + HistoryMetadataObservation { + url: String::from("https://www.mozilla.org"), + view_time: Some(1000 * 60 * 60 * 12), + search_term: None, + document_type: None, + referrer_url: None, + title: None + }, + NoteHistoryMetadataObservationOptions::new(), + ) + .is_ok() + ); } #[test] @@ -1869,9 +1873,11 @@ mod tests { .expect("should exist"); assert!(pi.last_visit_id.is_none()); // and no metadata observations. - assert!(get_latest_for_url(&conn, &url) - .expect("should work") - .is_none()); + assert!( + get_latest_for_url(&conn, &url) + .expect("should work") + .is_none() + ); } #[test] @@ -1903,9 +1909,11 @@ mod tests { delete_visits_for(&conn, &place_guid).expect("should work"); // place no longer exists. assert!(fetch_page_info(&conn, &url).expect("should work").is_none()); - assert!(get_latest_for_url(&conn, &url) - .expect("should work") - .is_none()); + assert!( + get_latest_for_url(&conn, &url) + .expect("should work") + .is_none() + ); } #[test] @@ -1935,9 +1943,11 @@ mod tests { delete_visits_for(&conn, &place_guid).expect("should work"); // place no longer exists. assert!(fetch_page_info(&conn, &url).expect("should work").is_none()); - assert!(get_latest_for_url(&conn, &url) - .expect("should work") - .is_none()); + assert!( + get_latest_for_url(&conn, &url) + .expect("should work") + .is_none() + ); } #[test] @@ -2146,14 +2156,15 @@ mod tests { ); // double-check that we have the 'firefox' search query entry. - assert!(conn - .try_query_one::( + assert!( + conn.try_query_one::( "SELECT id FROM moz_places_metadata_search_queries WHERE term = :term", rusqlite::named_params! { ":term": "firefox" }, true ) .expect("select works") - .is_some()); + .is_some() + ); // Delete our first page & its visits. Note that /another/ page will remain in place. delete_visits_between( diff --git a/components/places/src/storage/mod.rs b/components/places/src/storage/mod.rs index 5b79a5a6d5..5730a530fc 100644 --- a/components/places/src/storage/mod.rs +++ b/components/places/src/storage/mod.rs @@ -11,14 +11,14 @@ pub mod history_metadata; pub mod tags; use crate::db::PlacesDb; -use crate::error::{warn, Error, InvalidPlaceInfo, Result}; +use crate::error::{Error, InvalidPlaceInfo, Result, warn}; use crate::ffi::HistoryVisitInfo; use crate::ffi::TopFrecentSiteInfo; -use crate::frecency::{calculate_frecency, DEFAULT_FRECENCY_SETTINGS}; +use crate::frecency::{DEFAULT_FRECENCY_SETTINGS, calculate_frecency}; use crate::types::{SyncStatus, UnknownFields, VisitType}; use interrupt_support::SqlInterruptScope; -use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use rusqlite::Result as RusqliteResult; +use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use rusqlite::{Connection, Row}; use serde_derive::*; use sql_support::{self, ConnExt}; @@ -399,8 +399,8 @@ mod tests { use crate::api::places_api::test::new_mem_connection; use crate::observation::VisitObservation; use bookmarks::{ - delete_bookmark, insert_bookmark, BookmarkPosition, BookmarkRootGuid, InsertableBookmark, - InsertableItem, + BookmarkPosition, BookmarkRootGuid, InsertableBookmark, InsertableItem, delete_bookmark, + insert_bookmark, }; use history::apply_observation; @@ -409,9 +409,11 @@ mod tests { let conn = new_mem_connection(); let value1 = "value 1".to_string(); let value2 = "value 2".to_string(); - assert!(get_meta::(&conn, "foo") - .expect("should get") - .is_none()); + assert!( + get_meta::(&conn, "foo") + .expect("should get") + .is_none() + ); put_meta(&conn, "foo", &value1).expect("should put"); assert_eq!( get_meta(&conn, "foo").expect("should get new val"), @@ -420,9 +422,11 @@ mod tests { put_meta(&conn, "foo", &value2).expect("should put an existing value"); assert_eq!(get_meta(&conn, "foo").expect("should get"), Some(value2)); delete_meta(&conn, "foo").expect("should delete"); - assert!(get_meta::(&conn, "foo") - .expect("should get non-existing") - .is_none()); + assert!( + get_meta::(&conn, "foo") + .expect("should get non-existing") + .is_none() + ); delete_meta(&conn, "foo").expect("delete non-existing should work"); } @@ -515,14 +519,16 @@ mod tests { 1 ); // visit the bookmark. - assert!(apply_observation( - &conn, - VisitObservation::new(url) - .with_at(Timestamp::from(727_747_200_001)) - .with_visit_type(VisitType::Link) - ) - .unwrap() - .is_some()); + assert!( + apply_observation( + &conn, + VisitObservation::new(url) + .with_at(Timestamp::from(727_747_200_001)) + .with_visit_type(VisitType::Link) + ) + .unwrap() + .is_some() + ); delete_bookmark(&conn, &bookmark_guid).unwrap(); assert_eq!( @@ -530,7 +536,7 @@ mod tests { .unwrap(), 5 ); // our 5 roots - // the place should have no foreign references, but still exists. + // the place should have no foreign references, but still exists. assert_eq!( conn.conn_ext_query_one::( "SELECT foreign_count FROM moz_places WHERE url = \"http://example.com/foo\";" @@ -594,7 +600,7 @@ mod tests { .unwrap(), 5 ); // our 5 roots - // should be gone from places and origins. + // should be gone from places and origins. assert_eq!( conn.conn_ext_query_one::("SELECT COUNT(*) FROM moz_places;") .unwrap(), diff --git a/components/places/src/storage/tags.rs b/components/places/src/storage/tags.rs index c755dce477..1631496263 100644 --- a/components/places/src/storage/tags.rs +++ b/components/places/src/storage/tags.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::{fetch_page_info, TAG_LENGTH_MAX}; +use super::{TAG_LENGTH_MAX, fetch_page_info}; use crate::db::PlacesDb; use crate::error::{InvalidPlaceInfo, Result}; use sql_support::ConnExt; diff --git a/components/places/src/tests.rs b/components/places/src/tests.rs index b64f7466cd..aa651e6006 100644 --- a/components/places/src/tests.rs +++ b/components/places/src/tests.rs @@ -7,7 +7,7 @@ use serde_json::Value; use crate::{ db::PlacesDb, storage::bookmarks::get_raw_bookmark, - storage::bookmarks::json_tree::{fetch_tree, insert_tree, BookmarkTreeNode, FetchDepth}, + storage::bookmarks::json_tree::{BookmarkTreeNode, FetchDepth, fetch_tree, insert_tree}, types::BookmarkType, }; diff --git a/components/places/src/types.rs b/components/places/src/types.rs index 9c2cf8a812..416bdf2e1f 100644 --- a/components/places/src/types.rs +++ b/components/places/src/types.rs @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use rusqlite::Result as RusqliteResult; +use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use serde::ser::{Serialize, Serializer}; use std::fmt; diff --git a/components/sync15/Cargo.toml b/components/sync15/Cargo.toml index 9e53ad75d2..9ae60652b5 100644 --- a/components/sync15/Cargo.toml +++ b/components/sync15/Cargo.toml @@ -1,8 +1,7 @@ [package] name = "sync15" -edition = "2021" +edition = "2024" version = "0.1.0" -authors = ["Sync Team "] license = "MPL-2.0" exclude = ["/android", "/ios"] @@ -16,34 +15,18 @@ random-guid = ["sync-guid/random"] # Some consumers of this just need our encrypted payloads and no other sync functionality. crypto = ["rc_crypto", "base16", "base64"] -# Some crates need to implement a "sync engine", but aren't a "sync client" (ie, their -# engine is used by a "sync client".) Engines don't interact directly with the storage servers, -# nor do they do their own crypto. +# Some libraries need to implement a "sync engine", but aren't a "sync client" (ie, their +# engine is used by an external "sync client", like on desktop). +# Engines don't interact directly with the storage servers, nor do they do their own crypto. # See the rustdocs in `crate::engine` for more information about engines. sync-engine = ["random-guid"] -# Some crates are a "sync client" and do full management/initialization of server storage, -# keys, etc and sync one or more engines. This crate has an engine to manage the "clients" -# collection, so needs the sync-engine feature. +# Some libraries are a "sync client" and do full management/initialization of server storage, +# keys, etc and sync one or more engines. This feature will enable this crate to have a `clients` +# engine to manage state in the `clients` collection - thus, it requires the `sync-engine` feature. # See the rustdocs in `crate::client` for more information about clients. sync-client = ["sync-engine", "crypto", "viaduct", "url"] -# Some crates just do their own engine but need to pretend they are a client, -# eg, iOS pre-sync-manager. -# Consider places: -# * It always is going to need to supply a "sync-engine". -# * When used in iOS, due to the lack of sync_manager support, it also needs to -# supply a kind of "sync-client". It is *not* necessary to supply this for Android. -# In a perfect world: -# * places would also have a feature called, say, "sync-client" -# * The code needed for iOS would be behind the "sync-client" feature. -# * The ios megazord would enable the "sync-client" feature, but the android megazord would not. -# -# However, that's not yet the case. This "stand-alone" sync feature is used by crates -# such as places, and is really a marker to help identify the crates which should be -# upgraded to make the sync-client part truly optional. -standalone-sync = ["sync-client"] - [dependencies] anyhow = "1.0" base16 = { version = "0.2", optional = true } @@ -66,6 +49,3 @@ viaduct = { path = "../viaduct", optional = true } [dev-dependencies] error-support = { path = "../support/error", features = ["testing"] } nss = { path = "../support/rc_crypto/nss" } - -[build-dependencies] -uniffi = { version = "0.29.0", features=["build"]} diff --git a/components/sync15/build.rs b/components/sync15/build.rs deleted file mode 100644 index a4c1bb8d4e..0000000000 --- a/components/sync15/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("./src/sync15.udl").unwrap(); -} diff --git a/components/sync15/src/bso/content.rs b/components/sync15/src/bso/content.rs index 4f3e09385f..f40d773d1e 100644 --- a/components/sync15/src/bso/content.rs +++ b/components/sync15/src/bso/content.rs @@ -10,8 +10,8 @@ //! * Turn arbitrary objects with an `id` field into an OutgoingBso. use super::{IncomingBso, IncomingContent, IncomingKind, OutgoingBso, OutgoingEnvelope}; -use crate::error::{trace, warn}; use crate::Guid; +use crate::error::{trace, warn}; use error_support::report_error; use serde::Serialize; @@ -143,8 +143,7 @@ where if content_id != id { trace!( "malformed incoming record: envelope id: {} payload id: {}", - content_id, - id + content_id, id ); report_error!( "incoming-invalid-mismatched-ids", diff --git a/components/sync15/src/bso/crypto.rs b/components/sync15/src/bso/crypto.rs index d572c4692b..4e58843aec 100644 --- a/components/sync15/src/bso/crypto.rs +++ b/components/sync15/src/bso/crypto.rs @@ -6,10 +6,10 @@ //! This module decrypts them into IncomingBso's suitable for use by the //! engines. use super::{IncomingBso, IncomingEnvelope, OutgoingBso, OutgoingEnvelope}; +use crate::EncryptedPayload; use crate::error; use crate::key_bundle::KeyBundle; -use crate::EncryptedPayload; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; // The BSO implementation we use for encrypted payloads. // Note that this is almost identical to the IncomingBso implementations, except diff --git a/components/sync15/src/client/coll_state.rs b/components/sync15/src/client/coll_state.rs index d4fba5bd65..cf3c98f5be 100644 --- a/components/sync15/src/client/coll_state.rs +++ b/components/sync15/src/client/coll_state.rs @@ -4,11 +4,11 @@ use super::request::InfoConfiguration; use super::{CollectionKeys, GlobalState}; +use crate::KeyBundle; +use crate::ServerTimestamp; use crate::engine::{CollSyncIds, EngineSyncAssociation, SyncEngine}; use crate::error; use crate::error::{info, trace, warn}; -use crate::KeyBundle; -use crate::ServerTimestamp; /// Holds state for a collection necessary to perform a sync of it. Lives for the lifetime /// of a single sync. @@ -166,13 +166,13 @@ impl<'state> LocalCollStateMachine<'state> { #[cfg(test)] mod tests { - use super::super::request::{InfoCollections, InfoConfiguration}; use super::super::CollectionKeys; + use super::super::request::{InfoCollections, InfoConfiguration}; use super::*; use crate::bso::{IncomingBso, OutgoingBso}; use crate::engine::CollectionRequest; use crate::record_types::{MetaGlobalEngine, MetaGlobalRecord}; - use crate::{telemetry, CollectionName}; + use crate::{CollectionName, telemetry}; use anyhow::Result; use nss::ensure_initialized; use std::cell::{Cell, RefCell}; diff --git a/components/sync15/src/client/coll_update.rs b/components/sync15/src/client/coll_update.rs index 87430b7727..2164a6d669 100644 --- a/components/sync15/src/client/coll_update.rs +++ b/components/sync15/src/client/coll_update.rs @@ -3,8 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use super::{ - request::{NormalResponseHandler, UploadInfo}, CollState, Sync15ClientResponse, Sync15StorageClient, + request::{NormalResponseHandler, UploadInfo}, }; use crate::bso::{IncomingBso, OutgoingBso, OutgoingEncryptedBso}; use crate::engine::CollectionRequest; diff --git a/components/sync15/src/client/mod.rs b/components/sync15/src/client/mod.rs index c49486bfe6..e13a6334b2 100644 --- a/components/sync15/src/client/mod.rs +++ b/components/sync15/src/client/mod.rs @@ -26,7 +26,7 @@ mod token; mod util; pub(crate) use coll_state::{CollState, LocalCollStateMachine}; -pub(crate) use coll_update::{fetch_incoming, CollectionUpdate}; +pub(crate) use coll_update::{CollectionUpdate, fetch_incoming}; pub(crate) use collection_keys::CollectionKeys; pub(crate) use request::InfoConfiguration; pub(crate) use state::GlobalState; @@ -35,5 +35,5 @@ pub use storage_client::{ SetupStorageClient, Sync15ClientResponse, Sync15StorageClient, Sync15StorageClientInit, }; pub use sync_multiple::{ - sync_multiple, sync_multiple_with_command_processor, MemoryCachedState, SyncRequestInfo, + MemoryCachedState, SyncRequestInfo, sync_multiple, sync_multiple_with_command_processor, }; diff --git a/components/sync15/src/client/request.rs b/components/sync15/src/client/request.rs index 3c2a21c8ed..e21629fe77 100644 --- a/components/sync15/src/client/request.rs +++ b/components/sync15/src/client/request.rs @@ -3,9 +3,9 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use super::storage_client::Sync15ClientResponse; -use crate::bso::OutgoingEncryptedBso; -use crate::error::{self, debug, info, warn, Error as ErrorKind, Result}; use crate::ServerTimestamp; +use crate::bso::OutgoingEncryptedBso; +use crate::error::{self, Error as ErrorKind, Result, debug, info, warn}; use serde_derive::*; use std::collections::HashMap; use std::default::Default; @@ -348,7 +348,7 @@ where // First commit in possible batch BatchState::NoBatch => Some("true".into()), // In a batch and we have a batch id. - BatchState::InBatch(ref s) => Some(s.clone()), + BatchState::InBatch(s) => Some(s.clone()), }; info!( @@ -427,7 +427,7 @@ where warn!("Server changed its mind about supporting batching mid-batch..."); } - BatchState::InBatch(ref cur_id) => { + BatchState::InBatch(cur_id) => { if cur_id != &batch_id { return Err(ErrorKind::ServerBatchProblem( "Invalid server response: 202 without a batch ID", @@ -486,8 +486,8 @@ impl PostQueue { #[cfg(test)] mod test { use super::*; - use crate::bso::{IncomingEncryptedBso, OutgoingEncryptedBso, OutgoingEnvelope}; use crate::EncryptedPayload; + use crate::bso::{IncomingEncryptedBso, OutgoingEncryptedBso, OutgoingEnvelope}; use lazy_static::lazy_static; use std::cell::RefCell; use std::collections::VecDeque; diff --git a/components/sync15/src/client/state.rs b/components/sync15/src/client/state.rs index 11932a175b..564701858e 100644 --- a/components/sync15/src/client/state.rs +++ b/components/sync15/src/client/state.rs @@ -4,13 +4,13 @@ use std::collections::{HashMap, HashSet}; +use super::CollectionKeys; use super::request::{InfoCollections, InfoConfiguration}; use super::storage_client::{SetupStorageClient, Sync15ClientResponse}; -use super::CollectionKeys; +use crate::EncryptedPayload; use crate::bso::OutgoingEncryptedBso; -use crate::error::{self, debug, info, trace, warn, Error as ErrorKind, ErrorResponse}; +use crate::error::{self, Error as ErrorKind, ErrorResponse, debug, info, trace, warn}; use crate::record_types::{MetaGlobalEngine, MetaGlobalRecord}; -use crate::EncryptedPayload; use crate::{Guid, KeyBundle, ServerTimestamp}; use interrupt_support::Interruptee; use serde_derive::*; @@ -144,7 +144,7 @@ fn compute_engine_states(input: EngineStateInput) -> EngineStateOutput { impl PersistedGlobalState { fn set_declined(&mut self, new_declined: Vec) { match self { - Self::V2 { ref mut declined } => *declined = Some(new_declined), + Self::V2 { declined } => *declined = Some(new_declined), } } pub(crate) fn get_declined(&self) -> &[String] { @@ -353,7 +353,9 @@ impl<'a> SetupStateMachine<'a> { if global.storage_version < STORAGE_VERSION { Ok(FreshStartRequired { config }) } else { - info!("Have info/collections and meta/global. Computing new engine states"); + info!( + "Have info/collections and meta/global. Computing new engine states" + ); let initial_global_declined: HashSet = global.declined.iter().cloned().collect(); let result = compute_engine_states(EngineStateInput { @@ -372,8 +374,7 @@ impl<'a> SetupStateMachine<'a> { global.declined = result.declined.iter().cloned().collect(); info!( "Uploading new declined {:?} to meta/global with timestamp {:?}", - global.declined, - global_timestamp, + global.declined, global_timestamp, ); true } else { @@ -666,10 +667,12 @@ mod tests { global: &MetaGlobalRecord, ) -> error::Result { // Ensure that the meta/global record we uploaded is "fixed up" - assert!(DEFAULT_ENGINES - .iter() - .filter(|e| e.0 != "logins") - .all(|&(k, _v)| global.engines.contains_key(k))); + assert!( + DEFAULT_ENGINES + .iter() + .filter(|e| e.0 != "logins") + .all(|&(k, _v)| global.engines.contains_key(k)) + ); assert!(!global.engines.contains_key("logins")); assert_eq!(global.declined, vec!["logins".to_string()]); // return a different timestamp. diff --git a/components/sync15/src/client/status.rs b/components/sync15/src/client/status.rs index 407efeec12..ae1f43ef18 100644 --- a/components/sync15/src/client/status.rs +++ b/components/sync15/src/client/status.rs @@ -44,7 +44,7 @@ impl ServiceStatus { } // BackoffError is also from the tokenserver. Error::BackoffError(_) => ServiceStatus::ServiceError, - Error::StorageHttpError(ref e) => match e { + Error::StorageHttpError(e) => match e { ErrorResponse::Unauthorized { .. } => ServiceStatus::AuthenticationError, _ => ServiceStatus::ServiceError, }, diff --git a/components/sync15/src/client/storage_client.rs b/components/sync15/src/client/storage_client.rs index ca38c18876..4066e31433 100644 --- a/components/sync15/src/client/storage_client.rs +++ b/components/sync15/src/client/storage_client.rs @@ -8,7 +8,7 @@ use super::request::{ use super::token; use crate::bso::{IncomingBso, IncomingEncryptedBso, OutgoingBso, OutgoingEncryptedBso}; use crate::engine::{CollectionPost, CollectionRequest}; -use crate::error::{self, debug, info, trace, warn, Error, ErrorResponse}; +use crate::error::{self, Error, ErrorResponse, debug, info, trace, warn}; use crate::record_types::MetaGlobalRecord; use crate::{CollectionName, Guid, ServerTimestamp}; use serde_json::Value; @@ -16,8 +16,8 @@ use std::str::FromStr; use std::sync::atomic::{AtomicU32, Ordering}; use url::Url; use viaduct::{ - header_names::{self, AUTHORIZATION}, Method, Request, Response, + header_names::{self, AUTHORIZATION}, }; /// A response from a GET request on a Sync15StorageClient, encapsulating all @@ -565,8 +565,10 @@ mod test { .newer_than(ServerTimestamp(1_234_560)), ) .unwrap(); - assert_eq!(complex.as_str(), - "https://example.com/sync/storage/specific?full=1&older=9876.54&newer=1234.56&sort=oldest&limit=10"); + assert_eq!( + complex.as_str(), + "https://example.com/sync/storage/specific?full=1&older=9876.54&newer=1234.56&sort=oldest&limit=10" + ); } #[cfg(feature = "sync-client")] diff --git a/components/sync15/src/client/sync.rs b/components/sync15/src/client/sync.rs index 9f07fe43c4..f680afaa27 100644 --- a/components/sync15/src/client/sync.rs +++ b/components/sync15/src/client/sync.rs @@ -3,11 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use super::{CollectionUpdate, GlobalState, LocalCollStateMachine, Sync15StorageClient}; +use crate::KeyBundle; use crate::clients_engine; use crate::engine::SyncEngine; -use crate::error::{info, warn, Error}; +use crate::error::{Error, info, warn}; use crate::telemetry; -use crate::KeyBundle; use interrupt_support::Interruptee; #[allow(clippy::too_many_arguments)] diff --git a/components/sync15/src/client/sync_multiple.rs b/components/sync15/src/client/sync_multiple.rs index dbc4ad4351..e24d0d4410 100644 --- a/components/sync15/src/client/sync_multiple.rs +++ b/components/sync15/src/client/sync_multiple.rs @@ -8,11 +8,11 @@ use super::state::{EngineChangesNeeded, GlobalState, PersistedGlobalState, SetupStateMachine}; use super::status::{ServiceStatus, SyncResult}; use super::storage_client::{BackoffListener, Sync15StorageClient, Sync15StorageClientInit}; -use crate::clients_engine::{self, CommandProcessor, CLIENTS_TTL_REFRESH}; +use crate::KeyBundle; +use crate::clients_engine::{self, CLIENTS_TTL_REFRESH, CommandProcessor}; use crate::engine::{EngineSyncAssociation, SyncEngine}; -use crate::error::{debug, info, trace, warn, Error}; +use crate::error::{Error, debug, info, trace, warn}; use crate::telemetry; -use crate::KeyBundle; use interrupt_support::Interruptee; use std::collections::HashMap; use std::result; diff --git a/components/sync15/src/client/token.rs b/components/sync15/src/client/token.rs index fed19ae271..86ae17084e 100644 --- a/components/sync15/src/client/token.rs +++ b/components/sync15/src/client/token.rs @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::error::{self, debug, trace, warn, Error as ErrorKind, Result}; use crate::ServerTimestamp; +use crate::error::{self, Error as ErrorKind, Result, debug, trace, warn}; use rc_crypto::hawk; use serde_derive::*; use std::borrow::{Borrow, Cow}; @@ -11,7 +11,7 @@ use std::cell::RefCell; use std::fmt; use std::time::{Duration, SystemTime}; use url::Url; -use viaduct::{header_names, Request}; +use viaduct::{Request, header_names}; const RETRY_AFTER_DEFAULT_MS: u64 = 10000; @@ -328,7 +328,7 @@ impl TokenProviderImpl { Some(self.fetch_token(Some(existing_context.token.api_endpoint.as_str()))) } } - TokenState::Backoff(ref until, ref existing_endpoint) => { + TokenState::Backoff(until, existing_endpoint) => { if let Ok(remaining) = until.duration_since(self.fetcher.now()) { debug!("enforcing existing backoff - {:?} remains", remaining); None @@ -362,7 +362,7 @@ impl TokenProviderImpl { // it should be impossible to get here. panic!("Can't be in NoToken state after advancing"); } - TokenState::Token(ref token_context) => { + TokenState::Token(token_context) => { // make the call. func(token_context) } @@ -374,7 +374,7 @@ impl TokenProviderImpl { // this is unrecoverable. Err(ErrorKind::StorageResetError) } - TokenState::Backoff(ref remaining, _) => Err(ErrorKind::BackoffError(*remaining)), + TokenState::Backoff(remaining, _) => Err(ErrorKind::BackoffError(*remaining)), } } diff --git a/components/sync15/src/clients_engine/engine.rs b/components/sync15/src/clients_engine/engine.rs index 436afa5b9d..dd43b8c28f 100644 --- a/components/sync15/src/clients_engine/engine.rs +++ b/components/sync15/src/clients_engine/engine.rs @@ -11,14 +11,14 @@ use crate::client::{ }; use crate::client_types::{ClientData, RemoteClient}; use crate::engine::CollectionRequest; -use crate::error::{debug, info, warn, Result}; +use crate::error::{Result, debug, info, warn}; use crate::{Guid, KeyBundle}; use interrupt_support::Interruptee; use super::{ + CLIENTS_TTL, Command, CommandProcessor, CommandStatus, record::{ClientRecord, CommandRecord}, ser::shrink_to_fit, - Command, CommandProcessor, CommandStatus, CLIENTS_TTL, }; const COLLECTION_NAME: &str = "clients"; @@ -362,7 +362,7 @@ mod tests { use crate::bso::IncomingBso; use anyhow::Result; use interrupt_support::NeverInterrupts; - use serde_json::{json, Value}; + use serde_json::{Value, json}; use std::iter::zip; struct TestProcessor { diff --git a/components/sync15/src/device_type.rs b/components/sync15/src/device_type.rs index 8b4ed9593b..abe4068bc4 100644 --- a/components/sync15/src/device_type.rs +++ b/components/sync15/src/device_type.rs @@ -14,8 +14,10 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// /// Firefox Accounts and the broader Sync universe separates devices into broad categories for /// various purposes, such as distinguishing a desktop PC from a mobile phone. +/// Upon signin, the application should inspect the device it is running on and select an appropriate +/// [`DeviceType`] to include in its device registration record. /// -/// A special variant in this enum, `DeviceType::Unknown` is used to capture +/// A special variant in this enum, [`DeviceType::Unknown`] is used to capture /// the string values we don't recognise. It also has a custom serde serializer and deserializer /// which implements the following semantics: /// * deserializing a `DeviceType` which uses a string value we don't recognise or null will return @@ -32,7 +34,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// upload records with *this* device's type, not the type of other devices, and it's reasonable /// to assume that this module knows about all valid device types for the device type it is /// deployed on. -#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, uniffi::Enum)] pub enum DeviceType { Desktop, Mobile, diff --git a/components/sync15/src/engine/bridged_engine.rs b/components/sync15/src/engine/bridged_engine.rs index e1781eb2ec..6cb9c2ffa2 100644 --- a/components/sync15/src/engine/bridged_engine.rs +++ b/components/sync15/src/engine/bridged_engine.rs @@ -3,11 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::error::debug; -use crate::{telemetry, ServerTimestamp}; +use crate::{ServerTimestamp, telemetry}; use anyhow::Result; -use crate::bso::{IncomingBso, OutgoingBso}; use crate::Guid; +use crate::bso::{IncomingBso, OutgoingBso}; use super::{CollSyncIds, EngineSyncAssociation, SyncEngine}; diff --git a/components/sync15/src/engine/sync_engine.rs b/components/sync15/src/engine/sync_engine.rs index bc57e354d1..83b50b866e 100644 --- a/components/sync15/src/engine/sync_engine.rs +++ b/components/sync15/src/engine/sync_engine.rs @@ -5,7 +5,7 @@ use super::CollectionRequest; use crate::bso::{IncomingBso, OutgoingBso}; use crate::client_types::ClientData; -use crate::{telemetry, CollectionName, Guid, ServerTimestamp}; +use crate::{CollectionName, Guid, ServerTimestamp, telemetry}; use anyhow::Result; use std::fmt; diff --git a/components/sync15/src/key_bundle.rs b/components/sync15/src/key_bundle.rs index 2032c2e8f5..c8d6875270 100644 --- a/components/sync15/src/key_bundle.rs +++ b/components/sync15/src/key_bundle.rs @@ -2,10 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::error::{warn, Error, Result}; +use crate::error::{Error, Result, warn}; use base64::{ - engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}, Engine, + engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}, }; use rc_crypto::{ aead::{self, OpeningKey, SealingKey}, diff --git a/components/sync15/src/lib.rs b/components/sync15/src/lib.rs index 0a8cb9ef58..6a2694cd91 100644 --- a/components/sync15/src/lib.rs +++ b/components/sync15/src/lib.rs @@ -47,4 +47,4 @@ fn skip_if_default(v: &T) -> bool { *v == T::default() } -uniffi::include_scaffolding!("sync15"); +uniffi::setup_scaffolding!("sync15"); diff --git a/components/sync15/src/sync15.udl b/components/sync15/src/sync15.udl deleted file mode 100644 index 6837cbea3f..0000000000 --- a/components/sync15/src/sync15.udl +++ /dev/null @@ -1,21 +0,0 @@ -// # sync15 types - -// This exists purely to expose types used by other components. -namespace sync15 { - -}; - -/// Enumeration for the different types of device. -/// -/// Firefox Accounts separates devices into broad categories for display purposes, -/// such as distinguishing a desktop PC from a mobile phone. Upon signin, the -/// application should inspect the device it is running on and select an appropriate -/// [`DeviceType`] to include in its device registration record. -enum DeviceType { - "Desktop", - "Mobile", - "Tablet", - "VR", - "TV", - "Unknown", -}; diff --git a/components/sync15/src/telemetry.rs b/components/sync15/src/telemetry.rs index 6b0ab056eb..c4ce6897fa 100644 --- a/components/sync15/src/telemetry.rs +++ b/components/sync15/src/telemetry.rs @@ -13,7 +13,7 @@ use crate::error::warn; use std::collections::HashMap; use std::time; -use serde::{ser, Serialize, Serializer}; +use serde::{Serialize, Serializer, ser}; // A test helper, used by the many test modules below. #[cfg(test)] @@ -439,7 +439,7 @@ impl Engine { pub fn incoming(&mut self, inc: EngineIncoming) { match &mut self.incoming { None => self.incoming = Some(inc), - Some(ref mut existing) => existing.accum(&inc), + Some(existing) => existing.accum(&inc), }; } @@ -830,7 +830,7 @@ impl From<&Error> for SyncFailure { #[cfg(feature = "sync-client")] Error::BackoffError(_) => SyncFailure::Http { code: 503 }, #[cfg(feature = "sync-client")] - Error::StorageHttpError(ref e) => match e { + Error::StorageHttpError(e) => match e { ErrorResponse::NotFound { .. } => SyncFailure::Http { code: 404 }, ErrorResponse::Unauthorized { .. } => SyncFailure::Auth { from: "storage" }, ErrorResponse::PreconditionFailed { .. } => SyncFailure::Http { code: 412 }, @@ -838,16 +838,16 @@ impl From<&Error> for SyncFailure { ErrorResponse::RequestFailed { status, .. } => SyncFailure::Http { code: *status }, }, #[cfg(feature = "crypto")] - Error::CryptoError(ref e) => SyncFailure::Unexpected { + Error::CryptoError(e) => SyncFailure::Unexpected { error: e.to_string(), }, #[cfg(feature = "sync-client")] - Error::RequestError(ref e) => SyncFailure::Unexpected { + Error::RequestError(e) => SyncFailure::Unexpected { error: e.to_string(), }, #[cfg(feature = "sync-client")] - Error::UnexpectedStatus(ref e) => SyncFailure::Http { code: e.status }, - Error::Interrupted(ref e) => SyncFailure::Unexpected { + Error::UnexpectedStatus(e) => SyncFailure::Http { code: e.status }, + Error::Interrupted(e) => SyncFailure::Unexpected { error: e.to_string(), }, e => SyncFailure::Other {