1use super::*;
2use crate::{
3 resolve::{Merged, Version},
4 working::{Request, Sealed},
5};
6use onestore::{CommitError, CommitState, RevisionIndex, Stamp, Store, Transaction};
7use rusqlite::OptionalExtension;
8use std::{
9 collections::BTreeMap,
10 sync::{MutexGuard, TryLockError},
11};
12
13/// A single remote file with fresh reads and native-compatible guarded publication.
14/// Errors retain publication state; confirmation checks the stamp, flushes, and notifies
15/// cached readers.
16pub trait Remote {
17 /// Completes a non-blocking operation that returned `WouldBlock`; retrying that
18 /// operation then takes its result. Blocking providers leave this absent.
19 fn pending(&mut self) -> Option<std::pin::Pin<Box<dyn Future<Output = ()> + '_>>> {
20 None
21 }
22 fn read(&mut self) -> io::Result<Vec<u8>>;
23 /// The file's stamp without reading its body or coordinating with writers. While it is
24 /// the last observed image's, synchronization neither reads nor revalidates the file.
25 fn stamp(&mut self) -> io::Result<Stamp>;
26 fn publish(&mut self, transaction: &Transaction) -> std::result::Result<(), CommitError>;
27 fn accepts_edits(&self) -> bool {
28 false
29 }
30 /// Where the remote accepts edits, a batch published again with the same revisions, or
31 /// a protected section's transaction published again, however its first attempt ended,
32 /// lands at most once; one refused as `StaleNetworkFileHandle` has landed if the image
33 /// holds its revisions, and else never can, as the remote no longer holds its base.
34 fn publish_edits(
35 &mut self,
36 transaction: &Transaction,
37 edits: &[PendingEdit],
38 revisions: &BTreeMap<ExGuid, ExGuid>,
39 ) -> std::result::Result<(), CommitError> {
40 let _ = (edits, revisions);
41 self.publish(transaction)
42 }
43 /// Confirms that the file still has `base`'s stamp and is durable (`onestore::confirm`).
44 fn confirm(&mut self, base: &Stamp) -> std::result::Result<(), CommitError>;
45 /// The versions a file provider keeps beside the file, as iCloud Drive keeps the commits
46 /// that lost to another device's (unresolved conflict versions); none by default.
47 /// Synchronization merges each into the file, then retires it, so none are listed while
48 /// the file is a copy the provider has yet to replace with a newer one.
49 fn versions(&mut self) -> io::Result<Vec<Version>> {
50 Ok(Vec::new())
51 }
52 /// A version's image.
53 fn version(&mut self, id: &str) -> io::Result<Vec<u8>> {
54 Err(io::Error::new(
55 io::ErrorKind::NotFound,
56 format!("No version {id}"),
57 ))
58 }
59 /// Retires a version the file now holds everything of; with `keep`, one that is another
60 /// section or cannot be read, kept first as a file of its own beside this one.
61 fn retire(&mut self, id: &str, keep: bool) -> io::Result<()> {
62 let _ = (id, keep);
63 Ok(())
64 }
65}
66
67pub(crate) trait Waiting {
68 fn waiting(&self) -> bool;
69}
70
71impl Waiting for io::Error {
72 fn waiting(&self) -> bool {
73 self.kind() == io::ErrorKind::WouldBlock
74 }
75}
76
77impl Waiting for CommitError {
78 fn waiting(&self) -> bool {
79 self.error.kind() == io::ErrorKind::WouldBlock
80 }
81}
82
83pub(crate) async fn awaited<R: Remote, T, E: Waiting>(
84 remote: &mut R,
85 mut operation: impl FnMut(&mut R) -> std::result::Result<T, E>,
86) -> std::result::Result<T, E> {
87 loop {
88 let result = operation(remote);
89 if result.as_ref().is_err_and(Waiting::waiting)
90 && let Some(pending) = remote.pending()
91 {
92 pending.await;
93 continue;
94 }
95 return result;
96 }
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum EditStatus {
101 Pending,
102 /// Retained publication attempt; this revision alone may be insufficient to confirm it.
103 AwaitingConfirmation {
104 revision: ExGuid,
105 },
106 /// Historical confirmation; later remote edits or restores may remove the effect.
107 Published {
108 revision: ExGuid,
109 },
110 /// Retired unpublished by a reviewed release; the archive at this path holds the
111 /// edit, its attempt evidence and both images.
112 Archived {
113 archive: String,
114 },
115}
116
117/// What one synchronization step did: the state its batch reached, named by the batch's
118/// newest edit, and the pages a remote change replaced.
119#[derive(Debug, Clone, Default, PartialEq, Eq)]
120pub struct Synced {
121 pub edit: Option<(u64, EditStatus)>,
122 pub changed: Vec<ExGuid>,
123}
124
125/// The queue as a synchronization step starts it.
126struct State {
127 base: Stamp,
128 /// The observed remote image's stamp while it is not the base.
129 remote: Option<Stamp>,
130 /// The first batch waiting on a remote answer to an attempt.
131 blocked: Option<Blocked>,
132 queued: bool,
133}
134
135struct Blocked {
136 batch: i64,
137 revisions: Option<BTreeMap<ExGuid, ExGuid>>,
138}
139
140fn state(connection: &Connection) -> Result<State> {
141 let base = base::base_stamp(connection)?;
142 let blocked = connection
143 .query_row(
144 "SELECT id, revisions FROM batches WHERE attempted=1 ORDER BY id LIMIT 1",
145 [],
146 |row| Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(1)?)),
147 )
148 .optional()?
149 .map(|(batch, revisions)| {
150 Ok::<_, Error>(Blocked {
151 batch,
152 revisions: revisions
153 .map(|revisions| decode_revisions(&revisions))
154 .transpose()?,
155 })
156 })
157 .transpose()?;
158 Ok(State {
159 base,
160 remote: base::stamp(connection, base::Image::Remote)?,
161 blocked,
162 queued: connection
163 .query_row("SELECT EXISTS(SELECT 1 FROM batches)", [], |row| row.get(0))?,
164 })
165}
166
167fn decode_revisions(encoded: &str) -> Result<BTreeMap<ExGuid, ExGuid>> {
168 let revisions: BTreeMap<ExGuid, ExGuid> = serde_json::from_str(encoded)
169 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
170 if revisions
171 .iter()
172 .any(|(space, revision)| space.guid == [0; 16] || revision.guid == [0; 16])
173 {
174 return Err(io::Error::new(
175 io::ErrorKind::InvalidData,
176 "Cached publication evidence is incomplete",
177 )
178 .into());
179 }
180 Ok(revisions)
181}
182
183/// The revision a batch's seal stored for the first page an edit changes.
184fn revision_of(edit: &onestore::op::Edit, revisions: &BTreeMap<ExGuid, ExGuid>) -> Result<ExGuid> {
185 edit.ops
186 .iter()
187 .find_map(|op| match op {
188 onestore::op::Op::Page { space, .. } => revisions.get(space),
189 onestore::op::Op::Section(_) => None,
190 })
191 .or_else(|| revisions.values().next())
192 .copied()
193 .ok_or_else(|| {
194 io::Error::new(
195 io::ErrorKind::InvalidData,
196 "Cached publication evidence is incomplete",
197 )
198 .into()
199 })
200}
201
202/// The newest edit of a batch.
203fn newest(connection: &Connection, batch: i64) -> Result<u64> {
204 unsigned(
205 connection.query_row("SELECT max(id) FROM edits WHERE batch=?1", [batch], |row| {
206 row.get(0)
207 })?,
208 )
209}
210
211impl Replica {
212 /// Returns a durable receipt or the persisted state of a locally acknowledged edit.
213 pub fn status(&self, id: u64) -> Result<Option<EditStatus>> {
214 status(&*self.lock()?, id, self.section.key.as_ref())
215 }
216
217 /// The last observed remote image. Observation alone does not acknowledge any pending
218 /// edit's remote durability.
219 pub(crate) fn remote_snapshot(&self) -> Result<Vec<u8>> {
220 let connection = self.lock()?;
221 match base::read(&connection, base::Image::Remote)? {
222 Some(image) => Ok(image),
223 None => base::base(&connection),
224 }
225 }
226
227 /// Publishes the oldest unpublished batch, rebasing the queue first when the remote
228 /// changed. Reads the remote image only when its stamp moved; network I/O holds
229 /// synchronization ownership without holding the cache mutex. Uncertain attempts are
230 /// replayed only to a remote that accepts edits.
231 /// Versions the remote keeps beside the file merge into it first, each published as one
232 /// more revision and then retired (`resolve.rs`).
233 pub fn sync_once(&self, remote: &mut impl Remote) -> Result<Synced> {
234 crate::task::ready(self.sync_once_async(remote))?
235 }
236
237 /// The same guarded synchronization step, awaiting non-blocking remote operations.
238 pub async fn sync_once_async(&self, remote: &mut impl Remote) -> Result<Synced> {
239 let result = self.sync_once_inner(remote).await;
240 let durable = crate::fs::durable().await;
241 let synced = result?;
242 durable?;
243 Ok(synced)
244 }
245
246 /// Ownership uses `try_lock`; the cache mutex is released before every await.
247 #[allow(clippy::await_holding_lock)]
248 async fn sync_once_inner(&self, remote: &mut impl Remote) -> Result<Synced> {
249 let _owner = self.sync_owner()?;
250 for version in awaited(remote, Remote::versions)
251 .await
252 .map_err(Error::RemoteIo)?
253 {
254 let image = awaited(remote, |remote| remote.version(&version.id))
255 .await
256 .map_err(Error::RemoteIo)?;
257 let current = awaited(remote, Remote::read)
258 .await
259 .map_err(Error::RemoteIo)?;
260 // The file is this very version: a copy the provider has yet to replace, whatever it
261 // reports, so the version is kept for the file that replaces it.
262 if current == image {
263 continue;
264 }
265 let device = version.device.as_deref().unwrap_or("Another device");
266 let keep = match crate::resolve::merge(&current, &image, device) {
267 Ok(Merged::Held) => false,
268 Ok(Merged::Publish(transaction)) => {
269 awaited(remote, |remote| remote.publish(&transaction)).await?;
270 false
271 }
272 // A version this cannot merge is retired to be kept whole, never lost.
273 Ok(Merged::Foreign) | Err(Error::Document(_) | Error::Rejected(_)) => true,
274 Err(error) => return Err(error),
275 };
276 awaited(remote, |remote| remote.retire(&version.id, keep))
277 .await
278 .map_err(Error::RemoteIo)?;
279 }
280 let state = state(&*self.lock()?)?;
281 let batched = self.section.key.is_none()
282 && state.queued
283 && state.blocked.is_none()
284 && remote.accepts_edits();
285 let observed = awaited(remote, Remote::stamp)
286 .await
287 .map_err(Error::RemoteIo)?;
288 let replay = match &state.blocked {
289 Some(blocked) if remote.accepts_edits() => working::sealed(&*self.lock()?)?
290 .filter(|sealed| sealed.batch == blocked.batch)
291 .and_then(|sealed| sealed.transaction),
292 _ => None,
293 };
294 if let (Some(blocked), Some(transaction)) = (&state.blocked, replay) {
295 return self
296 .publish_sealed(remote, blocked.batch, transaction, true, true, Vec::new())
297 .await;
298 }
299 if let Some(blocked) = &state.blocked
300 && observed == *state.remote.as_ref().unwrap_or(&state.base)
301 {
302 // Nothing new to decide: the remote is as it was when the batch blocked.
303 let id = newest(&*self.lock()?, blocked.batch)?;
304 return Ok(Synced {
305 edit: Some((
306 id,
307 status(&*self.lock()?, id, self.section.key.as_ref())?
308 .unwrap_or(EditStatus::Pending),
309 )),
310 changed: Vec::new(),
311 });
312 }
313 let image = match observed {
314 observed if observed == state.base || batched => None,
315 _ => {
316 let image = awaited(remote, Remote::read)
317 .await
318 .map_err(Error::RemoteIo)?;
319 // Protected elsewhere: a section written anew, which only its key reads.
320 if self.section.key.is_none() && crate::discover::locked(&Store::parse(&image)?) {
321 return Err(Error::RemoteIo(io::Error::new(
322 io::ErrorKind::Unsupported,
323 "Password protected",
324 )));
325 }
326 // A read image is compared whole: a stamp stands for it only when read alone.
327 (base::base(&*self.lock()?)? != image).then_some(image)
328 }
329 };
330 let mut changed = Vec::new();
331 if let Some(image) = image {
332 if let Some(Blocked { batch, revisions }) = &state.blocked {
333 let id = newest(&*self.lock()?, *batch)?;
334 let revisions = revisions.clone().unwrap_or_default();
335 let store = Store::parse(&image)?;
336 if !store.checksum_mismatches.is_empty() {
337 return Err(io::Error::new(
338 io::ErrorKind::InvalidData,
339 "Notebook transaction checksum damage",
340 )
341 .into());
342 }
343 let index = RevisionIndex::parse(&store)?;
344 index.validate_current()?;
345 if index.root != self.root {
346 return Err(io::Error::new(
347 io::ErrorKind::InvalidInput,
348 "Remote snapshot belongs to another document",
349 )
350 .into());
351 }
352 let observed = revisions.iter().all(|(space, revision)| {
353 index
354 .spaces
355 .get(space)
356 .is_some_and(|space| space.revisions.contains_key(revision))
357 });
358 let sealed = working::sealed(&*self.lock()?)?
359 .filter(|sealed| sealed.batch == *batch)
360 .and_then(|sealed| sealed.transaction);
361 // Without its revisions the attempt still counts once the remote holds
362 // every page it changed as it changed them; its receipts then name the
363 // remote's revisions.
364 let receipts = if observed {
365 None
366 } else {
367 let equal = self.holds(&image, sealed.as_ref(), &revisions)?;
368 if !equal {
369 base::write(&*self.lock()?, base::Image::Remote, &image)?;
370 return Ok(Synced {
371 edit: Some((
372 id,
373 status(&*self.lock()?, id, self.section.key.as_ref())?
374 .unwrap_or(EditStatus::Pending),
375 )),
376 changed,
377 });
378 }
379 Some(
380 revisions
381 .keys()
382 .filter_map(|space| Some((*space, index.active(*space).ok()?)))
383 .collect(),
384 )
385 };
386 let stamp = Stamp::of(&image)?;
387 if let Err(error) = awaited(remote, |remote| remote.confirm(&stamp)).await {
388 if error.state == CommitState::Committed {
389 self.acknowledge(*batch, sealed.as_ref(), receipts.as_ref())?;
390 }
391 return Err(error.into());
392 }
393 self.acknowledge(*batch, sealed.as_ref(), receipts.as_ref())?;
394 let revision = self.receipt(id)?;
395 changed = self.rebase(Some(image))?;
396 return Ok(Synced {
397 edit: Some((id, EditStatus::Published { revision })),
398 changed,
399 });
400 }
401 changed = self.rebase(Some(image))?;
402 } else if let Some(blocked) = &state.blocked {
403 if state.remote.is_some() {
404 // The remote is back at the base: what blocked the queue is gone.
405 base::clear(&*self.lock()?, base::Image::Remote)?;
406 }
407 let id = newest(&*self.lock()?, blocked.batch)?;
408 return Ok(Synced {
409 edit: Some((
410 id,
411 status(&*self.lock()?, id, self.section.key.as_ref())?
412 .unwrap_or(EditStatus::Pending),
413 )),
414 changed,
415 });
416 } else if !state.queued {
417 return Ok(Synced::default());
418 }
419 // The cache lock is released before the section thread, which takes it, seals.
420 let waiting = working::sealed(&*self.lock()?)?;
421 let sealed = match waiting {
422 Some(sealed) => {
423 if sealed.transaction.is_some() {
424 self.lock()?
425 .execute("UPDATE batches SET attempted=1 WHERE id=?1", [sealed.batch])?;
426 }
427 Some(sealed)
428 }
429 None => self.ask(|reply| Request::Seal { reply })?,
430 };
431 let Some(Sealed { batch, transaction }) = sealed else {
432 return Ok(Synced {
433 edit: None,
434 changed,
435 });
436 };
437 let Some(transaction) = transaction else {
438 let id = newest(&*self.lock()?, batch)?;
439 // Edits that changed nothing are published once the remote's image is durable.
440 let base = base::base_stamp(&*self.lock()?)?;
441 if let Err(error) = awaited(remote, |remote| remote.confirm(&base)).await {
442 if error.state == CommitState::Committed {
443 self.acknowledge(batch, None, None)?;
444 }
445 return Err(error.into());
446 }
447 self.acknowledge(batch, None, None)?;
448 let revision = self.receipt(id)?;
449 return Ok(Synced {
450 edit: Some((id, EditStatus::Published { revision })),
451 changed,
452 });
453 };
454 if let Err(error) = crate::fs::durable().await {
455 self.lock()?
456 .execute("UPDATE batches SET attempted=0 WHERE id=?1", [batch])?;
457 return Err(error.into());
458 }
459 self.publish_sealed(remote, batch, transaction, batched, false, changed)
460 .await
461 }
462
463 /// Publishes the attempted `batch` sealed as `transaction`, rebasing on the remote's
464 /// image after where `batched`; `changed` holds the pages a rebase already changed. An
465 /// attempt made `again` stays uncertain until the remote takes it, as the first may
466 /// still land. A batch whose base the remote refuses for good is acknowledged where the
467 /// remote's image holds it, else rebased onto that image.
468 async fn publish_sealed(
469 &self,
470 remote: &mut impl Remote,
471 batch: i64,
472 transaction: Transaction,
473 batched: bool,
474 again: bool,
475 mut changed: Vec<ExGuid>,
476 ) -> Result<Synced> {
477 let id = newest(&*self.lock()?, batch)?;
478 let published = if self.section.key.is_none() && remote.accepts_edits() {
479 let (edits, revisions) = {
480 let connection = self.lock()?;
481 let edits = queue::load(&connection, None, Some(batch))?;
482 let revisions = decode_revisions(&connection.query_row(
483 "SELECT revisions FROM batches WHERE id=?1",
484 [batch],
485 |row| row.get::<_, String>(0),
486 )?)?;
487 (edits, revisions)
488 };
489 awaited(remote, |remote| {
490 remote.publish_edits(&transaction, &edits, &revisions)
491 })
492 .await
493 } else {
494 awaited(remote, |remote| remote.publish(&transaction)).await
495 };
496 match published {
497 Ok(()) => {}
498 Err(error)
499 if error.state == CommitState::NotCommitted
500 && error.error.kind() == io::ErrorKind::StaleNetworkFileHandle =>
501 {
502 let image = awaited(remote, Remote::read)
503 .await
504 .map_err(Error::RemoteIo)?;
505 // A whole commit made uncertain may have landed before the one refused.
506 let revisions = decode_revisions(&self.lock()?.query_row(
507 "SELECT revisions FROM batches WHERE id=?1",
508 [batch],
509 |row| row.get::<_, String>(0),
510 )?)?;
511 let store = Store::parse(&image)?;
512 let index = RevisionIndex::parse(&store)?;
513 if revisions.iter().all(|(space, revision)| {
514 (index.spaces.get(space))
515 .is_some_and(|space| space.revisions.contains_key(revision))
516 }) {
517 self.acknowledge(batch, Some(&transaction), None)?;
518 let revision = self.receipt(id)?;
519 return Ok(Synced {
520 edit: Some((id, EditStatus::Published { revision })),
521 changed: self.rebase(Some(image))?,
522 });
523 }
524 self.lock()?
525 .execute("UPDATE batches SET attempted=0 WHERE id=?1", [batch])?;
526 self.rebase(Some(image))?;
527 return Err(error.into());
528 }
529 Err(error) if error.state == CommitState::NotCommitted && !again => {
530 self.lock()?
531 .execute("UPDATE batches SET attempted=0 WHERE id=?1", [batch])?;
532 return Err(error.into());
533 }
534 Err(error) if error.state == CommitState::Committed => {
535 self.acknowledge(batch, Some(&transaction), None)?;
536 return Err(error.into());
537 }
538 Err(error) => return Err(error.into()),
539 }
540 self.acknowledge(batch, Some(&transaction), None)?;
541 let revision = self.receipt(id)?;
542 if batched {
543 changed.extend(
544 self.rebase(Some(
545 awaited(remote, Remote::read)
546 .await
547 .map_err(Error::RemoteIo)?,
548 ))?,
549 );
550 changed.sort();
551 changed.dedup();
552 }
553 Ok(Synced {
554 edit: Some((id, EditStatus::Published { revision })),
555 changed,
556 })
557 }
558
559 /// Whether `image` holds every page in `revisions` as the base with `sealed` has it.
560 fn holds(
561 &self,
562 image: &[u8],
563 sealed: Option<&Transaction>,
564 revisions: &BTreeMap<ExGuid, ExGuid>,
565 ) -> Result<bool> {
566 let base = base::base(&*self.lock()?)?;
567 let (local, remote) = (onestore::Arena::default(), onestore::Arena::default());
568 let mut local = working::open(&local, base, self.section.key.as_ref())?;
569 if let Some(sealed) = sealed {
570 local.replay(sealed)?;
571 }
572 let mut remote = working::open(&remote, image.to_vec(), self.section.key.as_ref())?;
573 // A page's versions change without its page changing.
574 let versions = |section: &mut onestore::Section<'_>| {
575 section.versions().map(|versions| {
576 versions
577 .into_iter()
578 .filter(|(page, _)| revisions.contains_key(page))
579 .collect::<Vec<_>>()
580 })
581 };
582 Ok(revisions.keys().all(
583 |space| matches!((local.page(*space), remote.page(*space)), (Ok(a), Ok(b)) if a == b),
584 ) && versions(&mut local)? == versions(&mut remote)?)
585 }
586
587 /// Asks the section thread to replay the queue on `image`, returning the pages the
588 /// remote changed.
589 fn rebase(&self, image: Option<Vec<u8>>) -> Result<Vec<ExGuid>> {
590 self.ask(|reply| Request::Rebase { image, reply })
591 }
592
593 fn receipt(&self, id: u64) -> Result<ExGuid> {
594 match status(&*self.lock()?, id, self.section.key.as_ref())? {
595 Some(EditStatus::Published { revision }) => Ok(revision),
596 _ => Err(io::Error::other("A published edit has no receipt").into()),
597 }
598 }
599
600 /// Records a published batch: the base becomes the image it left, each of its edits
601 /// gets a receipt naming the revisions its seal stored, or `revisions`, and it leaves
602 /// the queue.
603 fn acknowledge(
604 &self,
605 batch: i64,
606 transaction: Option<&Transaction>,
607 revisions: Option<&BTreeMap<ExGuid, ExGuid>>,
608 ) -> Result<()> {
609 let mut connection = self.lock()?;
610 let database = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
611 if let Some(transaction) = transaction {
612 base::publish(&database, transaction)?;
613 }
614 let revisions = match revisions {
615 Some(revisions) => revisions.clone(),
616 None => decode_revisions(&database.query_row(
617 "SELECT revisions FROM batches WHERE id=?1",
618 [batch],
619 |row| row.get::<_, String>(0),
620 )?)?,
621 };
622 for queued in queue::load(&database, self.section.key.as_ref(), Some(batch))? {
623 database.execute(
624 "INSERT INTO receipts(edit_id, revision) VALUES (?1, ?2)",
625 params![
626 signed(queued.id)?,
627 revision_of(&queued.edit, &revisions)?.to_string()
628 ],
629 )?;
630 }
631 database.execute("DELETE FROM batches WHERE id=?1", [batch])?;
632 queue::collect(&database)?;
633 database.commit()?;
634 Ok(())
635 }
636
637 /// Retires the uncertain attempt of the batch holding edit `id` after review. The
638 /// queue is first exported to `archive` (a new file), which is the record: no receipt
639 /// is written. `Mine` publishes the batch again against the current remote; `Theirs`
640 /// abandons every unpublished edit, which become `Archived`, and the local pages return
641 /// to the remote's.
642 pub fn release(&self, id: u64, archive: &Path, resolution: Resolution) -> Result<()> {
643 let owner = self.sync_owner()?;
644 let batch: Option<i64> = self
645 .lock()?
646 .query_row(
647 "SELECT id FROM batches WHERE attempted=1 AND id=(SELECT batch FROM edits WHERE id=?1)",
648 [signed(id)?],
649 |row| row.get(0),
650 )
651 .optional()?;
652 let Some(batch) = batch else {
653 return Err(io::Error::new(
654 io::ErrorKind::InvalidInput,
655 "The edit has no uncertain attempt",
656 )
657 .into());
658 };
659 self.export_recovery(archive)?;
660 {
661 let mut connection = self.lock()?;
662 let transaction =
663 connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
664 match resolution {
665 Resolution::Mine => {
666 transaction.execute("UPDATE batches SET attempted=0 WHERE id=?1", [batch])?;
667 }
668 Resolution::Theirs => {
669 transaction.execute(
670 "INSERT INTO archived(edit_id, archive) SELECT id, ?1 FROM edits",
671 [archive.to_string_lossy().into_owned()],
672 )?;
673 transaction.execute("DELETE FROM batches", [])?;
674 if let Some(remote) = base::read(&transaction, base::Image::Remote)? {
675 base::write(&transaction, base::Image::Base, &remote)?;
676 base::clear(&transaction, base::Image::Remote)?;
677 }
678 queue::collect(&transaction)?;
679 }
680 }
681 transaction.commit()?;
682 }
683 if resolution == Resolution::Theirs {
684 self.ask(|reply| Request::Reopen { reply })?;
685 }
686 drop(owner);
687 self.wake_sync();
688 Ok(())
689 }
690
691 fn sync_owner(&self) -> Result<MutexGuard<'_, ()>> {
692 Ok(self
693 .synchronization
694 .try_lock()
695 .map_err(|error| match error {
696 TryLockError::WouldBlock => io::Error::from(io::ErrorKind::WouldBlock),
697 TryLockError::Poisoned(_) => {
698 io::Error::other("Synchronization owner panicked; reopen the cache")
699 }
700 })?)
701 }
702
703 /// Whether nothing is queued and the remote still has the base's stamp, or the queue
704 /// is blocked on a remote that has not changed since; reads neither image and does not
705 /// lock the cache during remote I/O.
706 pub(crate) async fn settled(&self, remote: &mut impl Remote) -> Result<bool> {
707 let state = state(&*self.lock()?)?;
708 let expected = match &state.blocked {
709 Some(_) => state.remote.unwrap_or(state.base),
710 None if !state.queued => state.base,
711 None => return Ok(false),
712 };
713 Ok(awaited(remote, Remote::stamp)
714 .await
715 .map_err(Error::RemoteIo)?
716 == expected
717 && awaited(remote, Remote::versions)
718 .await
719 .map_err(Error::RemoteIo)?
720 .is_empty())
721 }
722}
723
724pub(crate) fn status(
725 connection: &Connection,
726 id: u64,
727 key: Option<&onestore::protected::Key>,
728) -> Result<Option<EditStatus>> {
729 let id = signed(id)?;
730 if let Some(revision) = connection
731 .query_row(
732 "SELECT revision FROM receipts WHERE edit_id=?1",
733 [id],
734 |row| row.get::<_, String>(0),
735 )
736 .optional()?
737 {
738 return Ok(Some(EditStatus::Published {
739 revision: revision.parse()?,
740 }));
741 }
742 if let Some(archive) = connection
743 .query_row(
744 "SELECT archive FROM archived WHERE edit_id=?1",
745 [id],
746 |row| row.get::<_, String>(0),
747 )
748 .optional()?
749 {
750 return Ok(Some(EditStatus::Archived { archive }));
751 }
752 let record: Option<(bool, Option<String>, String)> = connection
753 .query_row(
754 "SELECT batches.attempted, batches.revisions, edits.edit
755 FROM edits JOIN batches ON batches.id=edits.batch WHERE edits.id=?1",
756 [id],
757 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
758 )
759 .optional()?;
760 Ok(match record {
761 None => None,
762 Some((true, revisions, edit)) => {
763 let revisions = decode_revisions(revisions.as_deref().unwrap_or("{}"))?;
764 let edit = queue::parse(key, &edit)?;
765 let revision = revision_of(&edit, &revisions)?;
766 Some(EditStatus::AwaitingConfirmation { revision })
767 }
768 Some((false, ..)) => Some(EditStatus::Pending),
769 })
770}