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