1pub(crate) mod review;
3use crate::capabilities::validation::baseline::ValidationBaseline;
4use crate::graph::query_snapshot::QuerySnapshot;
5use crate::{
6 ContentId, Engine, EngineError, Failure, MutationAnswer, Planned, RenameIntent, RewriteIntent,
7 SourceVersion,
8};
9use review::CapturedReview;
10pub use review::{
11 PlanPreview, PlanReviewCursor, PlanReviewItem, PlanReviewKind, PlanReviewPage, PlanReviewReply,
12 ReviewMutation, ReviewSection, ReviewTotals,
13};
14use serde::{Deserialize, Serialize};
15use std::sync::Arc;
16use std::time::Instant;
17
18#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21#[serde(transparent)]
22pub struct PlanId(pub(crate) String);
23
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
26#[serde(deny_unknown_fields)]
27pub struct PrepareRenameQuery {
28 pub intent: RenameIntent,
29 #[serde(default = "PrepareRenameQuery::default_max_bytes")]
30 #[cfg_attr(feature = "schema", schemars(range(min = 1024, max = 1048576)))]
31 pub max_bytes: usize,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
33 pub page: Option<crate::PageBudget>,
34}
35impl PrepareRenameQuery {
36 pub fn default_max_bytes() -> usize {
37 16_384
38 }
39 pub fn execute(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
40 let _operation = engine.operation();
41 self.execute_in(engine)
42 }
43 pub(crate) fn execute_in(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
44 let budget = PlanReviewReply::budget(self.max_bytes, self.page.as_ref())?;
45 let revision = engine.query_revision();
46 let (mut graph, snapshot) = QuerySnapshot::capture(engine)?;
47 if let Some(oracle) = engine.oracle() {
48 graph = graph.with_oracle(oracle);
49 }
50 let planned = self.intent.plan_in(&mut graph, engine.workspace())?;
51 RetainedPlan::publish(
52 engine,
53 planned.into_mutation(),
54 snapshot,
55 revision,
56 budget,
57 self.page.is_some(),
58 )
59 }
60}
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
63#[serde(deny_unknown_fields)]
64pub struct PrepareRewriteQuery {
65 pub intent: RewriteIntent,
66 #[serde(default = "PrepareRenameQuery::default_max_bytes")]
67 #[cfg_attr(feature = "schema", schemars(range(min = 1024, max = 1048576)))]
68 pub max_bytes: usize,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub page: Option<crate::PageBudget>,
71}
72impl PrepareRewriteQuery {
73 pub fn execute(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
74 let _operation = engine.operation();
75 self.execute_in(engine)
76 }
77 pub(crate) fn execute_in(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
78 let budget = PlanReviewReply::budget(self.max_bytes, self.page.as_ref())?;
79 let revision = engine.query_revision();
80 let (mut graph, snapshot) = QuerySnapshot::capture(engine)?;
81 let planned = self.intent.plan_in(&mut graph, engine.workspace())?;
82 RetainedPlan::publish(
83 engine,
84 planned.into_mutation(),
85 snapshot,
86 revision,
87 budget,
88 self.page.is_some(),
89 )
90 }
91}
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
95#[serde(deny_unknown_fields)]
96pub struct PrepareMoveSymbolIntent {
97 pub name: String,
98 pub from: crate::RelPath,
99 pub to: crate::RelPath,
100 #[serde(default, skip_serializing_if = "crate::Selection::is_all")]
101 pub selection: crate::Selection,
102 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub expected_content: Option<crate::ContentId>,
104}
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
107#[serde(deny_unknown_fields)]
108pub struct PrepareMoveSymbolQuery {
109 pub intent: PrepareMoveSymbolIntent,
110 #[serde(default = "PrepareRenameQuery::default_max_bytes")]
111 #[cfg_attr(feature = "schema", schemars(range(min = 1024, max = 1048576)))]
112 pub max_bytes: usize,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub page: Option<crate::PageBudget>,
115}
116impl PrepareMoveSymbolQuery {
117 pub fn execute(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
118 let _operation = engine.operation();
119 self.execute_in(engine)
120 }
121 pub(crate) fn execute_in(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
122 PrepareMoveIntent {
123 from: self.intent.from.clone(),
124 to: self.intent.to.clone(),
125 }
126 .validate()?;
127 let budget = PlanReviewReply::budget(self.max_bytes, self.page.as_ref())?;
128 let revision = engine.query_revision();
129 let (mut graph, snapshot) = QuerySnapshot::capture(engine)?;
130 if let Some(oracle) = engine.oracle() {
131 graph = graph.with_oracle(oracle);
132 }
133 let mut intent = crate::MoveSymbolIntent::new(
134 self.intent.name,
135 self.intent.from.to_path_buf(),
136 self.intent.to.to_path_buf(),
137 )
138 .selecting(self.intent.selection);
139 intent.expected_content = self.intent.expected_content;
140 let planned = intent.plan_in(&mut graph, engine.workspace())?;
141 RetainedPlan::publish(
142 engine,
143 planned.into_mutation(),
144 snapshot,
145 revision,
146 budget,
147 self.page.is_some(),
148 )
149 }
150}
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
154#[serde(deny_unknown_fields)]
155pub struct PrepareMoveIntent {
156 pub from: crate::RelPath,
157 pub to: crate::RelPath,
158}
159impl PrepareMoveIntent {
160 fn validate(&self) -> Result<(), EngineError> {
161 for path in [&self.from, &self.to] {
162 if path.as_os_str().is_empty()
163 || path.is_absolute()
164 || path.components().any(|part| {
165 !matches!(
166 part,
167 std::path::Component::Normal(_) | std::path::Component::CurDir
168 )
169 })
170 || !path
171 .components()
172 .any(|part| matches!(part, std::path::Component::Normal(_)))
173 {
174 return Err(EngineError::InvalidMovePath { path: path.clone() });
175 }
176 }
177 Ok(())
178 }
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
183#[serde(deny_unknown_fields)]
184pub struct PrepareMoveQuery {
185 pub intent: PrepareMoveIntent,
186 #[serde(default = "PrepareRenameQuery::default_max_bytes")]
187 #[cfg_attr(feature = "schema", schemars(range(min = 1024, max = 1048576)))]
188 pub max_bytes: usize,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub page: Option<crate::PageBudget>,
191}
192impl PrepareMoveQuery {
193 pub fn execute(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
194 let _operation = engine.operation();
195 self.execute_in(engine)
196 }
197 pub(crate) fn execute_in(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
198 self.intent.validate()?;
199 let budget = PlanReviewReply::budget(self.max_bytes, self.page.as_ref())?;
200 let revision = engine.query_revision();
201 let (mut graph, snapshot) = QuerySnapshot::capture(engine)?;
202 if let Some(oracle) = engine.oracle() {
203 graph = graph.with_oracle(oracle);
204 }
205 let intent =
206 crate::MoveIntent::new(self.intent.from.to_path_buf(), self.intent.to.to_path_buf());
207 let planned = intent.plan_in(&mut graph, engine.workspace())?;
208 RetainedPlan::publish(
209 engine,
210 planned.into_mutation(),
211 snapshot,
212 revision,
213 budget,
214 self.page.is_some(),
215 )
216 }
217}
218#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
219#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
220#[serde(deny_unknown_fields)]
221pub struct InspectPlanQuery {
222 pub plan_id: PlanId,
223 #[serde(default = "PrepareRenameQuery::default_max_bytes")]
224 #[cfg_attr(feature = "schema", schemars(range(min = 1024, max = 1048576)))]
225 pub max_bytes: usize,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub page: Option<crate::PageBudget>,
228}
229impl InspectPlanQuery {
230 pub fn execute(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
231 let _operation = engine.operation();
232 self.execute_in(engine)
233 }
234 pub(crate) fn execute_in(self, engine: &Engine) -> Result<PlanReviewReply, EngineError> {
235 let budget = PlanReviewReply::budget(self.max_bytes, self.page.as_ref())?;
236 let review = engine.plans().review(&self.plan_id, Instant::now())?;
237 let result = if self.page.is_some() && matches!(review.status, PlanStatus::Prepared { .. })
238 {
239 let captured = engine.plans().captured(&self.plan_id, Instant::now())?;
240 PlanReviewReply::Page(captured.page(engine, &self.plan_id, 0, 0, budget.clone())?)
241 } else {
242 PlanReviewReply::Complete(review)
243 };
244 budget.check(&result)?;
245 Ok(result)
246 }
247}
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
250#[serde(deny_unknown_fields)]
251pub struct ReviewPlanQuery {
252 pub cursor: PlanReviewCursor,
253 #[serde(default)]
254 pub page: crate::PageBudget,
255}
256impl ReviewPlanQuery {
257 pub fn execute(self, engine: &Engine) -> Result<PlanReviewPage, EngineError> {
258 let _operation = engine.operation();
259 self.execute_in(engine)
260 }
261 pub(crate) fn execute_in(self, engine: &Engine) -> Result<PlanReviewPage, EngineError> {
262 self.page.validate()?;
263 let (id, record, offset) = self.cursor.position()?;
264 let captured = engine.plans().captured(&id, Instant::now())?;
265 captured.page(engine, &id, record, offset, self.page)
266 }
267}
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
270#[serde(deny_unknown_fields)]
271pub struct ApplyPlanQuery {
272 pub plan_id: PlanId,
273}
274impl ApplyPlanQuery {
275 pub fn execute(self, engine: &Engine) -> Result<PlanReceipt, EngineError> {
276 let _operation = engine.operation();
277 self.execute_in(engine)
278 }
279 pub(crate) fn execute_in(self, engine: &Engine) -> Result<PlanReceipt, EngineError> {
280 let review = engine.plans().review(&self.plan_id, Instant::now())?;
281 match review.status {
282 PlanStatus::Applied { receipt } => return Ok(receipt),
283 PlanStatus::Prepared { .. } => {}
284 _ => return Err(EngineError::PlanConsumed),
285 }
286 let pending = engine.plans().take(&self.plan_id)?;
289 let result = pending.apply(engine, self.plan_id.clone());
290 engine.plans().complete(&self.plan_id, &result);
291 result
292 }
293}
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
296#[serde(deny_unknown_fields)]
297pub struct DiscardPlanQuery {
298 pub plan_id: PlanId,
299}
300impl DiscardPlanQuery {
301 pub fn execute(self, engine: &Engine) -> Result<PlanReview, EngineError> {
302 let _operation = engine.operation();
303 self.execute_in(engine)
304 }
305 pub(crate) fn execute_in(self, engine: &Engine) -> Result<PlanReview, EngineError> {
306 engine.publish_read(|| engine.plans().discard(&self.plan_id, Instant::now()))
307 }
308}
309#[derive(Debug, Clone, Serialize, Deserialize)]
310#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
311pub struct PlanReview {
312 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub validation: Option<crate::ValidationReport>,
315 pub plan_id: PlanId,
316 pub lifetime_seconds: u64,
318 #[serde(flatten)]
319 pub status: PlanStatus,
320}
321#[derive(Debug, Clone, Serialize, Deserialize)]
322#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
323#[serde(tag = "state", rename_all = "snake_case")]
324#[allow(clippy::large_enum_variant)]
325pub enum PlanStatus {
326 Prepared { preview: PlanPreview },
327 Applied { receipt: PlanReceipt },
328 Failed { failure: Failure },
329 Discarded,
330}
331#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
332#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
333pub struct PlanReceipt {
334 pub plan_id: PlanId,
335 pub history_id: u64,
337 pub files: Vec<SourceVersion>,
339}
340
341pub(crate) struct RetainedPlan {
342 pub review: PlanReview,
343 pub pending: Option<PendingPlan>,
344 pub captured: Option<Arc<CapturedReview>>,
345 pub baseline: Option<Arc<ValidationBaseline>>,
346 pub bytes: usize,
347}
348pub(crate) struct PendingPlan {
349 planned: Planned<MutationAnswer>,
350 baseline: Arc<ValidationBaseline>,
351 revision: u64,
352}
353impl RetainedPlan {
354 fn publish(
355 engine: &Engine,
356 planned: Planned<MutationAnswer>,
357 snapshot: QuerySnapshot,
358 revision: u64,
359 budget: crate::PageBudget,
360 paged: bool,
361 ) -> Result<PlanReviewReply, EngineError> {
362 if revision != engine.query_revision() {
363 return Err(EngineError::StalePlan);
364 }
365 let preview = PlanPreview::from_mutation(&planned)?;
366 let review = PlanReview {
367 plan_id: engine.plans().allocate(),
368 validation: None,
369 lifetime_seconds: crate::PlanLimits::default().lifetime_seconds,
370 status: PlanStatus::Prepared { preview },
371 };
372 let baseline = ValidationBaseline::capture(engine, snapshot, planned.preview())?;
373 let retained = Self::new(review.clone(), planned, baseline, revision);
374 let reply = if paged {
375 PlanReviewReply::Page(retained.captured.as_ref().expect("prepared review").page(
376 engine,
377 &review.plan_id,
378 0,
379 0,
380 budget.clone(),
381 )?)
382 } else {
383 PlanReviewReply::Complete(review)
384 };
385 budget.check(&reply)?;
386 retained
387 .baseline
388 .as_ref()
389 .expect("prepared baseline")
390 .validate_before(engine)?;
391 if revision != engine.query_revision() {
392 return Err(EngineError::StalePlan);
393 }
394 engine.publish_read(|| engine.plans().insert(retained, Instant::now()))?;
395 Ok(reply)
396 }
397 pub(crate) fn new(
398 review: PlanReview,
399 planned: Planned<MutationAnswer>,
400 baseline: ValidationBaseline,
401 revision: u64,
402 ) -> Self {
403 let source_bytes = planned
406 .preview()
407 .iter()
408 .map(|file| file.before.len().saturating_add(file.after.len()))
409 .fold(0usize, usize::saturating_add);
410 let bytes = source_bytes
411 .saturating_mul(4)
412 .saturating_add(crate::query_store::QueryStore::weight(&review))
413 .saturating_add(crate::query_store::QueryStore::weight(&baseline).saturating_mul(2));
414 let captured = match &review.status {
415 PlanStatus::Prepared { preview } => {
416 Some(Arc::new(CapturedReview::new(preview.clone())))
417 }
418 _ => None,
419 };
420 let bytes = bytes.saturating_add(captured.as_ref().map_or(0, |c| c.weight()));
421 let baseline = Arc::new(baseline);
422 Self {
423 review,
424 captured,
425 baseline: Some(baseline.clone()),
426 pending: Some(PendingPlan {
427 planned,
428 baseline,
429 revision,
430 }),
431 bytes,
432 }
433 }
434}
435impl PendingPlan {
436 fn apply(self, engine: &Engine, plan_id: PlanId) -> Result<PlanReceipt, EngineError> {
437 if self.revision != engine.query_revision() {
438 return Err(EngineError::StalePlan);
439 }
440 self.baseline
441 .validate_before(engine)
442 .map_err(|error| match error {
443 EngineError::StaleQuery | EngineError::StaleSource { .. } => EngineError::StalePlan,
444 other => other,
445 })?;
446 let files = self
447 .planned
448 .preview()
449 .iter()
450 .map(|file| SourceVersion {
451 path: file.moved_to.clone().unwrap_or_else(|| file.path.clone()),
452 content: ContentId::of(&file.after),
453 })
454 .collect();
455 let mut receipt = PlanReceipt {
456 plan_id,
457 history_id: u64::MAX,
458 files,
459 };
460 crate::PageBudget::MAXIMUM.check(&receipt)?;
462 let applied = crate::Apply(self.planned).apply_in(engine)?;
463 receipt.history_id = applied.history_id();
464 Ok(receipt)
465 }
466}
467impl crate::report::Document {
468 pub(crate) fn plan_review(review: &PlanReview) -> Self {
469 use crate::protocol::display::{Line, Role};
470 let mut doc = match &review.status {
471 PlanStatus::Prepared { preview } => match preview {
472 PlanPreview::Rename(r) => Self::rename(r),
473 PlanPreview::Rewrite(r) => Self::rewrite(r),
474 PlanPreview::Move(r) => Self::move_file(r),
475 PlanPreview::MoveSymbol(r) => Self::move_symbol(r),
476 },
477 PlanStatus::Applied { receipt } => Self::plan_receipt(receipt),
478 PlanStatus::Failed { failure } => Self::error(failure),
479 PlanStatus::Discarded => Self::new(),
480 };
481 if let Some(validation) = &review.validation {
482 let result = Self::validation(validation);
483 let (body, notes) = result.parts();
484 for block in body {
485 doc.block_body(block.clone());
486 }
487 for block in notes {
488 doc.block_note(block.clone());
489 }
490 }
491 doc.notes([Line::single(Role::Plain, "Plan: ").and(Role::Plain, &review.plan_id.0)]);
492 doc
493 }
494 pub(crate) fn plan_receipt(receipt: &PlanReceipt) -> Self {
495 use crate::protocol::display::{Line, Role};
496 let mut doc = Self::new();
497 doc.body([Line::single(Role::Strong, "Applied reviewed plan")
498 .and(Role::Plain, format!(" (history {})", receipt.history_id))]);
499 for file in &receipt.files {
500 doc.body([Line::single(Role::Path, file.path.to_string())]);
501 }
502 doc
503 }
504}