1use std::path::Path;
4use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5use std::sync::{Arc, Mutex, MutexGuard};
6
7use vvv_core::{LanguageRegistry, Oracle};
8
9use crate::graph::{Graph, Retention};
10use crate::{EngineError, LanguageId, Workspace};
11
12#[derive(Clone)]
13pub struct Engine {
14 workspace: Workspace,
15 languages: LanguageRegistry,
16 pub(crate) file_previews: Arc<Mutex<crate::capabilities::file::FileCache>>,
17 retention: Retention,
18 oracle: Option<Arc<dyn Oracle>>,
20 graph: Arc<Mutex<Graph>>,
22 operation: Arc<Mutex<()>>,
24 dirty: Arc<AtomicBool>,
26 queries: Arc<Mutex<crate::query_store::QueryStore>>,
27 plans: Arc<Mutex<crate::plan_store::PlanStore>>,
28 query_revision: Arc<AtomicU64>,
29 cancellation: Option<crate::ReadCancellation>,
30}
31
32impl std::fmt::Debug for Engine {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 f.debug_struct("Engine")
35 .field("workspace", &self.workspace)
36 .field("retention", &self.retention)
37 .field("oracle", &self.oracle.is_some())
38 .finish_non_exhaustive()
39 }
40}
41
42impl Engine {
43 pub fn new(workspace: Workspace, languages: LanguageRegistry) -> Self {
47 let graph = Graph::new(workspace.clone(), languages.clone());
48 Self {
49 workspace,
50 languages,
51 file_previews: Arc::new(Mutex::new(crate::capabilities::file::FileCache::default())),
52 retention: Retention::default(),
53 oracle: None,
54 graph: Arc::new(Mutex::new(graph)),
55 operation: Arc::new(Mutex::new(())),
56 dirty: Arc::new(AtomicBool::new(false)),
57 queries: Arc::new(Mutex::new(crate::query_store::QueryStore::default())),
58 query_revision: Arc::new(AtomicU64::new(0)),
59 cancellation: None,
60 plans: Arc::new(Mutex::new(crate::plan_store::PlanStore::default())),
61 }
62 }
63
64 pub fn with_retention(self, retention: Retention) -> Self {
67 Self { retention, ..self }
68 }
69
70 pub fn run(&self, request: crate::Request) -> Result<Execution, EngineError> {
82 let _operation = self.operation();
83 self.check_read()?;
84 let result = (|| {
85 Ok(match request {
86 crate::Request::DiscardPlan(query) => {
87 Execution::Completed(crate::Answer::DiscardPlan(query.execute_in(self)?))
88 }
89 crate::Request::ValidatePlan(query) => {
90 Execution::Completed(crate::Answer::ValidatePlan(query.execute_in(self)?))
91 }
92 crate::Request::ApplyPlan(query) => {
93 Execution::Completed(crate::Answer::ApplyPlan(query.execute_in(self)?))
94 }
95 crate::Request::InspectPlan(query) => {
96 Execution::Completed(crate::Answer::InspectPlan(query.execute_in(self)?))
97 }
98 crate::Request::PrepareMove(query) => {
99 Execution::Completed(crate::Answer::PrepareMove(query.execute_in(self)?))
100 }
101 crate::Request::PrepareRewrite(query) => {
102 Execution::Completed(crate::Answer::PrepareRewrite(query.execute_in(self)?))
103 }
104 crate::Request::ReviewPlan(query) => {
105 Execution::Completed(crate::Answer::ReviewPlan(query.execute_in(self)?))
106 }
107 crate::Request::PrepareRename(query) => {
108 Execution::Completed(crate::Answer::PrepareRename(query.execute_in(self)?))
109 }
110 #[cfg(feature = "schema")]
111 crate::Request::Schema(query) => {
112 Execution::Completed(crate::Answer::Schema(query.execute()?))
113 }
114 crate::Request::SearchPage(query) => {
115 Execution::Completed(crate::Answer::SearchPage(query.execute_in(self)?))
116 }
117 crate::Request::ContextPage(query) => {
118 Execution::Completed(crate::Answer::ContextPage(query.execute_in(self)?))
119 }
120 crate::Request::Continue(query) => {
121 Execution::Completed(crate::Answer::Continue(query.execute_in(self)?))
122 }
123 crate::Request::Expand(query) => {
124 Execution::Completed(crate::Answer::Expand(query.execute_in(self)?))
125 }
126 crate::Request::Discover(query) => {
127 Execution::Completed(crate::Answer::Discover(query.execute(self)))
128 }
129 crate::Request::Context(query) => Execution::Completed(crate::Answer::Context(
130 query.execute_in(&mut *self.graph()?)?,
131 )),
132 crate::Request::PrepareMoveSymbol(query) => {
133 Execution::Completed(crate::Answer::PrepareMoveSymbol(query.execute_in(self)?))
134 }
135 crate::Request::SymbolMoveCandidates(query) => {
136 Execution::Completed(crate::Answer::SymbolMoveCandidates(
137 query.execute_in(&mut *self.graph()?, self.workspace())?,
138 ))
139 }
140 crate::Request::Relationships(query) => {
141 Execution::Completed(crate::Answer::Relationships(query.execute_in(self)?))
142 }
143 crate::Request::Resolve(query) => Execution::Completed(crate::Answer::Resolve(
144 query.execute_in(&mut *self.graph()?)?,
145 )),
146 crate::Request::Navigate(query) => Execution::Completed(crate::Answer::Navigate(
147 query.execute_in(&mut *self.graph()?)?,
148 )),
149 crate::Request::Search(query) => Execution::Completed(crate::Answer::Search(
150 query.execute_in(&mut *self.graph()?)?,
151 )),
152 crate::Request::Outline(query) => Execution::Completed(crate::Answer::Outline(
153 query.execute_in(&mut *self.graph()?, self.workspace())?,
154 )),
155 crate::Request::References(query) => Execution::Completed(
156 crate::Answer::References(query.execute_in(&mut *self.graph()?)?),
157 ),
158 crate::Request::Where(query) => Execution::Completed(crate::Answer::Where(
159 query.execute_in(&mut *self.graph()?, self.workspace())?,
160 )),
161 crate::Request::Deps(query) => Execution::Completed(crate::Answer::Deps(
162 query.execute_in(&mut *self.graph()?, self.workspace())?,
163 )),
164 crate::Request::Explain(query) => Execution::Completed(crate::Answer::Explain(
165 query.execute_in(&mut *self.graph()?, self.workspace())?,
166 )),
167 crate::Request::Surface(query) => Execution::Completed(crate::Answer::Surface(
168 query.execute_in(&mut *self.graph()?)?,
169 )),
170 crate::Request::Impact(query) => Execution::Completed(crate::Answer::Impact(
171 query.execute_in(&mut *self.graph()?)?,
172 )),
173 crate::Request::Dead(query) => Execution::Completed(crate::Answer::Dead(
174 query.execute_in(&mut *self.graph()?)?,
175 )),
176 crate::Request::Imports(query) => Execution::Completed(crate::Answer::Imports(
177 query.execute_in(&mut *self.graph()?, self.workspace())?,
178 )),
179 crate::Request::WorkspaceFiles(query) => {
180 Execution::Completed(crate::Answer::WorkspaceFiles(query.execute_in(self)?))
181 }
182 crate::Request::File(query) => {
183 Execution::Completed(crate::Answer::File(query.execute_in(self)?))
184 }
185 crate::Request::Rename { intent, apply } => {
186 let planned = {
187 let mut graph = self.graph()?;
188 intent.plan_in(&mut graph, self.workspace())?
189 };
190 self.mutation(planned, apply)?
191 }
192 crate::Request::Move { intent, apply } => {
193 let planned = {
194 let mut graph = self.graph()?;
195 intent.plan_in(&mut graph, self.workspace())?
196 };
197 self.mutation(planned, apply)?
198 }
199 crate::Request::MoveSymbol { intent, apply } => {
200 let planned = {
201 let mut graph = self.graph()?;
202 intent.plan_in(&mut graph, self.workspace())?
203 };
204 self.mutation(planned, apply)?
205 }
206 crate::Request::Rewrite { intent, apply } => {
207 let planned = {
208 let mut graph = self.graph()?;
209 intent.plan_in(&mut graph, self.workspace())?
210 };
211 self.mutation(planned, apply)?
212 }
213 crate::Request::Batch { intent, apply } => {
214 self.mutation(intent.plan_in(self)?, apply)?
215 }
216 crate::Request::History => Execution::Completed(crate::Answer::History(
217 crate::Ledger::new(self).history_in()?,
218 )),
219 crate::Request::Undo => {
220 Execution::Completed(crate::Answer::Undo(crate::Ledger::new(self).undo_in()?))
221 }
222 })
223 })();
224 self.check_read()?;
225 result
226 }
227
228 fn mutation<T: crate::Mutation>(
229 &self,
230 planned: crate::Planned<T>,
231 apply: bool,
232 ) -> Result<Execution, EngineError> {
233 if apply {
234 Ok(Execution::Applied(
235 crate::Apply(planned).apply_in(self)?.into_mutation(),
236 ))
237 } else {
238 Ok(Execution::Preview(planned.into_mutation()))
239 }
240 }
241
242 pub fn with_oracle(mut self, oracle: Arc<dyn Oracle>) -> Self {
248 {
249 let _operation = self.operation();
250 let mut graph = self
251 .graph
252 .lock()
253 .unwrap_or_else(std::sync::PoisonError::into_inner);
254 *graph = Graph::new(self.workspace.clone(), self.languages.clone())
255 .with_oracle(oracle.clone());
256 }
257 self.oracle = Some(oracle);
258 self
259 }
260
261 pub fn touched(&self) {
264 self.dirty.store(true, Ordering::Release);
265 self.query_revision.fetch_add(1, Ordering::AcqRel);
266 }
267
268 pub fn root(&self) -> &Path {
270 self.workspace.root()
271 }
272
273 pub fn language_ids(&self) -> Vec<LanguageId> {
275 self.languages.iter().map(|l| l.id().clone()).collect()
276 }
277
278 pub(crate) fn plans(&self) -> MutexGuard<'_, crate::plan_store::PlanStore> {
279 self.plans
280 .lock()
281 .unwrap_or_else(std::sync::PoisonError::into_inner)
282 }
283 pub(crate) fn queries(&self) -> MutexGuard<'_, crate::query_store::QueryStore> {
284 self.queries
285 .lock()
286 .unwrap_or_else(std::sync::PoisonError::into_inner)
287 }
288 pub(crate) fn query_revision(&self) -> u64 {
289 self.query_revision.load(Ordering::Acquire)
290 }
291
292 pub(crate) fn with_cancellation(&self, cancellation: crate::ReadCancellation) -> Self {
293 Self {
294 cancellation: Some(cancellation),
295 ..self.clone()
296 }
297 }
298 pub(crate) fn without_cancellation(&self) -> Self {
299 Self {
300 cancellation: None,
301 ..self.clone()
302 }
303 }
304 pub(crate) fn cancellation(&self) -> Option<crate::ReadCancellation> {
305 self.cancellation.clone()
306 }
307 pub(crate) fn check_read(&self) -> Result<(), EngineError> {
308 self.cancellation
309 .as_ref()
310 .map_or(Ok(()), crate::ReadCancellation::check)
311 }
312 pub(crate) fn publish_read<T>(
313 &self,
314 publish: impl FnOnce() -> Result<T, EngineError>,
315 ) -> Result<T, EngineError> {
316 match &self.cancellation {
317 Some(c) => c.complete(publish),
318 None => publish(),
319 }
320 }
321
322 pub(crate) fn oracle(&self) -> Option<Arc<dyn Oracle>> {
323 self.oracle.clone()
324 }
325
326 pub(crate) fn workspace(&self) -> &Workspace {
327 &self.workspace
328 }
329
330 pub(crate) fn languages(&self) -> &LanguageRegistry {
331 &self.languages
332 }
333
334 pub(crate) fn operation(&self) -> MutexGuard<'_, ()> {
336 self.operation
337 .lock()
338 .unwrap_or_else(std::sync::PoisonError::into_inner)
339 }
340
341 pub(crate) fn staged(&self) -> (Engine, Workspace) {
343 let staging = self.workspace.staged();
344 let engine =
345 Engine::new(staging.clone(), self.languages.clone()).with_retention(Retention::PerCall);
346 (engine, staging)
347 }
348
349 pub(crate) fn graph(&self) -> Result<MutexGuard<'_, Graph>, EngineError> {
352 let mut graph = self
353 .graph
354 .lock()
355 .unwrap_or_else(std::sync::PoisonError::into_inner);
356 if self.dirty.swap(false, Ordering::AcqRel) {
357 graph.touched();
358 }
359 if self.retention == Retention::PerCall {
360 let fresh = Graph::new(self.workspace.clone(), self.languages.clone());
361 *graph = match &self.oracle {
362 Some(oracle) => fresh.with_oracle(oracle.clone()),
363 None => fresh,
364 };
365 }
366 graph.cancellation = self.cancellation();
367 graph.refresh(self.retention)?;
368 Ok(graph)
369 }
370}
371
372#[derive(Debug)]
374pub enum Execution {
375 Completed(crate::Answer),
376 Preview(crate::Planned<crate::MutationAnswer>),
377 Applied(crate::Applied<crate::MutationAnswer>),
378}
379
380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
382pub enum ExecutionKind {
383 Completed,
384 Preview,
385 Applied,
386}
387
388impl std::fmt::Display for ExecutionKind {
389 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390 f.write_str(match self {
391 Self::Completed => "completed",
392 Self::Preview => "preview",
393 Self::Applied => "applied",
394 })
395 }
396}
397
398impl Execution {
399 pub fn kind(&self) -> ExecutionKind {
400 match self {
401 Self::Completed(_) => ExecutionKind::Completed,
402 Self::Preview(_) => ExecutionKind::Preview,
403 Self::Applied(_) => ExecutionKind::Applied,
404 }
405 }
406
407 pub fn into_answer(self) -> crate::Answer {
409 match self {
410 Self::Completed(answer) => answer,
411 Self::Preview(planned) => planned.into_inner().into(),
412 Self::Applied(applied) => applied.into_inner().into(),
413 }
414 }
415
416 pub fn into_preview(self) -> Result<crate::Planned<crate::MutationAnswer>, EngineError> {
417 match self {
418 Self::Preview(planned) => Ok(planned),
419 other => Err(EngineError::ExecutionKind {
420 expected: ExecutionKind::Preview,
421 actual: other.kind(),
422 }),
423 }
424 }
425
426 pub fn into_applied(self) -> Result<crate::Applied<crate::MutationAnswer>, EngineError> {
427 match self {
428 Self::Applied(applied) => Ok(applied),
429 other => Err(EngineError::ExecutionKind {
430 expected: ExecutionKind::Applied,
431 actual: other.kind(),
432 }),
433 }
434 }
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 #[test]
442 fn engine_clones_exclude_whole_operations_even_without_a_graph() {
443 let engine = Engine::new(
444 Workspace::new("/ws", Arc::new(crate::MemoryVfs::new())),
445 LanguageRegistry::new(),
446 );
447 let guard = engine.operation();
448 let clone = engine.clone();
449 let (started, ready) = std::sync::mpsc::channel();
450 let (finished, result) = std::sync::mpsc::channel();
451 let worker = std::thread::spawn(move || {
452 started.send(()).unwrap();
453 finished.send(crate::Ledger::new(&clone).history()).unwrap();
454 });
455 ready.recv().unwrap();
456 assert!(matches!(
457 result.recv_timeout(std::time::Duration::from_millis(50)),
458 Err(std::sync::mpsc::RecvTimeoutError::Timeout)
459 ));
460 drop(guard);
461 assert!(result.recv().unwrap().unwrap().entries.is_empty());
462 worker.join().unwrap();
463 }
464}