1use super::*;
2use std::{future::Future, pin::Pin};
3
4pub(super) enum Outcome {
5 Read(Vec<u8>),
6 Stamp(Box<Stamp>),
7 Published,
8}
9
10pub(super) enum Pending {
11 Running(Pin<Box<dyn Future<Output = std::result::Result<Outcome, CommitError>>>>),
12 Ready(std::result::Result<Outcome, CommitError>),
13}
14
15fn uncommitted(error: io::Error) -> CommitError {
16 CommitError {
17 state: CommitState::NotCommitted,
18 error,
19 }
20}
21
22impl HostedRemote {
23 fn operation(
24 &mut self,
25 work: impl Future<Output = std::result::Result<Outcome, CommitError>> + 'static,
26 ) -> std::result::Result<Outcome, CommitError> {
27 match self.pending.take() {
28 Some(Pending::Ready(result)) => result,
29 pending => {
30 self.pending = Some(pending.unwrap_or_else(|| Pending::Running(Box::pin(work))));
31 Err(uncommitted(io::ErrorKind::WouldBlock.into()))
32 }
33 }
34 }
35
36 fn publication(
37 &mut self,
38 result: std::result::Result<Outcome, CommitError>,
39 ) -> std::result::Result<(), CommitError> {
40 match result {
41 Ok(Outcome::Published) => {
42 self.seen = None;
43 Ok(())
44 }
45 Ok(_) => Err(uncommitted(io::ErrorKind::InvalidInput.into())),
46 Err(error) => {
47 if error.error.kind() != io::ErrorKind::WouldBlock
48 && error.state == CommitState::NotCommitted
49 {
50 self.rejected = true;
51 self.guest.inner.current.lock().unwrap().remove(&self.path);
52 }
53 Err(error)
54 }
55 }
56 }
57}
58
59impl crate::Remote for HostedRemote {
60 fn pending(&mut self) -> Option<Pin<Box<dyn Future<Output = ()> + '_>>> {
61 let pending = self.pending.as_mut()?;
62 Some(Box::pin(async move {
63 if let Pending::Running(work) = pending {
64 *pending = Pending::Ready(work.await);
65 }
66 }))
67 }
68
69 fn read(&mut self) -> io::Result<Vec<u8>> {
70 let (guest, path, seen) = (self.guest.clone(), self.path.clone(), self.seen.clone());
71 let result = self
72 .operation(async move {
73 let image = match seen.as_ref().and_then(|stamp| guest.held(&path, stamp)) {
74 Some(image) => image,
75 None => guest
76 .read_async(kind::READ, &path, LIMIT)
77 .await
78 .map_err(uncommitted)?,
79 };
80 Ok(Outcome::Read(image))
81 })
82 .map_err(|error| error.error)?;
83 match result {
84 Outcome::Read(image) => {
85 self.rejected = false;
86 Ok(image)
87 }
88 _ => Err(io::ErrorKind::InvalidInput.into()),
89 }
90 }
91
92 fn stamp(&mut self) -> io::Result<Stamp> {
93 self.rejected = false;
94 let (guest, path) = (self.guest.clone(), self.path.clone());
95 let result = self
96 .operation(async move {
97 guest
98 .stamp_async(&path)
99 .await
100 .map(|stamp| Outcome::Stamp(Box::new(stamp)))
101 .map_err(uncommitted)
102 })
103 .map_err(|error| error.error)?;
104 match result {
105 Outcome::Stamp(stamp) => {
106 self.seen = Some((*stamp).clone());
107 Ok(*stamp)
108 }
109 _ => Err(io::ErrorKind::InvalidInput.into()),
110 }
111 }
112
113 fn accepts_edits(&self) -> bool {
114 !self.rejected
115 && self
116 .guest
117 .host()
118 .is_some_and(|host| host.ops == Some(1) && host.kinds.contains(&kind::EDITS))
119 }
120
121 fn publish_edits(
122 &mut self,
123 transaction: &Transaction,
124 edits: &[crate::PendingEdit],
125 revisions: &BTreeMap<onestore::ExGuid, onestore::ExGuid>,
126 ) -> std::result::Result<(), CommitError> {
127 let (guest, path, transaction, edits, revisions) = (
128 self.guest.clone(),
129 self.path.clone(),
130 transaction.clone(),
131 edits.to_vec(),
132 revisions.clone(),
133 );
134 let result = self.operation(async move {
135 guest
136 .edits_async(&path, &transaction, &edits, &revisions)
137 .await?;
138 Ok(Outcome::Published)
139 });
140 self.publication(result)
141 }
142
143 fn publish(&mut self, transaction: &Transaction) -> std::result::Result<(), CommitError> {
144 let (guest, path, transaction) =
145 (self.guest.clone(), self.path.clone(), transaction.clone());
146 let result = self.operation(async move {
147 guest.commit_async(&path, &transaction).await?;
148 guest.inner.published(&path, &transaction);
149 Ok(Outcome::Published)
150 });
151 self.publication(result)
152 }
153
154 fn confirm(&mut self, base: &Stamp) -> std::result::Result<(), CommitError> {
155 let (guest, path, base) = (self.guest.clone(), self.path.clone(), base.clone());
156 let result = self.operation(async move {
157 guest.confirm_async(&path, &base).await?;
158 Ok(Outcome::Published)
159 });
160 self.publication(result)
161 }
162}
163
164struct Cached<'a>(&'a Hosted, Listings);
165
166impl Guest {
167 pub(super) async fn cache_entries(
168 &self,
169 folder: &str,
170 entries: &[discover::Entry],
171 ) -> io::Result<()> {
172 let Some(listed) = self.inner.catalog.lock().unwrap().clone() else {
173 return Ok(());
174 };
175 let files = listed.with_extension("files");
176 let mut listings: Listings = crate::fs::read(&listed)
177 .ok()
178 .and_then(|bytes| serde_json::from_slice(&bytes).ok())
179 .unwrap_or_default();
180 let before = listings.get(folder).cloned().unwrap_or_default();
181 let mut current = Vec::with_capacity(entries.len());
182 crate::fs::create_dir_all(files.join(folder))?;
183 for entry in entries {
184 if entry.name.contains(['/', '\\', '\0']) || matches!(entry.name.as_str(), "." | "..") {
185 return Err(io::ErrorKind::InvalidData.into());
186 }
187 let e = wire_entry(entry);
188 let listed = (e.name, e.kind, e.size, e.modified);
189 let path = if folder.is_empty() {
190 entry.name.clone()
191 } else {
192 format!("{folder}/{}", entry.name)
193 };
194 if entry.kind == discover::EntryKind::File
195 && (!before.contains(&listed) || crate::fs::metadata(files.join(&path)).is_err())
196 {
197 let kind = if path.ends_with(".one") || path.ends_with(".onetoc2") {
198 kind::READ
199 } else {
200 kind::READ_FILE
201 };
202 let bytes = self.read_async(kind, &path, LIMIT).await?;
203 crate::fs::write(files.join(path), bytes)?;
204 }
205 current.push(listed);
206 }
207 // Other folders may have finished listing while these files were being read.
208 if let Ok(bytes) = crate::fs::read(&listed) {
209 listings = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
210 }
211 if listings.get(folder) != Some(&current) {
212 listings.insert(folder.to_owned(), current);
213 crate::fs::write(&listed, serde_json::to_vec(&listings)?)?;
214 crate::fs::durable().await?;
215 if let Some(reports) = &*self.inner.watch.lock().unwrap() {
216 reports.catalog(folder);
217 }
218 (self.inner.events)();
219 }
220 Ok(())
221 }
222}
223
224impl discover::Source for Cached<'_> {
225 fn entries(&mut self, path: &str, limit: usize) -> io::Result<Vec<discover::Entry>> {
226 let entries = self.1.get(path).ok_or(io::ErrorKind::NotConnected)?;
227 if entries.len() > limit {
228 return Err(io::ErrorKind::FileTooLarge.into());
229 }
230 Ok(entries
231 .iter()
232 .map(|(name, kind, size, modified)| {
233 entry(&WireEntry {
234 name: name.clone(),
235 kind: *kind,
236 size: *size,
237 modified: *modified,
238 })
239 })
240 .collect())
241 }
242 fn read(&mut self, path: &str, limit: usize) -> io::Result<Vec<u8>> {
243 let bytes = self
244 .0
245 .guest
246 .inner
247 .image(path)
248 .map(|image| image.to_vec())
249 .map(Ok)
250 .unwrap_or_else(|| crate::fs::read(self.0.files().join(path)))?;
251 if bytes.len() > limit {
252 return Err(io::ErrorKind::FileTooLarge.into());
253 }
254 Ok(bytes)
255 }
256 fn read_asset(&mut self, path: &str, limit: usize) -> io::Result<Vec<u8>> {
257 self.read(path, limit)
258 }
259}
260
261impl Hosted {
262 fn files(&self) -> PathBuf {
263 self.listed.with_extension("files")
264 }
265
266 /// Loads a bounded catalog and its files before the synchronous editor opens it.
267 pub async fn prepare(guest: Arc<Guest>, cache: &std::path::Path) -> io::Result<()> {
268 let listed =
269 crate::session::listing(cache, &guest.location()).with_extension("entries.json");
270 let hosted = Self::new(guest, listed);
271 let deadline = Instant::now() + Duration::from_secs(20);
272 let (_, waiting) = crate::task::channel();
273 while hosted.guest.host().is_none() {
274 if Instant::now() >= deadline {
275 return Err(hosted.guest.offline());
276 }
277 crate::task::wait(&waiting, Some(Duration::from_millis(50))).await;
278 }
279 let mut folders = vec![String::new()];
280 let mut count = 0;
281 while let Some(folder) = folders.pop() {
282 if folder.split('/').count() > 32 {
283 return Err(io::ErrorKind::FileTooLarge.into());
284 }
285 let entries = hosted.guest.entries_async(&folder).await?;
286 count += entries.len();
287 if count > 10000 {
288 return Err(io::ErrorKind::FileTooLarge.into());
289 }
290 crate::fs::create_dir_all(hosted.files().join(&folder))?;
291 for entry in &entries {
292 if entry.kind == discover::EntryKind::Directory {
293 folders.push(if folder.is_empty() {
294 entry.name.clone()
295 } else {
296 format!("{folder}/{}", entry.name)
297 });
298 }
299 }
300 }
301 crate::fs::durable().await
302 }
303}
304
305fn desktop() -> Error {
306 io::Error::new(
307 io::ErrorKind::Unsupported,
308 "Create and organize sections in desktop Snowbound.",
309 )
310 .into()
311}
312
313impl Storage for Hosted {
314 fn discover(
315 &self,
316 cache: &mut discover::Cache,
317 limits: discover::Limits,
318 ) -> Result<discover::Folder> {
319 let listings =
320 serde_json::from_slice(&crate::fs::read(&self.listed)?).map_err(io::Error::other)?;
321 Ok(cache.discover(&mut Cached(self, listings), limits)?)
322 }
323 fn location(&self) -> String {
324 self.guest.location()
325 }
326 fn entries(&self, path: &str) -> io::Result<Vec<discover::Entry>> {
327 let listings =
328 serde_json::from_slice(&crate::fs::read(&self.listed)?).map_err(io::Error::other)?;
329 discover::Source::entries(&mut Cached(self, listings), path, 10000)
330 }
331 fn exists(&self, path: &str) -> bool {
332 crate::fs::metadata(self.files().join(path)).is_ok()
333 }
334 fn stamp(&self, path: &str) -> io::Result<Stamp> {
335 Stamp::of(&self.read(path).map_err(io::Error::other)?).map_err(io::Error::other)
336 }
337 fn read(&self, path: &str) -> Result<Vec<u8>> {
338 self.read_file(path, LIMIT)
339 }
340 fn read_file(&self, path: &str, limit: usize) -> Result<Vec<u8>> {
341 Ok(discover::Source::read(
342 &mut Cached(self, Listings::new()),
343 path,
344 limit,
345 )?)
346 }
347 fn create(&self, _: &str, _: &[u8]) -> Result<()> {
348 Err(desktop())
349 }
350 fn create_directory(&self, _: &str) -> Result<()> {
351 Err(desktop())
352 }
353 fn hide(&self, _: &str) -> Result<()> {
354 Err(desktop())
355 }
356 fn rename(&self, _: &str, _: &str) -> Result<()> {
357 Err(desktop())
358 }
359 fn rename_root(&self, _: &str, _: &[String]) -> Result<String> {
360 Err(desktop())
361 }
362 fn replace(&self, _: &str, _: &str) -> Result<()> {
363 Err(desktop())
364 }
365 fn delete(&self, _: &str) -> Result<()> {
366 Err(desktop())
367 }
368 fn place(&self, _: &str, _: [u8; 16], _: &str) -> Result<()> {
369 Err(desktop())
370 }
371 fn commit(&self, _: &str, _: &Transaction) -> Result<()> {
372 Err(desktop())
373 }
374 fn confirm(&self, _: &str, _: &Stamp) -> std::result::Result<(), CommitError> {
375 Err(uncommitted(io::Error::new(
376 io::ErrorKind::Unsupported,
377 "Section management requires desktop Snowbound",
378 )))
379 }
380 fn supersede(&self, _: &str, _: &Stamp, _: &str) -> Result<()> {
381 Err(desktop())
382 }
383}