Skip to main content

mln_runtime/
offline.rs

1//! The offline regions in a runtime's cache database.
2
3use std::path::Path;
4
5use mln_engine::offline::DatabaseFileSourceExt;
6use mln_engine::storage::ResourceError;
7use mln_engine::storage::offline::{
8    OfflineRegion, OfflineRegionDefinition, OfflineRegionDownloadState, OfflineRegionExpiry, OfflineRegionMetadata,
9    OfflineRegionObserver, OfflineRegionStatus,
10};
11use mln_style::error::Error;
12
13use crate::completion::Completion;
14use crate::event::{EventMask, EventSource, RuntimeEvent, RuntimeEventKind};
15use crate::runtime::{CoreQueue, Runtime, post, reply_on};
16
17/// The offline regions in a runtime's cache database, from
18/// [`Runtime::offline`]. Each call is a command of the runtime, and the
19/// regions download on the database's thread.
20pub struct Offline<'a> {
21    runtime: &'a Runtime,
22}
23
24impl<'a> Offline<'a> {
25    pub(crate) fn new(runtime: &'a Runtime) -> Self {
26        Offline { runtime }
27    }
28
29    /// Creates a region. It doesn't download until
30    /// [`set_region_download_state`](Self::set_region_download_state) starts
31    /// it.
32    pub fn create_region(
33        &self,
34        definition: OfflineRegionDefinition,
35        metadata: OfflineRegionMetadata,
36    ) -> Result<Completion<OfflineRegion>, Error> {
37        self.runtime.offline_command(move |database, core, resolver| {
38            database.create_offline_region(&definition, &metadata, reply_on(core.queue.clone(), resolver));
39        })
40    }
41
42    /// The region `region_id`, or `None` when the database has none.
43    pub fn region(&self, region_id: i64) -> Result<Completion<Option<OfflineRegion>>, Error> {
44        self.runtime.offline_command(move |database, core, resolver| {
45            database.get_offline_region(region_id, reply_on(core.queue.clone(), resolver));
46        })
47    }
48
49    /// Every region in the database.
50    pub fn regions(&self) -> Result<Completion<Vec<OfflineRegion>>, Error> {
51        self.runtime.offline_command(move |database, core, resolver| {
52            database.list_offline_regions(reply_on(core.queue.clone(), resolver));
53        })
54    }
55
56    /// Copies the regions of another cache database into this one, and gives
57    /// this database's copy of each. A region that this database has already
58    /// isn't copied again. The other database only needs to be readable.
59    ///
60    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) when
61    /// `side_database_path` names no database file that opens for reading.
62    /// That check opens the file on the calling thread.
63    pub fn merge_regions(
64        &self,
65        side_database_path: impl Into<String>,
66    ) -> Result<Completion<Vec<OfflineRegion>>, Error> {
67        let side_database_path = side_database_path.into();
68        check_side_database(&side_database_path)?;
69        self.runtime.offline_command(move |database, core, resolver| {
70            database.merge_offline_regions(&side_database_path, reply_on(core.queue.clone(), resolver));
71        })
72    }
73
74    /// Replaces a region's metadata, and gives the updated region.
75    pub fn update_region_metadata(
76        &self,
77        region_id: i64,
78        metadata: OfflineRegionMetadata,
79    ) -> Result<Completion<OfflineRegion>, Error> {
80        self.runtime.offline_command(move |database, core, resolver| {
81            database.update_offline_metadata(region_id, &metadata, reply_on(core.queue.clone(), resolver));
82        })
83    }
84
85    /// A region's download progress.
86    pub fn region_status(&self, region_id: i64) -> Result<Completion<OfflineRegionStatus>, Error> {
87        self.runtime.offline_command(move |database, core, resolver| {
88            database.get_offline_region_status(region_id, reply_on(core.queue.clone(), resolver));
89        })
90    }
91
92    /// How long a region's stored resources stay usable. Before
93    /// [`usable_offline_until`](OfflineRegionExpiry::usable_offline_until), a
94    /// download refreshes them.
95    pub fn region_expiry(&self, region_id: i64) -> Result<Completion<OfflineRegionExpiry>, Error> {
96        self.runtime.offline_command(move |database, core, resolver| {
97            database.get_offline_region_expiry(region_id, reply_on(core.queue.clone(), resolver));
98        })
99    }
100
101    /// Selects the events that the runtime reports about a region's
102    /// download, from [`EventMask::ALL_RUNTIME_EVENTS`]. It replaces the
103    /// region's earlier selection, and [`EventMask::NONE`] stops them.
104    ///
105    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
106    /// mask with map events.
107    pub fn set_region_observed(&self, region_id: i64, events: EventMask) -> Result<Completion<()>, Error> {
108        if events.bits() & !EventMask::ALL_RUNTIME_EVENTS.bits() != 0 {
109            return Err(Error::invalid_argument("an offline region reports only runtime events"));
110        }
111        self.runtime.offline_command(move |database, core, resolver| {
112            let observer = (events != EventMask::NONE).then(|| -> Box<dyn OfflineRegionObserver + Send> {
113                Box::new(RegionObserver { region_id, events, queue: core.queue.clone() })
114            });
115            database.set_offline_region_observer(region_id, observer, reply_on(core.queue.clone(), resolver));
116        })
117    }
118
119    /// Starts or pauses a region's download. A download fetches the
120    /// resources the region lacks, and revalidates those that are stale.
121    pub fn set_region_download_state(
122        &self,
123        region_id: i64,
124        state: OfflineRegionDownloadState,
125    ) -> Result<Completion<()>, Error> {
126        self.runtime.offline_command(move |database, core, resolver| {
127            database.set_offline_region_download_state(region_id, state, reply_on(core.queue.clone(), resolver));
128        })
129    }
130
131    /// Makes each resource of a region stale, so maps check it with its
132    /// server when they next use it, and the region's next download
133    /// refreshes them all. The region keeps its resources, which stay usable
134    /// unless their server requires checking them first.
135    pub fn invalidate_region(&self, region_id: i64) -> Result<Completion<()>, Error> {
136        self.runtime.offline_command(move |database, core, resolver| {
137            database.invalidate_offline_region(region_id, reply_on(core.queue.clone(), resolver));
138        })
139    }
140
141    /// Deletes a region, with the resources that no other region uses.
142    pub fn delete_region(&self, region_id: i64) -> Result<Completion<()>, Error> {
143        self.runtime.offline_command(move |database, core, resolver| {
144            database.delete_offline_region(region_id, reply_on(core.queue.clone(), resolver));
145        })
146    }
147}
148
149/// Checks that `path` names an existing file that opens for reading. SQLite would otherwise take an empty path, `:memory:` or a
150/// `file:` URI for an in-memory database, and create a missing file.
151fn check_side_database(path: &str) -> Result<(), Error> {
152    let unreadable = || Error::invalid_argument("side database path must name an existing readable database file");
153    if path.is_empty() || path.starts_with(':') || path.starts_with("file:") || !Path::new(path).is_file() {
154        return Err(unreadable());
155    }
156    std::fs::File::open(path).map(drop).map_err(|_| unreadable())
157}
158
159/// Sends an observed region's download events to the runtime's handler, on
160/// the runtime's thread.
161struct RegionObserver {
162    region_id: i64,
163    events: EventMask,
164    queue: CoreQueue,
165}
166
167impl RegionObserver {
168    fn send(&self, kind: RuntimeEventKind) {
169        if !self.events.contains(kind.event_type()) {
170            return;
171        }
172        let event = RuntimeEvent { source: EventSource::Runtime, kind };
173        post(&self.queue, move |core, outbox| core.send_events(vec![event], outbox));
174    }
175}
176
177impl OfflineRegionObserver for RegionObserver {
178    fn status_changed(&self, status: OfflineRegionStatus) {
179        self.send(RuntimeEventKind::OfflineRegionStatusChanged { region_id: self.region_id, status });
180    }
181
182    fn response_error(&self, error: ResourceError) {
183        self.send(RuntimeEventKind::OfflineRegionResponseError { region_id: self.region_id, error });
184    }
185}