forked from web-infra-dev/rspack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative_watcher.rs
More file actions
315 lines (281 loc) · 8.6 KB
/
Copy pathnative_watcher.rs
File metadata and controls
315 lines (281 loc) · 8.6 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::{
boxed::Box,
collections::HashMap,
path::{Path, PathBuf},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use napi::bindgen_prelude::*;
use napi_derive::*;
use rspack_paths::ArcPath;
use rspack_regex::RspackRegex;
use rspack_watcher::{FsEventKind, FsWatcher, FsWatcherIgnored, FsWatcherOptions};
type JsWatcherIgnored = Either3<String, Vec<String>, RspackRegex>;
fn to_fs_watcher_ignored(ignored: Option<JsWatcherIgnored>) -> FsWatcherIgnored {
if let Some(ignored) = ignored {
match ignored {
Either3::A(path) => FsWatcherIgnored::Path(path),
Either3::B(paths) => FsWatcherIgnored::Paths(paths),
Either3::C(regex) => FsWatcherIgnored::Regex(regex),
}
} else {
FsWatcherIgnored::None
}
}
#[napi(object, object_to_js = false)]
pub struct NativeWatcherOptions {
pub follow_symlinks: Option<bool>,
pub poll_interval: Option<u32>,
pub aggregate_timeout: Option<u32>,
#[napi(ts_type = "string | string[] | RegExp")]
/// The ignored paths for the watcher.
/// It can be a single path, an array of paths, or a regular expression.
pub ignored: Option<JsWatcherIgnored>,
}
#[napi]
pub struct NativeWatchResult {
pub changed_files: Vec<String>,
pub removed_files: Vec<String>,
}
/// watchpack-style time info for a single path, surfaced to webpack as a
/// `FileSystemInfoEntry`. `timestamp` is absent for directory (context)
/// entries, whose value is a derived `safe_time` only.
#[napi(object)]
pub struct JsTimeInfoEntry {
pub safe_time: f64,
pub timestamp: Option<f64>,
}
/// The full `fileTimeInfoEntries` / `contextTimeInfoEntries` snapshot, mirroring
/// watchpack's `collectTimeInfoEntries` output.
#[napi(object)]
pub struct NativeTimeInfo {
pub file_time_info_entries: HashMap<String, JsTimeInfoEntry>,
pub context_time_info_entries: HashMap<String, JsTimeInfoEntry>,
}
#[napi]
pub struct NativeWatcher {
watcher: FsWatcher,
closed: bool,
}
fn timestamp_to_system_time(millis: u64) -> SystemTime {
UNIX_EPOCH + Duration::from_millis(millis)
}
#[napi]
impl NativeWatcher {
#[napi(constructor)]
pub fn new(options: NativeWatcherOptions) -> Self {
let watcher = FsWatcher::new(
FsWatcherOptions {
follow_symlinks: options.follow_symlinks.unwrap_or(false),
poll_interval: options.poll_interval,
aggregate_timeout: options.aggregate_timeout,
},
to_fs_watcher_ignored(options.ignored),
);
Self {
watcher,
closed: false,
}
}
#[napi]
#[allow(clippy::too_many_arguments)]
pub fn watch(
&mut self,
reference: Reference<NativeWatcher>,
files: (Vec<String>, Vec<String>),
directories: (Vec<String>, Vec<String>),
missing: (Vec<String>, Vec<String>),
start_time: BigInt,
#[napi(ts_arg_type = "(err: Error | null, result: NativeWatchResult) => void")]
callback: Function<'static>,
#[napi(ts_arg_type = "(path: string) => void")] callback_undelayed: Function<'static>,
env: Env,
) -> napi::Result<()> {
if self.closed {
return Err(napi::Error::from_reason(
"The native watcher has been closed, cannot watch again.",
));
}
let js_event_handler = JsEventHandler::new(callback)?;
let js_event_handler_undelayed = JsEventHandlerUndelayed::new(callback_undelayed)?;
let start_time = start_time.get_u64().1;
reference.share_with(env, |native_watcher| {
napi::bindgen_prelude::spawn(async move {
native_watcher
.watcher
.watch(
to_tuple_path_iterator(files),
to_tuple_path_iterator(directories),
to_tuple_path_iterator(missing),
timestamp_to_system_time(start_time),
Box::new(js_event_handler),
Box::new(js_event_handler_undelayed),
)
.await
});
Ok(())
})?;
Ok(())
}
#[napi(ts_type = "(kind: 'change' | 'remove' | 'create', path: string): void")]
pub fn trigger_event(&self, kind: String, path: String) {
if let Some(kind) = match kind.as_str() {
"change" => Some(FsEventKind::Change),
"remove" => Some(FsEventKind::Remove),
"create" => Some(FsEventKind::Create),
_ => None,
} {
self
.watcher
.trigger_event(&ArcPath::from(AsRef::<Path>::as_ref(&path)), kind);
}
}
#[napi]
/// # Safety
///
/// This function is unsafe because it uses `&mut self` to call the watcher asynchronously.
/// It's important to ensure that the watcher is not used in any other places before this function is finished.
/// You must ensure that the watcher not call watch, close or pause in the same time, otherwise it may lead to undefined behavior.
pub async unsafe fn close(&mut self) -> napi::Result<()> {
self
.watcher
.close()
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
self.closed = true;
Ok(())
}
#[napi]
pub fn pause(&self) -> napi::Result<()> {
self
.watcher
.pause()
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
Ok(())
}
/// Collect the full file/context time tables, mirroring watchpack's
/// `collectTimeInfoEntries`. Called synchronously from JS after an aggregated
/// event (or from `getInfo()`) to populate `compiler.fileTimestamps` /
/// `contextTimestamps`.
#[napi]
pub fn get_time_info(&self) -> NativeTimeInfo {
let (files, contexts) = self.watcher.collect_time_info();
let file_time_info_entries = files
.into_iter()
.map(|(path, entry)| {
(
path,
JsTimeInfoEntry {
safe_time: entry.safe_time as f64,
timestamp: Some(entry.timestamp as f64),
},
)
})
.collect();
let context_time_info_entries = contexts
.into_iter()
.map(|(path, safe_time)| {
(
path,
JsTimeInfoEntry {
safe_time: safe_time as f64,
timestamp: None,
},
)
})
.collect();
NativeTimeInfo {
file_time_info_entries,
context_time_info_entries,
}
}
}
fn to_tuple_path_iterator(
tuple: (Vec<String>, Vec<String>),
) -> (impl Iterator<Item = ArcPath>, impl Iterator<Item = ArcPath>) {
(
tuple.0.into_iter().map(|s| ArcPath::from(PathBuf::from(s))),
tuple.1.into_iter().map(|s| ArcPath::from(PathBuf::from(s))),
)
}
struct JsEventHandler {
inner: napi::threadsafe_function::ThreadsafeFunction<
NativeWatchResult,
napi::Unknown<'static>,
NativeWatchResult,
Status,
true,
true,
1,
>,
}
impl JsEventHandler {
fn new(callback: Function<'static>) -> napi::Result<Self> {
let callback = callback
.build_threadsafe_function::<NativeWatchResult>()
.callee_handled::<true>()
.max_queue_size::<1>()
.weak::<true>()
.build_callback(
move |ctx: napi::threadsafe_function::ThreadSafeCallContext<_>| Ok(ctx.value),
)?;
Ok(Self { inner: callback })
}
}
impl rspack_watcher::EventAggregateHandler for JsEventHandler {
fn on_event_handle(
&self,
changed_files: rspack_util::fx_hash::FxHashSet<String>,
deleted_files: rspack_util::fx_hash::FxHashSet<String>,
) {
let changed_files_vec: Vec<String> = changed_files.into_iter().collect();
let deleted_files_vec: Vec<String> = deleted_files.into_iter().collect();
let result = NativeWatchResult {
changed_files: changed_files_vec,
removed_files: deleted_files_vec,
};
self.inner.call(
Ok(result),
napi::threadsafe_function::ThreadsafeFunctionCallMode::NonBlocking,
);
}
fn on_error(&self, error: rspack_error::Error) {
// Handle error, maybe log it or notify the user
let error_message = format!("Watcher error: {error}");
self.inner.call(
Err(napi::Error::from_reason(error_message)),
napi::threadsafe_function::ThreadsafeFunctionCallMode::NonBlocking,
);
}
}
struct JsEventHandlerUndelayed {
inner: napi::threadsafe_function::ThreadsafeFunction<
String,
napi::Unknown<'static>,
String,
Status,
false,
false,
1,
>,
}
impl JsEventHandlerUndelayed {
fn new(callback: Function<'static>) -> napi::Result<Self> {
let callback = callback
.build_threadsafe_function::<String>()
.weak::<false>()
.max_queue_size::<1>()
.build_callback(
move |ctx: napi::threadsafe_function::ThreadSafeCallContext<_>| Ok(ctx.value),
)?;
Ok(Self { inner: callback })
}
}
impl rspack_watcher::EventHandler for JsEventHandlerUndelayed {
fn on_change(&self, changed_file: String) -> rspack_error::Result<()> {
self.inner.call(
changed_file,
napi::threadsafe_function::ThreadsafeFunctionCallMode::NonBlocking,
);
Ok(())
}
}