1use super::{PlanId, PlanReview};
3use crate::{Engine, EngineError, Intent, Move, MutationAnswer, PageBudget, Rename, Rewrite};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use std::sync::Arc;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
10#[serde(untagged)]
11pub enum PlanPreview {
12 Rename(Arc<Rename>),
13 Rewrite(Arc<Rewrite>),
14 Move(Arc<Move>),
15 MoveSymbol(Arc<crate::MoveSymbol>),
16}
17impl PlanPreview {
18 pub(crate) fn from_mutation(value: &MutationAnswer) -> Result<Self, EngineError> {
19 match value {
20 MutationAnswer::Rename(r) => Ok(Self::Rename(Arc::new(r.clone()))),
21 MutationAnswer::Rewrite(r) => Ok(Self::Rewrite(Arc::new(r.clone()))),
22 MutationAnswer::Move(r) => Ok(Self::Move(Arc::new(r.clone()))),
23 MutationAnswer::MoveSymbol(r) => Ok(Self::MoveSymbol(Arc::new(r.clone()))),
24 _ => Err(EngineError::InvalidPlan),
25 }
26 }
27 pub fn files(&self) -> &[crate::FileChange] {
28 match self {
29 Self::Rename(r) => &r.files,
30 Self::Rewrite(r) => &r.files,
31 Self::Move(r) => &r.files,
32 Self::MoveSymbol(r) => &r.files,
33 }
34 }
35 fn intent(&self) -> Intent {
36 match self {
37 Self::Rename(r) => Intent::Rename(r.intent.clone()),
38 Self::Rewrite(r) => Intent::Rewrite(r.intent.clone()),
39 Self::Move(r) => Intent::Move(r.intent.clone()),
40 Self::MoveSymbol(r) => Intent::MoveSymbol(r.intent.clone()),
41 }
42 }
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
47#[serde(untagged)]
48#[allow(clippy::large_enum_variant)]
49pub enum PlanReviewReply {
50 Complete(PlanReview),
51 Page(PlanReviewPage),
52}
53impl PlanReviewReply {
54 pub fn into_complete(self) -> Result<PlanReview, EngineError> {
55 match self {
56 Self::Complete(r) => Ok(r),
57 Self::Page(_) => Err(EngineError::InvalidPlan),
58 }
59 }
60 pub(crate) fn budget(
61 max_bytes: usize,
62 page: Option<&PageBudget>,
63 ) -> Result<PageBudget, EngineError> {
64 let mut budget = PageBudget {
65 max_bytes,
66 max_items: 1,
67 };
68 budget.validate()?;
69 if let Some(page) = page {
70 page.validate()?;
71 budget.max_items = page.max_items;
72 budget.max_bytes = budget.max_bytes.min(page.max_bytes);
73 }
74 Ok(budget)
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
81#[serde(transparent)]
82pub struct PlanReviewCursor(String);
83impl PlanReviewCursor {
84 fn new(id: &PlanId, record: usize, offset: usize) -> Self {
85 Self(format!("r1.{}.{record:016x}.{offset:016x}", id.0))
86 }
87 pub(crate) fn position(&self) -> Result<(PlanId, usize, usize), EngineError> {
88 let parts: Vec<_> = self.0.split('.').collect();
89 if parts.len() != 6
90 || parts[0] != "r1"
91 || parts[1] != "p1"
92 || !parts[2..]
93 .iter()
94 .all(|p| p.len() == 16 && p.bytes().all(|b| b.is_ascii_hexdigit()))
95 {
96 return Err(EngineError::InvalidCursor);
97 }
98 let record = usize::from_str_radix(parts[4], 16).map_err(|_| EngineError::InvalidCursor)?;
99 let offset = usize::from_str_radix(parts[5], 16).map_err(|_| EngineError::InvalidCursor)?;
100 Ok((PlanId(parts[1..4].join(".")), record, offset))
101 }
102}
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
104#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
105#[serde(rename_all = "snake_case")]
106pub enum ReviewSection {
107 Move,
108 Piece,
109 Notice,
110 Respelling,
111 Declaration,
112 Occurrence,
113 File,
114 Edit,
115 Diff,
116}
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
119pub struct ReviewTotals {
120 pub declarations: usize,
121 pub occurrences: usize,
122 pub files: usize,
123 pub edits: usize,
124 #[serde(default, skip_serializing_if = "ReviewTotals::zero")]
125 pub notices: usize,
126 #[serde(default, skip_serializing_if = "ReviewTotals::zero")]
127 pub respellings: usize,
128 #[serde(default, skip_serializing_if = "ReviewTotals::zero")]
129 pub pieces: usize,
130}
131impl ReviewTotals {
132 fn zero(value: &usize) -> bool {
133 *value == 0
134 }
135}
136#[derive(Debug, Clone, Serialize, Deserialize)]
139#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
140#[serde(tag = "kind", rename_all = "snake_case")]
141pub enum PlanReviewItem {
142 Metadata {
143 section: ReviewSection,
144 index: usize,
145 #[serde(skip_serializing_if = "Option::is_none")]
146 file_index: Option<usize>,
147 value: Value,
148 },
149 Text {
150 section: ReviewSection,
151 index: usize,
152 #[serde(skip_serializing_if = "Option::is_none")]
153 file_index: Option<usize>,
154 field: String,
155 offset: usize,
156 total_bytes: usize,
157 text: String,
158 complete: bool,
159 },
160}
161#[derive(Debug, Clone, Serialize, Deserialize)]
162#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
163pub struct PlanReviewPage {
164 pub kind: PlanReviewKind,
165 pub plan_id: PlanId,
166 pub lifetime_seconds: u64,
167 pub review_id: crate::ContentId,
168 pub mutation: ReviewMutation,
169 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub intent: Option<Intent>,
171 pub totals: ReviewTotals,
172 pub items: Vec<PlanReviewItem>,
173 pub next_cursor: Option<PlanReviewCursor>,
174}
175#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
176#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
177#[serde(rename_all = "snake_case")]
178pub enum PlanReviewKind {
179 PlanReview,
180}
181#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
182#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
183#[serde(rename_all = "snake_case")]
184pub enum ReviewMutation {
185 Rename,
186 Rewrite,
187 Move,
188 MoveSymbol,
189}
190
191pub(crate) struct CapturedReview {
192 preview: PlanPreview,
193 identity: crate::ContentId,
194 totals: ReviewTotals,
195 records: Vec<PlanReviewItem>,
196}
197impl CapturedReview {
198 pub(crate) fn new(preview: PlanPreview) -> Self {
199 let identity =
200 crate::ContentId::of(&serde_json::to_string(&preview).expect("preview serializes"));
201 let mut review = Self {
202 preview,
203 identity,
204 totals: ReviewTotals {
205 declarations: 0,
206 occurrences: 0,
207 files: 0,
208 edits: 0,
209 notices: 0,
210 respellings: 0,
211 pieces: 0,
212 },
213 records: vec![],
214 };
215 let rename = match &review.preview {
216 PlanPreview::Rename(r) => Some(r.clone()),
217 PlanPreview::Rewrite(_) | PlanPreview::Move(_) | PlanPreview::MoveSymbol(_) => None,
218 };
219 if let Some(r) = rename {
220 review.totals.declarations = r.declarations.len();
221 review.totals.occurrences = r.occurrences.len();
222 for (index, declaration) in r.declarations.iter().enumerate() {
223 review.record(
224 ReviewSection::Declaration,
225 index,
226 None,
227 serde_json::to_value(declaration).expect("match serializes"),
228 );
229 }
230 for (index, occurrence) in r.occurrences.iter().enumerate() {
231 review.record(
232 ReviewSection::Occurrence,
233 index,
234 None,
235 serde_json::to_value(occurrence).expect("occurrence serializes"),
236 );
237 }
238 }
239 if let PlanPreview::Move(moved) = &review.preview {
240 let moved = moved.clone();
241 let mut metadata = serde_json::json!({"from": moved.from, "to": moved.to});
242 if let Some(address) = &moved.from_address {
243 metadata["from_address"] =
244 serde_json::to_value(address).expect("address serializes");
245 }
246 if let Some(address) = &moved.to_address {
247 metadata["to_address"] = serde_json::to_value(address).expect("address serializes");
248 }
249 review.record(ReviewSection::Move, 0, None, metadata);
250 review.totals.notices = moved.notices.len();
251 review.totals.respellings = moved.respellings.len();
252 for (index, notice) in moved.notices.iter().enumerate() {
253 review.record(
254 ReviewSection::Notice,
255 index,
256 None,
257 serde_json::to_value(notice).expect("notice serializes"),
258 );
259 }
260 for (index, respelling) in moved.respellings.iter().enumerate() {
261 review.record(
262 ReviewSection::Respelling,
263 index,
264 None,
265 serde_json::to_value(respelling).expect("respelling serializes"),
266 );
267 }
268 }
269 if let PlanPreview::MoveSymbol(moved) = &review.preview {
270 let moved = moved.clone();
271 review.record(
272 ReviewSection::Move,
273 0,
274 None,
275 serde_json::json!({"from": moved.from, "to": moved.to}),
276 );
277 review.totals.declarations = 1;
278 review.totals.pieces = moved.pieces.len();
279 review.record(
280 ReviewSection::Declaration,
281 0,
282 None,
283 serde_json::to_value(&moved.declaration).expect("declaration serializes"),
284 );
285 for (index, piece) in moved.pieces.iter().enumerate() {
286 review.record(
287 ReviewSection::Piece,
288 index,
289 None,
290 serde_json::to_value(piece).expect("piece serializes"),
291 );
292 }
293 review.totals.notices = moved.notices.len();
294 review.totals.respellings = moved.respellings.len();
295 for (index, notice) in moved.notices.iter().enumerate() {
296 review.record(
297 ReviewSection::Notice,
298 index,
299 None,
300 serde_json::to_value(notice).expect("notice serializes"),
301 );
302 }
303 for (index, respelling) in moved.respellings.iter().enumerate() {
304 review.record(
305 ReviewSection::Respelling,
306 index,
307 None,
308 serde_json::to_value(respelling).expect("respelling serializes"),
309 );
310 }
311 }
312 review.totals.files = review.preview.files().len();
313 for index in 0..review.totals.files {
315 let file = &review.preview.files()[index];
316 let mut metadata = serde_json::json!({"path": file.path});
317 if let Some(destination) = &file.moved_to {
318 metadata["moved_to"] = serde_json::to_value(destination).expect("path serializes");
319 }
320 let edits = file
321 .edits
322 .iter()
323 .map(|r| serde_json::to_value(r).expect("edit serializes"))
324 .collect::<Vec<_>>();
325 let diff = file.diff.to_string();
326 review.record(ReviewSection::File, index, None, metadata);
327 review.totals.edits += edits.len();
328 for (edit_index, edit) in edits.into_iter().enumerate() {
329 review.record(ReviewSection::Edit, edit_index, Some(index), edit);
330 }
331 review.records.push(PlanReviewItem::Text {
332 section: ReviewSection::Diff,
333 index,
334 file_index: None,
335 field: "/diff".into(),
336 offset: 0,
337 total_bytes: diff.len(),
338 complete: true,
339 text: diff,
340 });
341 }
342 review
343 }
344 fn record(
345 &mut self,
346 section: ReviewSection,
347 index: usize,
348 file_index: Option<usize>,
349 mut value: Value,
350 ) {
351 let mut text = vec![];
352 Self::text_fields(&mut value, "", &mut text);
353 self.records.push(PlanReviewItem::Metadata {
354 section,
355 index,
356 file_index,
357 value,
358 });
359 for (field, text) in text {
360 self.records.push(PlanReviewItem::Text {
361 section,
362 index,
363 file_index,
364 field,
365 offset: 0,
366 total_bytes: text.len(),
367 complete: true,
368 text,
369 });
370 }
371 }
372 fn text_fields(value: &mut Value, pointer: &str, fields: &mut Vec<(String, String)>) {
373 match value {
374 Value::Object(object) => {
375 for (key, value) in object {
376 let pointer =
377 format!("{pointer}/{}", key.replace('~', "~0").replace('/', "~1"));
378 if matches!(
379 key.as_str(),
380 "text" | "line" | "replacement" | "import" | "item" | "from" | "to"
381 ) && value.is_string()
382 {
383 let text = value.as_str().expect("string").to_owned();
384 if !text.is_empty() {
385 fields.push((pointer, text));
386 *value = Value::String(String::new());
387 }
388 } else {
389 Self::text_fields(value, &pointer, fields);
390 }
391 }
392 }
393 Value::Array(array) => {
394 for (index, value) in array.iter_mut().enumerate() {
395 Self::text_fields(value, &format!("{pointer}/{index}"), fields);
396 }
397 }
398 _ => {}
399 }
400 }
401 pub(crate) fn weight(&self) -> usize {
402 crate::query_store::QueryStore::weight(&self.records)
403 .saturating_add(crate::query_store::QueryStore::weight(&self.preview))
404 }
405 pub(crate) fn page(
406 &self,
407 engine: &Engine,
408 id: &PlanId,
409 mut record: usize,
410 mut offset: usize,
411 budget: PageBudget,
412 ) -> Result<PlanReviewPage, EngineError> {
413 engine.check_read()?;
414 if record > self.records.len() || (record == self.records.len() && offset != 0) {
415 return Err(EngineError::InvalidCursor);
416 }
417 let mut page = PlanReviewPage {
418 kind: PlanReviewKind::PlanReview,
419 plan_id: id.clone(),
420 lifetime_seconds: crate::PlanLimits::default().lifetime_seconds,
421 review_id: self.identity.clone(),
422 mutation: match self.preview {
423 PlanPreview::Rename(_) => ReviewMutation::Rename,
424 PlanPreview::Rewrite(_) => ReviewMutation::Rewrite,
425 PlanPreview::Move(_) => ReviewMutation::Move,
426 PlanPreview::MoveSymbol(_) => ReviewMutation::MoveSymbol,
427 },
428 intent: (record == 0 && offset == 0).then(|| self.preview.intent()),
429 totals: self.totals.clone(),
430 items: vec![],
431 next_cursor: None,
432 };
433 while record < self.records.len() && page.items.len() < budget.max_items {
434 engine.check_read()?;
435 let original = &self.records[record];
436 let length = match original {
437 PlanReviewItem::Text { text, .. } => {
438 if offset >= text.len() && !text.is_empty() || !text.is_char_boundary(offset) {
439 return Err(EngineError::InvalidCursor);
440 }
441 text.len()
442 }
443 _ => {
444 if offset != 0 {
445 return Err(EngineError::InvalidCursor);
446 }
447 0
448 }
449 };
450 let minimum = match original {
451 PlanReviewItem::Text { text, .. } => text[offset..]
452 .chars()
453 .next()
454 .map_or(offset, |c| offset + c.len_utf8()),
455 _ => 0,
456 };
457 let mut best = None;
458 if length.saturating_sub(offset) <= budget.max_bytes {
461 page.items.push(original.chunk(offset, length));
462 page.next_cursor = (record + 1 < self.records.len())
463 .then(|| PlanReviewCursor::new(id, record + 1, 0));
464 if budget.check(&page).is_ok() {
465 best = Some((length, (record + 1, 0)));
466 }
467 page.items.pop();
468 }
469 if best.is_none() && minimum < length {
470 let mut low = minimum;
471 let mut high = (length - 1).min(offset.saturating_add(budget.max_bytes));
472 while low <= high {
473 engine.check_read()?;
474 let middle = low + (high - low) / 2;
475 let mut end = middle;
476 if let PlanReviewItem::Text { text, .. } = original {
477 while !text.is_char_boundary(end) {
478 end -= 1;
479 }
480 }
481 page.items.push(original.chunk(offset, end));
482 page.next_cursor = Some(PlanReviewCursor::new(id, record, end));
483 let fits = budget.check(&page).is_ok();
484 page.items.pop();
485 if fits {
486 best = Some((end, (record, end)));
487 low = middle + 1;
488 } else {
489 if middle == 0 {
490 break;
491 }
492 high = middle - 1;
493 }
494 }
495 }
496 if let Some((end, successor)) = best {
497 page.items.push(original.chunk(offset, end));
498 (record, offset) = successor;
499 } else if page.items.is_empty() {
500 page.items.push(original.chunk(offset, minimum));
501 let successor = if minimum == length {
502 (record + 1, 0)
503 } else {
504 (record, minimum)
505 };
506 page.next_cursor = (successor.0 < self.records.len())
507 .then(|| PlanReviewCursor::new(id, successor.0, successor.1));
508 budget.check(&page)?;
509 unreachable!("minimum record did not fit")
510 } else {
511 break;
512 }
513 }
514 page.next_cursor =
515 (record < self.records.len()).then(|| PlanReviewCursor::new(id, record, offset));
516 budget.check(&page)?;
517 engine.check_read()?;
518 Ok(page)
519 }
520}
521impl PlanReviewItem {
522 fn chunk(&self, start: usize, end: usize) -> Self {
523 match self {
524 Self::Metadata { .. } => self.clone(),
525 Self::Text {
526 section,
527 index,
528 file_index,
529 field,
530 total_bytes,
531 text,
532 ..
533 } => Self::Text {
534 section: *section,
535 index: *index,
536 file_index: *file_index,
537 field: field.clone(),
538 offset: start,
539 total_bytes: *total_bytes,
540 text: text[start..end].to_owned(),
541 complete: end == *total_bytes,
542 },
543 }
544 }
545}
546impl crate::report::Document {
547 pub(crate) fn plan_reply(reply: &PlanReviewReply) -> Self {
548 match reply {
549 PlanReviewReply::Complete(r) => Self::plan_review(r),
550 PlanReviewReply::Page(p) => Self::plan_page(p),
551 }
552 }
553 pub(crate) fn plan_page(page: &PlanReviewPage) -> Self {
554 use crate::protocol::display::{Line, Role};
555 let mut doc = Self::new();
556 doc.body([Line::single(Role::Plain, "Plan: ").and(Role::Plain, &page.plan_id.0)]);
557 for item in &page.items {
558 doc.body([Line::single(
559 Role::Plain,
560 serde_json::to_string(item).expect("review item serializes"),
561 )]);
562 }
563 if let Some(cursor) = &page.next_cursor {
564 doc.notes([Line::single(Role::Plain, "Review cursor: ").and(Role::Plain, &cursor.0)]);
565 }
566 doc
567 }
568}