-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathhmr.rs
260 lines (233 loc) · 8.54 KB
/
hmr.rs
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
// Copyright 2018-2025 the Deno authors. MIT license.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use deno_core::error::CoreError;
use deno_core::futures::StreamExt;
use deno_core::serde_json::json;
use deno_core::serde_json::{self};
use deno_core::url::Url;
use deno_core::LocalInspectorSession;
use deno_error::JsErrorBox;
use deno_terminal::colors;
use tokio::select;
use crate::cdp;
use crate::emit::Emitter;
use crate::util::file_watcher::WatcherCommunicator;
use crate::util::file_watcher::WatcherRestartMode;
fn explain(status: &cdp::Status) -> &'static str {
match status {
cdp::Status::Ok => "OK",
cdp::Status::CompileError => "compile error",
cdp::Status::BlockedByActiveGenerator => "blocked by active generator",
cdp::Status::BlockedByActiveFunction => "blocked by active function",
cdp::Status::BlockedByTopLevelEsModuleChange => {
"blocked by top-level ES module change"
}
}
}
fn should_retry(status: &cdp::Status) -> bool {
match status {
cdp::Status::Ok => false,
cdp::Status::CompileError => false,
cdp::Status::BlockedByActiveGenerator => true,
cdp::Status::BlockedByActiveFunction => true,
cdp::Status::BlockedByTopLevelEsModuleChange => false,
}
}
/// This structure is responsible for providing Hot Module Replacement
/// functionality.
///
/// It communicates with V8 inspector over a local session and waits for
/// notifications about changed files from the `FileWatcher`.
///
/// Upon receiving such notification, the runner decides if the changed
/// path should be handled the `FileWatcher` itself (as if we were running
/// in `--watch` mode), or if the path is eligible to be hot replaced in the
/// current program.
///
/// Even if the runner decides that a path will be hot-replaced, the V8 isolate
/// can refuse to perform hot replacement, eg. a top-level variable/function
/// of an ES module cannot be hot-replaced. In such situation the runner will
/// force a full restart of a program by notifying the `FileWatcher`.
pub struct HmrRunner {
session: LocalInspectorSession,
watcher_communicator: Arc<WatcherCommunicator>,
script_ids: HashMap<String, String>,
emitter: Arc<Emitter>,
}
#[async_trait::async_trait(?Send)]
impl crate::worker::HmrRunner for HmrRunner {
// TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs`
async fn start(&mut self) -> Result<(), CoreError> {
self.enable_debugger().await
}
// TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs`
async fn stop(&mut self) -> Result<(), CoreError> {
self
.watcher_communicator
.change_restart_mode(WatcherRestartMode::Automatic);
self.disable_debugger().await
}
async fn run(&mut self) -> Result<(), CoreError> {
self
.watcher_communicator
.change_restart_mode(WatcherRestartMode::Manual);
let mut session_rx = self.session.take_notification_rx();
loop {
select! {
biased;
Some(notification) = session_rx.next() => {
let notification = serde_json::from_value::<cdp::Notification>(notification).map_err(JsErrorBox::from_err)?;
if notification.method == "Runtime.exceptionThrown" {
let exception_thrown = serde_json::from_value::<cdp::ExceptionThrown>(notification.params).map_err(JsErrorBox::from_err)?;
let (message, description) = exception_thrown.exception_details.get_message_and_description();
break Err(JsErrorBox::generic(format!("{} {}", message, description)).into());
} else if notification.method == "Debugger.scriptParsed" {
let params = serde_json::from_value::<cdp::ScriptParsed>(notification.params).map_err(JsErrorBox::from_err)?;
if params.url.starts_with("file://") {
let file_url = Url::parse(¶ms.url).unwrap();
let file_path = file_url.to_file_path().unwrap();
if let Ok(canonicalized_file_path) = file_path.canonicalize() {
let canonicalized_file_url = Url::from_file_path(canonicalized_file_path).unwrap();
self.script_ids.insert(canonicalized_file_url.to_string(), params.script_id);
}
}
}
}
changed_paths = self.watcher_communicator.watch_for_changed_paths() => {
let changed_paths = changed_paths.map_err(JsErrorBox::from_err)?;
let Some(changed_paths) = changed_paths else {
let _ = self.watcher_communicator.force_restart();
continue;
};
let filtered_paths: Vec<PathBuf> = changed_paths.into_iter().filter(|p| p.extension().is_some_and(|ext| {
let ext_str = ext.to_str().unwrap();
matches!(ext_str, "js" | "ts" | "jsx" | "tsx")
})).collect();
// If after filtering there are no paths it means it's either a file
// we can't HMR or an external file that was passed explicitly to
// `--watch-hmr=<file>` path.
if filtered_paths.is_empty() {
let _ = self.watcher_communicator.force_restart();
continue;
}
for path in filtered_paths {
let Some(path_str) = path.to_str() else {
let _ = self.watcher_communicator.force_restart();
continue;
};
let Ok(module_url) = Url::from_file_path(path_str) else {
let _ = self.watcher_communicator.force_restart();
continue;
};
let Some(id) = self.script_ids.get(module_url.as_str()).cloned() else {
let _ = self.watcher_communicator.force_restart();
continue;
};
let source_code = self.emitter.load_and_emit_for_hmr(
&module_url,
).await?;
let mut tries = 1;
loop {
let result = self.set_script_source(&id, source_code.as_str()).await?;
if matches!(result.status, cdp::Status::Ok) {
self.dispatch_hmr_event(module_url.as_str()).await?;
self.watcher_communicator.print(format!("Replaced changed module {}", module_url.as_str()));
break;
}
self.watcher_communicator.print(format!("Failed to reload module {}: {}.", module_url, colors::gray(explain(&result.status))));
if should_retry(&result.status) && tries <= 2 {
tries += 1;
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
continue;
}
let _ = self.watcher_communicator.force_restart();
break;
}
}
}
_ = self.session.receive_from_v8_session() => {}
}
}
}
}
impl HmrRunner {
pub fn new(
emitter: Arc<Emitter>,
session: LocalInspectorSession,
watcher_communicator: Arc<WatcherCommunicator>,
) -> Self {
Self {
session,
emitter,
watcher_communicator,
script_ids: HashMap::new(),
}
}
// TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs`
async fn enable_debugger(&mut self) -> Result<(), CoreError> {
self
.session
.post_message::<()>("Debugger.enable", None)
.await?;
self
.session
.post_message::<()>("Runtime.enable", None)
.await?;
Ok(())
}
// TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs`
async fn disable_debugger(&mut self) -> Result<(), CoreError> {
self
.session
.post_message::<()>("Debugger.disable", None)
.await?;
self
.session
.post_message::<()>("Runtime.disable", None)
.await?;
Ok(())
}
async fn set_script_source(
&mut self,
script_id: &str,
source: &str,
) -> Result<cdp::SetScriptSourceResponse, CoreError> {
let result = self
.session
.post_message(
"Debugger.setScriptSource",
Some(json!({
"scriptId": script_id,
"scriptSource": source,
"allowTopFrameEditing": true,
})),
)
.await?;
Ok(
serde_json::from_value::<cdp::SetScriptSourceResponse>(result)
.map_err(JsErrorBox::from_err)?,
)
}
async fn dispatch_hmr_event(
&mut self,
script_id: &str,
) -> Result<(), CoreError> {
let expr = format!(
"dispatchEvent(new CustomEvent(\"hmr\", {{ detail: {{ path: \"{}\" }} }}));",
script_id
);
let _result = self
.session
.post_message(
"Runtime.evaluate",
Some(json!({
"expression": expr,
"contextId": Some(1),
})),
)
.await?;
Ok(())
}
}