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_storage::ResourceError;
6use mln_storage::offline::{
7    OfflineRegion, OfflineRegionDefinition, OfflineRegionDownloadState, OfflineRegionMetadata, OfflineRegionObserver,
8    OfflineRegionStatus,
9};
10use mln_storage_offline::DatabaseFileSourceExt;
11use mln_util::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_util::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    /// Selects the events that the runtime reports about a region's
93    /// download, from [`EventMask::ALL_RUNTIME_EVENTS`]. It replaces the
94    /// region's earlier selection, and [`EventMask::NONE`] stops them.
95    ///
96    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
97    /// mask with map events.
98    pub fn set_region_observed(&self, region_id: i64, events: EventMask) -> Result<Completion<()>, Error> {
99        if events.bits() & !EventMask::ALL_RUNTIME_EVENTS.bits() != 0 {
100            return Err(Error::invalid_argument("an offline region reports only runtime events"));
101        }
102        self.runtime.offline_command(move |database, core, resolver| {
103            let observer = (events != EventMask::NONE).then(|| -> Box<dyn OfflineRegionObserver + Send> {
104                Box::new(RegionObserver { region_id, events, queue: core.queue.clone() })
105            });
106            database.set_offline_region_observer(region_id, observer, reply_on(core.queue.clone(), resolver));
107        })
108    }
109
110    /// Starts or pauses a region's download.
111    pub fn set_region_download_state(
112        &self,
113        region_id: i64,
114        state: OfflineRegionDownloadState,
115    ) -> Result<Completion<()>, Error> {
116        self.runtime.offline_command(move |database, core, resolver| {
117            database.set_offline_region_download_state(region_id, state, reply_on(core.queue.clone(), resolver));
118        })
119    }
120
121    /// Makes maps check each resource of a region with its server before
122    /// they use it. The region keeps its resources.
123    pub fn invalidate_region(&self, region_id: i64) -> Result<Completion<()>, Error> {
124        self.runtime.offline_command(move |database, core, resolver| {
125            database.invalidate_offline_region(region_id, reply_on(core.queue.clone(), resolver));
126        })
127    }
128
129    /// Deletes a region, with the resources that no other region uses.
130    pub fn delete_region(&self, region_id: i64) -> Result<Completion<()>, Error> {
131        self.runtime.offline_command(move |database, core, resolver| {
132            database.delete_offline_region(region_id, reply_on(core.queue.clone(), resolver));
133        })
134    }
135}
136
137/// Checks that `path` names an existing file that opens for reading. SQLite would otherwise take an empty path, `:memory:` or a
138/// `file:` URI for an in-memory database, and create a missing file.
139fn check_side_database(path: &str) -> Result<(), Error> {
140    let unreadable = || Error::invalid_argument("side database path must name an existing readable database file");
141    if path.is_empty() || path.starts_with(':') || path.starts_with("file:") || !Path::new(path).is_file() {
142        return Err(unreadable());
143    }
144    std::fs::File::open(path).map(drop).map_err(|_| unreadable())
145}
146
147/// Sends an observed region's download events to the runtime's handler, on
148/// the runtime's thread.
149struct RegionObserver {
150    region_id: i64,
151    events: EventMask,
152    queue: CoreQueue,
153}
154
155impl RegionObserver {
156    fn send(&self, kind: RuntimeEventKind) {
157        if !self.events.contains(kind.event_type()) {
158            return;
159        }
160        let event = RuntimeEvent { source: EventSource::Runtime, kind };
161        post(&self.queue, move |core, outbox| core.send_events(vec![event], outbox));
162    }
163}
164
165impl OfflineRegionObserver for RegionObserver {
166    fn status_changed(&self, status: OfflineRegionStatus) {
167        self.send(RuntimeEventKind::OfflineRegionStatusChanged { region_id: self.region_id, status });
168    }
169
170    fn response_error(&self, error: ResourceError) {
171        self.send(RuntimeEventKind::OfflineRegionResponseError { region_id: self.region_id, error });
172    }
173}