391 lines
16 KiB
Rust
391 lines
16 KiB
Rust
//! A scan that answers messages while it runs (`docs/features/scan-interleave/README.md`).
|
|
|
|
use super::*;
|
|
|
|
// ------------------------------------------------------------------
|
|
// a scan that answers messages while it runs
|
|
// ------------------------------------------------------------------
|
|
|
|
/// A tree of `files` one-package files, plus one that names the last of
|
|
/// them — enough files that a scan over it interleaves.
|
|
fn workspace_of(tag: &str, files: usize) -> Tree {
|
|
let tree = Tree::new(tag);
|
|
for n in 0..files {
|
|
tree.package(&format!("p{n:03}.sv"), &format!("p{n:03}"));
|
|
}
|
|
tree
|
|
}
|
|
|
|
/// A `workspace/symbol` request over the wire, by id.
|
|
pub(super) fn symbol_request(id: i32, query: &str) -> Message {
|
|
Message::Request(Request::new(
|
|
RequestId::from(id),
|
|
WorkspaceSymbolRequest::METHOD.to_string(),
|
|
serde_json::json!({ "query": query }),
|
|
))
|
|
}
|
|
|
|
/// Where the indexing bar's `end` sits among everything the server said,
|
|
/// and where the response to `id` sits. `None` for either if it never
|
|
/// came.
|
|
pub(super) fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
|
|
let ended = messages.iter().position(|message| {
|
|
matches!(message, Message::Notification(n) if n.method == Progress::METHOD
|
|
&& n.params["value"]["kind"] == "end")
|
|
});
|
|
let answered = messages
|
|
.iter()
|
|
.position(|message| matches!(message, Message::Response(r) if r.id == RequestId::from(id)));
|
|
(ended, answered)
|
|
}
|
|
|
|
#[test]
|
|
fn a_request_the_client_had_already_sent_is_answered_during_the_startup_scan() {
|
|
// The round's point, over the real dispatch: a request sitting on the
|
|
// transport when the server is built used to wait for the whole
|
|
// startup scan, because `Server::new` ran that scan before `run()`
|
|
// took its first message. It is now answered *inside* the scan — the
|
|
// response goes out before the bar comes down, which is the only
|
|
// ordering a test can check without a stopwatch.
|
|
let tree = workspace_of("interleaveanswer", INTERLEAVE_ABOVE + 6);
|
|
let session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![symbol_request(7, "p0")],
|
|
);
|
|
let said = session.drain();
|
|
let (ended, answered) = positions(&said, 7);
|
|
let answered = answered.expect("the request is answered at all");
|
|
let ended = ended.expect("the bar comes down");
|
|
assert!(
|
|
answered < ended,
|
|
"the answer must go out before the scan ends, not after it: {said:#?}"
|
|
);
|
|
// And the index really did finish, so nothing was traded for the
|
|
// latency but the completeness of that one answer.
|
|
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 6);
|
|
}
|
|
|
|
#[test]
|
|
fn a_scan_short_enough_to_wait_for_answers_nothing_in_the_middle_of_itself() {
|
|
// The other side of `INTERLEAVE_ABOVE`. A handful of files is over in
|
|
// milliseconds, so a request that arrived with them is answered from
|
|
// the *finished* index — the complete answer, which is worth more than
|
|
// the few milliseconds an interleaved one would have saved.
|
|
let tree = workspace_of("interleaveshort", 4);
|
|
let session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![symbol_request(7, "p0")],
|
|
);
|
|
// Nothing is answered during construction at all: the burst is still
|
|
// on the queue for `run` to take.
|
|
let said = session.drain();
|
|
assert_eq!(positions(&said, 7).1, None, "{said:#?}");
|
|
}
|
|
|
|
#[test]
|
|
fn interleave_above_is_a_hard_boundary_at_the_file_count_not_before_or_after() {
|
|
// QA attack (`docs/features/scan-interleave/README.md`, settling
|
|
// attacks): the exact edge of `INTERLEAVE_ABOVE`. `scan_once` compares
|
|
// with `>`, not `>=`, so a scan of *exactly* the threshold must still
|
|
// run one-shot and one file more must interleave. Both sides in one
|
|
// test so a future off-by-one in that comparison shows up as a single
|
|
// failing assertion rather than two tests that each only prove half.
|
|
let at_threshold = workspace_of("interleaveboundaryat", INTERLEAVE_ABOVE);
|
|
let one_shot = Session::started_behind(
|
|
vec![at_threshold.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![symbol_request(7, "p0")],
|
|
);
|
|
let said = one_shot.drain();
|
|
assert_eq!(
|
|
positions(&said, 7).1,
|
|
None,
|
|
"exactly INTERLEAVE_ABOVE files must run one-shot: {said:#?}"
|
|
);
|
|
|
|
let above_threshold = workspace_of("interleaveboundaryabove", INTERLEAVE_ABOVE + 1);
|
|
let interleaved = Session::started_behind(
|
|
vec![above_threshold.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![symbol_request(7, "p0")],
|
|
);
|
|
let said = interleaved.drain();
|
|
let (ended, answered) = positions(&said, 7);
|
|
assert!(
|
|
answered.expect("answered mid-scan") < ended.expect("the bar comes down"),
|
|
"one file over INTERLEAVE_ABOVE must interleave: {said:#?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_request_queued_behind_a_rescan_waits_for_that_rescan() {
|
|
// The order contract, which interleaving must not cost: a message
|
|
// that asks for a rescan is *applied* — rescan run and all — before
|
|
// anything queued behind it is answered. Here the cap is pushed down
|
|
// to nothing, which empties the index, and the request behind it must
|
|
// see the empty one rather than the half-built one it was sent into.
|
|
let tree = workspace_of("interleaveorder", INTERLEAVE_ABOVE + 6);
|
|
let mut session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![
|
|
Message::Notification(Notification::new(
|
|
DidChangeConfiguration::METHOD.to_string(),
|
|
capping(1),
|
|
)),
|
|
symbol_request(7, "p0"),
|
|
],
|
|
);
|
|
// The configuration was applied mid-scan and the rescan it asked for
|
|
// ran; the request behind it is still waiting, because it is owed that
|
|
// rescan's result.
|
|
assert!(session.server.held.len() == 1, "the request waits: {:?}", session.server.held);
|
|
assert_eq!(session.server.workspace.index().files().len(), 0, "the cap emptied the index");
|
|
let said = session.drain();
|
|
assert_eq!(positions(&said, 7).1, None, "not answered yet: {said:#?}");
|
|
|
|
// `run` answers it before it takes anything newer, and by then the
|
|
// rescan the client asked for has happened.
|
|
let held = std::mem::take(&mut session.server.held);
|
|
assert!(!session.batch(held), "the held burst is handled");
|
|
let answered = session.answers();
|
|
assert_eq!(answered.len(), 1, "{answered:#?}");
|
|
assert_eq!(
|
|
answered[0].response_result.as_ref().ok().and_then(|v| v.as_array()).map(Vec::len),
|
|
Some(0),
|
|
"answered from the index the push asked for, not the one it was sent into"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_held_request_keeps_its_place_and_takes_its_cancel_with_it() {
|
|
// Two corners of holding, in one experiment. The burst carries a
|
|
// cancel for the request it also carries, and the scan the burst's
|
|
// settings push asks for holds a *newer* request of its own along the
|
|
// way. What comes out has to be: the burst's own request first (it
|
|
// arrived first), the newer one behind it, and the cancel still in
|
|
// front of what it cancels — a cancel dropped by the wait would turn
|
|
// into a computed answer the client has stopped listening for.
|
|
let tree = workspace_of("interleaveheldorder", INTERLEAVE_ABOVE + 6);
|
|
let mut session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![
|
|
Message::Notification(Notification::new(
|
|
DidChangeConfiguration::METHOD.to_string(),
|
|
capping(1),
|
|
)),
|
|
Message::Notification(Notification::new(
|
|
Cancel::METHOD.to_string(),
|
|
serde_json::json!({ "id": 7 }),
|
|
)),
|
|
symbol_request(7, "p0"),
|
|
symbol_request(8, "p0"),
|
|
],
|
|
);
|
|
let held: Vec<String> = session
|
|
.server
|
|
.held
|
|
.iter()
|
|
.map(|message| match message {
|
|
Message::Request(request) => format!("req {}", request.id),
|
|
Message::Notification(n) => format!("notif {}", n.method),
|
|
Message::Response(r) => format!("resp {}", r.id),
|
|
})
|
|
.collect();
|
|
assert_eq!(held, ["notif $/cancelRequest", "req 7", "req 8"], "{held:?}");
|
|
|
|
let batch = std::mem::take(&mut session.server.held);
|
|
assert!(!session.batch(batch), "the held burst is handled");
|
|
let answered = session.answers();
|
|
assert_eq!(answered.len(), 2, "{answered:#?}");
|
|
assert_eq!(answered[0].id, RequestId::from(7));
|
|
assert!(
|
|
answered[0]
|
|
.response_result
|
|
.as_ref()
|
|
.is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32),
|
|
"the cancel survived the wait: {:#?}",
|
|
answered[0]
|
|
);
|
|
assert_eq!(answered[1].id, RequestId::from(8), "and the newer one is behind it");
|
|
assert!(answered[1].response_result.is_ok(), "which is answered normally: {:#?}", answered[1]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_rescan_asked_for_mid_scan_is_coalesced_into_exactly_one_more_scan() {
|
|
// Three settings pushes land inside one startup scan, each of which
|
|
// would rebuild the index on its own. They cost one more scan between
|
|
// them, not three, and no scan runs inside another: two bars, two
|
|
// tokens, in order.
|
|
let tree = workspace_of("interleavecoalesce", INTERLEAVE_ABOVE + 6);
|
|
let cap = |bytes: u64| {
|
|
Message::Notification(Notification::new(
|
|
DidChangeConfiguration::METHOD.to_string(),
|
|
capping(bytes),
|
|
))
|
|
};
|
|
let session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![cap(1), cap(2), cap(3)],
|
|
);
|
|
assert!(!session.server.scanning, "no scan is left running");
|
|
assert!(!session.server.rescan_wanted, "and none is left owed");
|
|
let bars: Vec<(&str, String)> = session
|
|
.drain()
|
|
.into_iter()
|
|
.filter_map(progress_step)
|
|
.filter(|(step, _)| *step != "report")
|
|
.collect();
|
|
assert_eq!(
|
|
bars,
|
|
vec![
|
|
("create", "lucisv-index-0".to_string()),
|
|
("begin", "lucisv-index-0".to_string()),
|
|
("end", "lucisv-index-0".to_string()),
|
|
("create", "lucisv-index-1".to_string()),
|
|
("begin", "lucisv-index-1".to_string()),
|
|
("end", "lucisv-index-1".to_string()),
|
|
],
|
|
"one startup scan and exactly one coalesced rescan behind it"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands() {
|
|
// A scan is interruptible now that it takes messages, and `shutdown`
|
|
// is what interrupts it: the bar never comes down, nothing is
|
|
// published after it, and `run` returns without taking another
|
|
// message. What the scan had already parsed is in the persistent
|
|
// store — it is written through per file — so the next session
|
|
// resumes from it exactly as it does after any other half-done scan.
|
|
let tree = workspace_of("interleaveshutdown", INTERLEAVE_ABOVE + 6);
|
|
let shutdown = || {
|
|
Message::Request(Request::new(
|
|
RequestId::from(9),
|
|
Shutdown::METHOD.to_string(),
|
|
Value::Null,
|
|
))
|
|
};
|
|
let mut session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
// On the connection as well as on the queue, and in this order:
|
|
// the queued copy is what the scan's first drain is *certain* to
|
|
// see, and the copy the forwarder carries is what stops it reading
|
|
// — so the `exit` behind it is still there for `handle_shutdown`,
|
|
// which reads the connection itself. Whichever of the two the
|
|
// handshake ends up consuming, the scan stops here.
|
|
vec![shutdown(), Message::Notification(Notification::new("exit".into(), Value::Null))],
|
|
vec![shutdown()],
|
|
);
|
|
assert!(session.server.stopped, "the scan saw the shutdown");
|
|
assert_eq!(session.ended(), Vec::<Option<String>>::new(), "the bar never came down");
|
|
assert!(
|
|
session.server.workspace.index().files().len() < INTERLEAVE_ABOVE + 6,
|
|
"the scan stopped where it stood rather than running to the end"
|
|
);
|
|
session.server.run().expect("run returns at once");
|
|
}
|
|
|
|
#[test]
|
|
fn a_buffer_opened_during_the_startup_scan_is_published_and_lenses_refreshed_once() {
|
|
// QA attack (`docs/features/scan-interleave/README.md`,
|
|
// progress/log-continuity): before this round no buffer could be
|
|
// *open* while `Server::new` was still running, so `Server::started`
|
|
// never had to pay the one-time republish-and-refresh `reindex` has
|
|
// always owed at the end of a rescan. A `didOpen` answered mid-scan
|
|
// now creates exactly that buffer, and the work log says
|
|
// `Server::started` pays the debt at the end of construction.
|
|
//
|
|
// Two publishes for the opened file are both correct, not a
|
|
// duplicate: `didOpen`'s own handler has always published against
|
|
// whatever index exists the moment a file opens (unrelated to this
|
|
// round), which here is the half-built one — so the debt payment
|
|
// after the bar comes down is what gives the client a diagnostics set
|
|
// computed against the *finished* index, and it must come after the
|
|
// `end` event, not folded into the mid-scan one.
|
|
let tree = workspace_of("interleaveopenedpublish", INTERLEAVE_ABOVE + 6);
|
|
let target = tree.path.join("p000.sv");
|
|
let opened = Message::Notification(Notification::new(
|
|
DidOpenTextDocument::METHOD.to_string(),
|
|
serde_json::json!({
|
|
"textDocument": {
|
|
"uri": path_to_uri(&target).expect("uri"),
|
|
"languageId": "systemverilog",
|
|
"version": 1,
|
|
"text": "package p000;\nendpackage\n",
|
|
}
|
|
}),
|
|
));
|
|
let abilities =
|
|
ClientAbilities { work_done_progress: true, code_lens_refresh: true, ..Default::default() };
|
|
let session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
abilities,
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![opened],
|
|
);
|
|
let said = session.drain();
|
|
let target_uri = path_to_uri(&target).expect("uri");
|
|
let ended = said
|
|
.iter()
|
|
.position(|m| {
|
|
matches!(m, Message::Notification(n) if n.method == Progress::METHOD
|
|
&& n.params["value"]["kind"] == "end")
|
|
})
|
|
.expect("the bar comes down");
|
|
let publish_positions: Vec<usize> = said
|
|
.iter()
|
|
.enumerate()
|
|
.filter_map(|(i, m)| match m {
|
|
Message::Notification(n)
|
|
if n.method == PublishDiagnostics::METHOD
|
|
&& serde_json::from_value::<PublishDiagnosticsParams>(n.params.clone())
|
|
.is_ok_and(|p| p.uri == target_uri) =>
|
|
{
|
|
Some(i)
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(
|
|
publish_positions.len(),
|
|
2,
|
|
"one publish from didOpen's own handler, one from the debt Server::started pays: \
|
|
{said:#?}"
|
|
);
|
|
assert!(
|
|
publish_positions[0] < ended,
|
|
"the first publish is didOpen's own, against the half-built index: {said:#?}"
|
|
);
|
|
assert!(
|
|
publish_positions[1] > ended,
|
|
"the second is the debt payment, against the finished index: {said:#?}"
|
|
);
|
|
let refreshes = said
|
|
.iter()
|
|
.filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD))
|
|
.count();
|
|
assert_eq!(refreshes, 1, "exactly one lens refresh, not one per drain: {said:#?}");
|
|
}
|