Skip to content

Commit 9e2e760

Browse files
committed
Make AddressCache backing non-dynamic, as per Markus' suggestion
1 parent d500f34 commit 9e2e760

File tree

4 files changed

+75
-80
lines changed

4 files changed

+75
-80
lines changed

mullvad-api/src/address_cache.rs

Lines changed: 42 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -30,18 +30,11 @@ pub enum Error {
3030
/// a backing store for an AddressCache.
3131
3232
#[async_trait]
33-
pub trait AddressCacheBacking: Sync + Send {
33+
pub trait AddressCacheBacking: 'static + Sync + Send + std::clone::Clone {
3434
async fn read(&self) -> Result<Vec<u8>, Error>;
3535
async fn write(&self, data: &[u8]) -> Result<(), Error>;
3636
}
3737

38-
// this should allow this to compile.
39-
impl Debug for dyn AddressCacheBacking {
40-
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
41-
write!(f, "[some AddressCacheBacking]")
42-
}
43-
}
44-
4538
#[derive(Clone)]
4639
pub struct FileAddressCacheBacking {
4740
read_path: Option<Arc<Path>>,
@@ -74,7 +67,7 @@ impl AddressCacheBacking for FileAddressCacheBacking {
7467

7568
/// A DNS resolver which resolves using `AddressCache`.
7669
#[async_trait]
77-
impl DnsResolver for AddressCache {
70+
impl<T: AddressCacheBacking> DnsResolver for AddressCache<T> {
7871
async fn resolve(&self, host: String) -> Result<Vec<SocketAddr>, io::Error> {
7972
self.resolve_hostname(&host)
8073
.await
@@ -84,69 +77,65 @@ impl DnsResolver for AddressCache {
8477
}
8578

8679
#[derive(Clone, Debug)]
87-
pub struct AddressCache {
80+
pub struct AddressCache<T>
81+
where
82+
T: Clone,
83+
{
8884
hostname: String,
8985
inner: Arc<Mutex<AddressCacheInner>>,
90-
backing: Arc<dyn AddressCacheBacking>,
86+
backing: Arc<T>,
9187
}
9288

93-
impl AddressCache {
94-
/// Initialise cache using a hardcoded address and a Backing for writing to
95-
pub fn new_with_address(endpoint: &ApiEndpoint, backing: Arc<dyn AddressCacheBacking>) -> Self {
96-
Self::new_inner(endpoint.address(), endpoint.host().to_owned(), backing)
89+
impl AddressCache<FileAddressCacheBacking> {
90+
/// Initialize cache using `read_path`, and write changes to `write_path`.
91+
pub async fn from_file(
92+
read_path: &Path,
93+
write_path: Option<Box<Path>>,
94+
hostname: String,
95+
) -> Result<AddressCache<FileAddressCacheBacking>, Error> {
96+
log::debug!("Loading API addresses from {}", read_path.display());
97+
let backing = FileAddressCacheBacking {
98+
read_path: Some(Arc::from(read_path)),
99+
write_path: write_path.map(Arc::from),
100+
};
101+
AddressCache::from_backing(hostname, Arc::new(backing)).await
97102
}
98103

99104
/// Initialize cache using the hardcoded address, and write changes to `write_path`.
100-
pub fn new(endpoint: &ApiEndpoint, write_path: Option<Box<Path>>) -> AddressCache {
101-
AddressCache::new_with_address(
102-
endpoint,
103-
Arc::new(FileAddressCacheBacking {
104-
read_path: None,
105-
write_path: write_path.map(Arc::from),
106-
}),
107-
)
105+
pub fn new(
106+
endpoint: &ApiEndpoint,
107+
write_path: Option<Box<Path>>,
108+
) -> AddressCache<FileAddressCacheBacking> {
109+
let backing = FileAddressCacheBacking {
110+
read_path: None,
111+
write_path: write_path.map(Arc::from),
112+
};
113+
AddressCache::new_with_address(endpoint, Arc::new(backing))
108114
}
115+
}
109116

110-
pub async fn from_backing(
111-
hostname: String,
112-
backing: Arc<dyn AddressCacheBacking>,
113-
) -> Result<Self, Error> {
114-
let address = read_address_backing(&backing).await?;
117+
impl<T: AddressCacheBacking + std::clone::Clone> AddressCache<T> {
118+
/// Initialise cache using a hardcoded address and a Backing for writing to
119+
pub fn new_with_address(endpoint: &ApiEndpoint, backing: Arc<T>) -> Self {
120+
Self::new_inner(endpoint.address(), endpoint.host().to_owned(), backing)
121+
}
122+
123+
pub async fn from_backing(hostname: String, backing: Arc<T>) -> Result<Self, Error> {
124+
let address = read_address_backing(backing.as_ref()).await?;
115125
Ok(Self::new_inner(address, hostname, backing))
116126
}
117127

118128
pub async fn from_backing_or(
119129
hostname: String,
120-
backing: Arc<dyn AddressCacheBacking>,
130+
backing: Arc<T>,
121131
endpoint: &ApiEndpoint,
122132
) -> Self {
123-
Self::from_backing(hostname.clone(), backing.clone())
133+
Self::from_backing(hostname.clone(), Arc::clone(&backing))
124134
.await
125135
.unwrap_or(Self::new_inner(endpoint.address(), hostname, backing))
126136
}
127137

128-
/// Initialize cache using `read_path`, and write changes to `write_path`.
129-
pub async fn from_file(
130-
read_path: &Path,
131-
write_path: Option<Box<Path>>,
132-
hostname: String,
133-
) -> Result<AddressCache, Error> {
134-
log::debug!("Loading API addresses from {}", read_path.display());
135-
AddressCache::from_backing(
136-
hostname,
137-
Arc::new(FileAddressCacheBacking {
138-
read_path: Some(Arc::from(read_path)),
139-
write_path: write_path.map(Arc::from),
140-
}),
141-
)
142-
.await
143-
}
144-
145-
fn new_inner(
146-
address: SocketAddr,
147-
hostname: String,
148-
backing: Arc<dyn AddressCacheBacking>,
149-
) -> Self {
138+
fn new_inner(address: SocketAddr, hostname: String, backing: Arc<T>) -> Self {
150139
let cache = AddressCacheInner::from_address(address);
151140
log::debug!("Using API address: {}", cache.address);
152141

@@ -201,9 +190,7 @@ impl AddressCacheInner {
201190
}
202191
}
203192

204-
async fn read_address_backing(
205-
backing: &Arc<dyn AddressCacheBacking + 'static>,
206-
) -> Result<SocketAddr, Error> {
193+
async fn read_address_backing(backing: &impl AddressCacheBacking) -> Result<SocketAddr, Error> {
207194
backing
208195
.read()
209196
.await

mullvad-api/src/lib.rs

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -311,9 +311,12 @@ impl DnsResolver for NullDnsResolver {
311311
}
312312

313313
/// A type that helps with the creation of API connections.
314-
pub struct Runtime {
314+
pub struct Runtime<B = FileAddressCacheBacking>
315+
where
316+
B: AddressCacheBacking,
317+
{
315318
handle: tokio::runtime::Handle,
316-
address_cache: AddressCache,
319+
address_cache: AddressCache<B>,
317320
api_availability: availability::ApiAvailability,
318321
endpoint: ApiEndpoint,
319322
#[cfg(target_os = "android")]
@@ -413,12 +416,29 @@ impl Runtime {
413416
})
414417
}
415418

419+
/// Returns a new request service handle
420+
pub fn rest_handle(&self, dns_resolver: impl DnsResolver) -> rest::RequestServiceHandle {
421+
self.new_request_service(
422+
ApiConnectionMode::Direct.into_provider(),
423+
Arc::new(dns_resolver),
424+
#[cfg(target_os = "android")]
425+
None,
426+
#[cfg(any(feature = "api-override", test))]
427+
false,
428+
)
429+
}
430+
}
431+
432+
impl<B: AddressCacheBacking> Runtime<B> {
416433
pub async fn with_cache_backing(
417434
handle: tokio::runtime::Handle,
418435
endpoint: &ApiEndpoint,
419-
backing: Arc<dyn AddressCacheBacking>,
436+
backing: Arc<B>,
420437
#[cfg(target_os = "android")] socket_bypass_tx: Option<mpsc::Sender<SocketBypassRequest>>,
421-
) -> Self {
438+
) -> Runtime<B>
439+
where
440+
B: AddressCacheBacking,
441+
{
422442
let address_cache =
423443
AddressCache::from_backing_or(endpoint.host().to_owned(), backing, endpoint).await;
424444
Runtime {
@@ -431,6 +451,10 @@ impl Runtime {
431451
}
432452
}
433453

454+
pub fn address_cache(&self) -> &AddressCache<B> {
455+
&self.address_cache
456+
}
457+
434458
/// Returns a request factory initialized to create requests for the master API Assumes an API
435459
/// endpoint that is constructed from env vars, or uses default values.
436460
pub fn mullvad_rest_handle<T: ConnectionModeProvider + 'static>(
@@ -452,18 +476,6 @@ impl Runtime {
452476
rest::MullvadRestHandle::new(service, factory, self.availability_handle())
453477
}
454478

455-
/// Returns a new request service handle
456-
pub fn rest_handle(&self, dns_resolver: impl DnsResolver) -> rest::RequestServiceHandle {
457-
self.new_request_service(
458-
ApiConnectionMode::Direct.into_provider(),
459-
Arc::new(dns_resolver),
460-
#[cfg(target_os = "android")]
461-
None,
462-
#[cfg(any(feature = "api-override", test))]
463-
false,
464-
)
465-
}
466-
467479
/// Creates a new request service and returns a handle to it.
468480
fn new_request_service<T: ConnectionModeProvider + 'static>(
469481
&self,
@@ -490,10 +502,6 @@ impl Runtime {
490502
pub fn availability_handle(&self) -> ApiAvailability {
491503
self.api_availability.clone()
492504
}
493-
494-
pub fn address_cache(&self) -> &AddressCache {
495-
&self.address_cache
496-
}
497505
}
498506

499507
#[derive(Clone)]

mullvad-ios/src/api_client/access_method_resolver.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ unsafe extern "C" {
2020
pub fn swift_read_address_cache() -> SwiftData;
2121
}
2222

23-
#[derive(Clone)]
23+
#[derive(Clone, Debug)]
2424
pub struct IOSAddressCacheBacking {}
2525

2626
#[async_trait]
@@ -42,7 +42,7 @@ pub struct SwiftAccessMethodResolver {
4242
domain: String,
4343
state: EncryptedDnsProxyState,
4444
bridge_provider: SwiftShadowsocksLoaderWrapper,
45-
address_cache: AddressCache,
45+
address_cache: AddressCache<IOSAddressCacheBacking>,
4646
}
4747

4848
impl SwiftAccessMethodResolver {
@@ -51,7 +51,7 @@ impl SwiftAccessMethodResolver {
5151
domain: String,
5252
state: EncryptedDnsProxyState,
5353
bridge_provider: SwiftShadowsocksLoaderWrapper,
54-
address_cache: AddressCache,
54+
address_cache: AddressCache<IOSAddressCacheBacking>,
5555
) -> Self {
5656
Self {
5757
endpoint,

mullvad-ios/src/api_client/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ impl SwiftApiContext {
5555
}
5656

5757
pub struct ApiContext {
58-
api_client: Runtime,
58+
api_client: Runtime<IOSAddressCacheBacking>,
5959
rest_client: MullvadRestHandle,
6060
access_mode_handler: AccessModeSelectorHandle,
6161
}
@@ -87,7 +87,7 @@ impl ApiContext {
8787
});
8888
}
8989

90-
pub fn address_cache(&self) -> &AddressCache {
90+
pub fn address_cache(&self) -> &AddressCache<IOSAddressCacheBacking> {
9191
self.api_client.address_cache()
9292
}
9393
}

0 commit comments

Comments
 (0)