1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use futures::prelude::*;
use notify::Config;
use notify::EventKind;
use notify::PollWatcher;
use notify::RecursiveMode;
use notify::Watcher;
use notify::event::DataChange;
use notify::event::MetadataKind;
use notify::event::ModifyKind;
use tokio::sync::mpsc;
use tokio::sync::mpsc::error::TrySendError;
#[cfg(not(test))]
const DEFAULT_WATCH_DURATION: Duration = Duration::from_secs(3);
#[cfg(test)]
const DEFAULT_WATCH_DURATION: Duration = Duration::from_millis(100);
/// Creates a stream events whenever the file at the path has changes. The stream never terminates
/// and must be dropped to finish watching.
///
/// # Arguments
///
/// * `path`: The file to watch
///
/// returns: impl Stream<Item=()>
///
pub(crate) fn watch(path: &Path) -> impl Stream<Item = ()> + use<> {
watch_with_duration(path, DEFAULT_WATCH_DURATION)
}
fn watch_with_duration(path: &Path, duration: Duration) -> impl Stream<Item = ()> + use<> {
// Due to the vagaries of file watching across multiple platforms, instead of watching the
// supplied path (file), we are going to watch the parent (directory) of the path.
let config_file_path = PathBuf::from(path);
let watched_path = config_file_path.clone();
let (watch_sender, watch_receiver) = mpsc::channel(1);
let watch_receiver_stream = tokio_stream::wrappers::ReceiverStream::new(watch_receiver);
// We can't use the recommended watcher, because there's just too much variation across
// platforms and file systems. We use the Poll Watcher, which is implemented consistently
// across all platforms. Less reactive than other mechanisms, but at least it's predictable
// across all environments. We compare contents as well, which reduces false positives with
// some additional processing burden.
let config = Config::default()
.with_poll_interval(duration)
.with_compare_contents(true);
let mut watcher = PollWatcher::new(
move |res: Result<notify::Event, notify::Error>| match res {
Ok(event) => {
// The two kinds of events of interest to use are writes to the metadata of a
// watched file and changes to the data of a watched file
if matches!(
event.kind,
EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime))
| EventKind::Modify(ModifyKind::Data(DataChange::Any))
) && event.paths.contains(&watched_path)
{
match watch_sender.try_send(()) {
Ok(_) => (),
// If the sender is full, it means the receiver hasn't processed the
// update yet, so it's fine to drop the event. In effect, it's the same
// as if we had cancelled the previous event and pushed a new one.
Err(TrySendError::Full(_err)) => (),
Err(err) => {
panic!("event channel failed: {err}");
}
}
}
}
Err(e) => tracing::error!("event error: {:?}", e),
},
config,
)
.unwrap_or_else(|_| panic!("could not create watch on: {config_file_path:?}"));
watcher
.watch(&config_file_path, RecursiveMode::NonRecursive)
.unwrap_or_else(|_| panic!("could not watch: {config_file_path:?}"));
// Tell watchers once they should read the file once,
// then listen to fs events.
stream::once(future::ready(()))
.chain(watch_receiver_stream)
.chain(stream::once(async move {
// This exists to give the stream ownership of the hotwatcher.
// Without it hotwatch will get dropped and the stream will terminate.
// This code never actually gets run.
// The ideal would be that hotwatch implements a stream and
// therefore we don't need this hackery.
drop(watcher);
}))
.boxed()
}
/// Creates a stream events whenever the path has changes. The stream never terminates
/// and must be dropped to finish watching.
///
/// # Arguments
///
/// * `path`: The path to watch
///
/// returns: impl Stream<Item=()>
///
pub(crate) fn watch_rhai(path: &Path) -> impl Stream<Item = ()> + use<> {
watch_rhai_with_duration(path, DEFAULT_WATCH_DURATION)
}
// We need different watcher configuration for Rhai source.
fn watch_rhai_with_duration(path: &Path, duration: Duration) -> impl Stream<Item = ()> + use<> {
// Due to the vagaries of file watching across multiple platforms, instead of watching the
// supplied path (file), we are going to watch the parent (directory) of the path.
let rhai_source_path = PathBuf::from(path);
let (watch_sender, watch_receiver) = mpsc::channel(1);
let watch_receiver_stream = tokio_stream::wrappers::ReceiverStream::new(watch_receiver);
// We can't use the recommended watcher, because there's just too much variation across
// platforms and file systems. We use the Poll Watcher, which is implemented consistently
// across all platforms. Less reactive than other mechanisms, but at least it's predictable
// across all environments. We compare contents as well, which reduces false positives with
// some additional processing burden.
let config = Config::default()
.with_poll_interval(duration)
.with_compare_contents(true);
let mut watcher = PollWatcher::new(
move |res: Result<notify::Event, notify::Error>| {
match res {
Ok(event) => {
// Let's limit the events we are interested in to:
// - Modified files
// - Created/Remove files
// - with suffix "rhai"
if matches!(
event.kind,
EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime))
| EventKind::Modify(ModifyKind::Data(DataChange::Any))
| EventKind::Create(_)
| EventKind::Remove(_)
) {
let mut proceed = false;
for path in &event.paths {
if path.extension().is_some_and(|ext| ext == "rhai") {
proceed = true;
break;
}
}
if proceed {
match watch_sender.try_send(()) {
Ok(_) => (),
// Same behaviour as the config file watcher (#8336): if the
// channel is full a reload is already pending, and when it
// runs it will re-read the files from disk and pick up the
// latest contents. There is a narrow race where a change
// that arrives during the read itself could be missed until
// a subsequent edit triggers a new notification, which is
// the same trade-off accepted for the config watcher.
Err(TrySendError::Full(_)) => (),
Err(err) => {
panic!("event channel failed: {err}");
}
}
}
}
}
Err(e) => tracing::error!("rhai watching event error: {:?}", e),
}
},
config,
)
.unwrap_or_else(|_| panic!("could not create watch on: {rhai_source_path:?}"));
watcher
.watch(&rhai_source_path, RecursiveMode::Recursive)
.unwrap_or_else(|_| panic!("could not watch: {rhai_source_path:?}"));
// Tell watchers once they should read the file once,
// then listen to fs events.
stream::once(future::ready(()))
.chain(watch_receiver_stream)
.chain(stream::once(async move {
// This exists to give the stream ownership of the hotwatcher.
// Without it hotwatch will get dropped and the stream will terminate.
// This code never actually gets run.
// The ideal would be that hotwatch implements a stream and
// therefore we don't need this hackery.
drop(watcher);
}))
.boxed()
}
#[cfg(test)]
pub(crate) mod tests {
use std::env::temp_dir;
use std::fs::File;
use std::io::Seek;
use std::io::Write;
use std::path::PathBuf;
use test_log::test;
use super::*;
#[test(tokio::test)]
async fn basic_watch() {
let (path, mut file) = create_temp_file();
let mut watch = watch_with_duration(&path, Duration::from_millis(100));
// This test can be very racy. Without synchronisation, all
// we can hope is that if we wait long enough between each
// write/flush then the future will become ready.
// Signal telling us we are ready
assert!(futures::poll!(watch.next()).is_ready());
write_and_flush(&mut file, "Some data 1").await;
assert!(futures::poll!(watch.next()).is_ready());
write_and_flush(&mut file, "Some data 2").await;
assert!(futures::poll!(watch.next()).is_ready())
}
#[test(tokio::test)]
async fn clog_watch() {
let (path, mut file) = create_temp_file();
let mut watch = watch_with_duration(&path, Duration::from_millis(100));
assert!(futures::poll!(watch.next()).is_ready());
write_and_flush(&mut file, "Some data 1").await;
write_and_flush(&mut file, "Some data 2").await;
write_and_flush(&mut file, "Some data 3").await;
write_and_flush(&mut file, "Some data 4").await;
assert!(
futures::poll!(watch.next()).is_ready(),
"polling the future should notice the event"
);
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(
!futures::poll!(watch.next()).is_ready(),
"should only have one event for multiple updates"
);
}
// Rapid rhai file changes while the state machine is busy must not block an
// OS thread in a retry loop that can panic when the channel is eventually
// closed. The watcher must drop duplicate events instead of retrying so
// that the callback always returns promptly.
#[test(tokio::test)]
async fn clog_watch_rhai() {
let dir = tempfile::tempdir().unwrap();
let rhai_path = dir.path().join("script.rhai");
let mut file = std::fs::File::create(&rhai_path).unwrap();
let mut watch = watch_rhai_with_duration(&rhai_path, Duration::from_millis(100));
assert!(futures::poll!(watch.next()).is_ready());
write_and_flush(&mut file, "// v1").await;
write_and_flush(&mut file, "// v2").await;
write_and_flush(&mut file, "// v3").await;
write_and_flush(&mut file, "// v4").await;
assert!(
futures::poll!(watch.next()).is_ready(),
"polling the future should notice the event"
);
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(
!futures::poll!(watch.next()).is_ready(),
"should only have one event for multiple updates"
);
}
pub(crate) fn create_temp_file() -> (PathBuf, File) {
let path = temp_dir().join(format!("{}", uuid::Uuid::new_v4()));
let file = std::fs::File::create(&path).unwrap();
(path, file)
}
pub(crate) async fn write_and_flush(file: &mut File, contents: &str) {
file.rewind().unwrap();
file.set_len(0).unwrap();
file.write_all(contents.as_bytes()).unwrap();
file.flush().unwrap();
tokio::time::sleep(Duration::from_millis(500)).await;
}
}