servo/
network_manager.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::collections::HashSet;
6
7use net_traits::ResourceThreads;
8
9#[derive(Clone, Debug, PartialEq)]
10pub struct CacheEntry {
11    key: String,
12}
13
14impl CacheEntry {
15    pub fn new(key: String) -> Self {
16        Self { key }
17    }
18
19    pub fn key(&self) -> &str {
20        &self.key
21    }
22}
23
24/// Provides APIs for managing network-related state.
25///
26/// `NetworkManager` is responsible for data owned by the networking layer,
27/// such as the HTTP cache. This data is not considered site data and is
28/// therefore intentionally separate from `SiteDataManager`.
29pub struct NetworkManager {
30    public_resource_threads: ResourceThreads,
31    private_resource_threads: ResourceThreads,
32}
33
34impl NetworkManager {
35    pub(crate) fn new(
36        public_resource_threads: ResourceThreads,
37        private_resource_threads: ResourceThreads,
38    ) -> Self {
39        Self {
40            public_resource_threads,
41            private_resource_threads,
42        }
43    }
44
45    /// Returns cache entries currently stored in the HTTP cache.
46    ///
47    /// The returned list contains one [`CacheEntry`] per unique cache key
48    /// (URL) for which the networking layer currently maintains cached
49    /// responses.
50    ///
51    /// Both public and private browsing contexts are included in the result.
52    ///
53    /// Note: The networking layer currently only implements an in-memory HTTP
54    /// cache. Support for an on-disk cache is under development.
55    pub fn cache_entries(&self) -> Vec<CacheEntry> {
56        let public_entries = self.public_resource_threads.cache_entries();
57        let private_entries = self.private_resource_threads.cache_entries();
58
59        let unique_keys: HashSet<String> = public_entries
60            .into_iter()
61            .chain(private_entries)
62            .map(|entry| entry.key)
63            .collect();
64
65        unique_keys.into_iter().map(CacheEntry::new).collect()
66    }
67
68    /// Clears the network (HTTP) cache.
69    ///
70    /// This removes all cached network responses maintained by the networking
71    /// layer for both public and private browsing contexts.
72    ///
73    /// Note: The networking layer currently only implements an in-memory HTTP
74    /// cache. Support for an on-disk cache is under development.
75    pub fn clear_cache(&self) {
76        self.public_resource_threads.clear_cache();
77        self.private_resource_threads.clear_cache();
78    }
79}