tinymist_vfs/notify.rs
1use core::fmt;
2use std::path::Path;
3
4use rpds::RedBlackTreeMapSync;
5use typst::diag::FileResult;
6
7use crate::{Bytes, FileChangeSet, FileSnapshot, ImmutPath, PathAccessModel};
8
9/// A memory event that is notified by some external source
10#[derive(Debug, Clone)]
11pub enum MemoryEvent {
12 /// Reset all dependencies and update according to the given changeset
13 ///
14 /// We have not provided a way to reset all dependencies without updating
15 /// yet, but you can create a memory event with empty changeset to achieve
16 /// this:
17 ///
18 /// ```
19 /// use tinymist_vfs::{FileChangeSet, notify::MemoryEvent};
20 /// let event = MemoryEvent::Sync(FileChangeSet::default());
21 /// ```
22 Sync(FileChangeSet),
23 /// Update according to the given changeset
24 Update(FileChangeSet),
25}
26
27/// A upstream update event that is notified by some external source.
28///
29/// This event is used to notify some file watcher to invalidate some files
30/// before applying upstream changes. This is very important to make some atomic
31/// changes.
32#[derive(Debug)]
33pub struct UpstreamUpdateEvent {
34 /// Associated files that the event causes to invalidate
35 pub invalidates: Vec<ImmutPath>,
36 /// Opaque data that is passed to the file watcher
37 pub opaque: Box<dyn std::any::Any + Send>,
38}
39
40/// Aggregated filesystem events from some file watcher
41#[derive(Debug)]
42pub enum FilesystemEvent {
43 /// Update file system files according to the given changeset
44 Update(FileChangeSet),
45 /// See [`UpstreamUpdateEvent`]
46 UpstreamUpdate {
47 /// New changeset produced by invalidation
48 changeset: FileChangeSet,
49 /// The upstream event that causes the invalidation
50 upstream_event: Option<UpstreamUpdateEvent>,
51 },
52}
53
54impl FilesystemEvent {
55 pub fn split(self) -> (FileChangeSet, Option<UpstreamUpdateEvent>) {
56 match self {
57 FilesystemEvent::UpstreamUpdate {
58 changeset,
59 upstream_event,
60 } => (changeset, upstream_event),
61 FilesystemEvent::Update(changeset) => (changeset, None),
62 }
63 }
64}
65
66pub trait NotifyDeps: fmt::Debug + Send + Sync {
67 fn dependencies(&self, f: &mut dyn FnMut(&ImmutPath));
68}
69
70impl NotifyDeps for Vec<ImmutPath> {
71 fn dependencies(&self, f: &mut dyn FnMut(&ImmutPath)) {
72 for path in self.iter() {
73 f(path);
74 }
75 }
76}
77
78/// A message that is sent to some file watcher
79#[derive(Debug)]
80pub enum NotifyMessage {
81 /// Oettle the watching
82 Settle,
83 /// Overrides all dependencies
84 SyncDependency(Box<dyn NotifyDeps>),
85 /// upstream invalidation This is very important to make some atomic changes
86 ///
87 /// Example:
88 /// ```plain
89 /// /// Receive memory event
90 /// let event: MemoryEvent = retrieve();
91 /// let invalidates = event.invalidates();
92 ///
93 /// /// Send memory change event to [`NotifyActor`]
94 /// let event = Box::new(event);
95 /// self.send(NotifyMessage::UpstreamUpdate{ invalidates, opaque: event });
96 ///
97 /// /// Wait for [`NotifyActor`] to finish
98 /// let fs_event = self.fs_notify.block_receive();
99 /// let event: MemoryEvent = fs_event.opaque.downcast().unwrap();
100 ///
101 /// /// Apply changes
102 /// self.lock();
103 /// update_memory(event);
104 /// apply_fs_changes(fs_event.changeset);
105 /// self.unlock();
106 /// ```
107 UpstreamUpdate(UpstreamUpdateEvent),
108}
109
110/// Provides notify access model which retrieves file system events and changes
111/// from some notify backend.
112///
113/// It simply hold notified filesystem data in memory, but still have a fallback
114/// access model, whose the typical underlying access model is
115/// [`crate::system::SystemAccessModel`]
116#[derive(Debug, Clone)]
117pub struct NotifyAccessModel<M> {
118 files: RedBlackTreeMapSync<ImmutPath, FileSnapshot>,
119 /// The fallback access model when the file is not notified ever.
120 pub inner: M,
121}
122
123impl<M: PathAccessModel> NotifyAccessModel<M> {
124 /// Create a new notify access model
125 pub fn new(inner: M) -> Self {
126 Self {
127 files: RedBlackTreeMapSync::default(),
128 inner,
129 }
130 }
131
132 /// Notify the access model with a filesystem event
133 pub fn notify(&mut self, changeset: FileChangeSet) {
134 for path in changeset.removes {
135 self.files.remove_mut(&path);
136 }
137
138 for (path, contents) in changeset.inserts {
139 self.files.insert_mut(path, contents);
140 }
141 }
142}
143
144impl<M: PathAccessModel> PathAccessModel for NotifyAccessModel<M> {
145 #[inline]
146 fn reset(&mut self) {
147 self.inner.reset();
148 }
149
150 fn content(&self, src: &Path) -> FileResult<Bytes> {
151 if let Some(entry) = self.files.get(src) {
152 return entry.content().cloned();
153 }
154
155 self.inner.content(src)
156 }
157}