proto.rs

  1//! Handles conversions of `language` items to and from the [`rpc`] protocol.
  2
  3use crate::{CursorShape, Diagnostic, DiagnosticSourceKind, diagnostic_set::DiagnosticEntry};
  4use anyhow::{Context as _, Result};
  5use clock::ReplicaId;
  6use lsp::{DiagnosticSeverity, LanguageServerId};
  7use rpc::proto;
  8use serde_json::Value;
  9use std::{ops::Range, str::FromStr, sync::Arc};
 10use text::*;
 11
 12pub use proto::{BufferState, File, Operation};
 13
 14/// Deserializes a `[text::LineEnding]` from the RPC representation.
 15pub fn deserialize_line_ending(message: proto::LineEnding) -> text::LineEnding {
 16    match message {
 17        proto::LineEnding::Unix => text::LineEnding::Unix,
 18        proto::LineEnding::Windows => text::LineEnding::Windows,
 19    }
 20}
 21
 22/// Serializes a [`text::LineEnding`] to be sent over RPC.
 23pub fn serialize_line_ending(message: text::LineEnding) -> proto::LineEnding {
 24    match message {
 25        text::LineEnding::Unix => proto::LineEnding::Unix,
 26        text::LineEnding::Windows => proto::LineEnding::Windows,
 27    }
 28}
 29
 30/// Serializes a [`crate::Operation`] to be sent over RPC.
 31pub fn serialize_operation(operation: &crate::Operation) -> proto::Operation {
 32    proto::Operation {
 33        variant: Some(match operation {
 34            crate::Operation::Buffer(text::Operation::Edit(edit)) => {
 35                proto::operation::Variant::Edit(serialize_edit_operation(edit))
 36            }
 37
 38            crate::Operation::Buffer(text::Operation::Undo(undo)) => {
 39                proto::operation::Variant::Undo(proto::operation::Undo {
 40                    replica_id: undo.timestamp.replica_id as u32,
 41                    lamport_timestamp: undo.timestamp.value,
 42                    version: serialize_version(&undo.version),
 43                    counts: undo
 44                        .counts
 45                        .iter()
 46                        .map(|(edit_id, count)| proto::UndoCount {
 47                            replica_id: edit_id.replica_id as u32,
 48                            lamport_timestamp: edit_id.value,
 49                            count: *count,
 50                        })
 51                        .collect(),
 52                })
 53            }
 54
 55            crate::Operation::UpdateSelections {
 56                selections,
 57                line_mode,
 58                lamport_timestamp,
 59                cursor_shape,
 60            } => proto::operation::Variant::UpdateSelections(proto::operation::UpdateSelections {
 61                replica_id: lamport_timestamp.replica_id as u32,
 62                lamport_timestamp: lamport_timestamp.value,
 63                selections: serialize_selections(selections),
 64                line_mode: *line_mode,
 65                cursor_shape: serialize_cursor_shape(cursor_shape) as i32,
 66            }),
 67
 68            crate::Operation::UpdateDiagnostics {
 69                lamport_timestamp,
 70                server_id,
 71                diagnostics,
 72            } => proto::operation::Variant::UpdateDiagnostics(proto::UpdateDiagnostics {
 73                replica_id: lamport_timestamp.replica_id as u32,
 74                lamport_timestamp: lamport_timestamp.value,
 75                server_id: server_id.0 as u64,
 76                diagnostics: serialize_diagnostics(diagnostics.iter()),
 77            }),
 78
 79            crate::Operation::UpdateCompletionTriggers {
 80                triggers,
 81                lamport_timestamp,
 82                server_id,
 83            } => proto::operation::Variant::UpdateCompletionTriggers(
 84                proto::operation::UpdateCompletionTriggers {
 85                    replica_id: lamport_timestamp.replica_id as u32,
 86                    lamport_timestamp: lamport_timestamp.value,
 87                    triggers: triggers.iter().cloned().collect(),
 88                    language_server_id: server_id.to_proto(),
 89                },
 90            ),
 91        }),
 92    }
 93}
 94
 95/// Serializes an [`EditOperation`] to be sent over RPC.
 96pub fn serialize_edit_operation(operation: &EditOperation) -> proto::operation::Edit {
 97    proto::operation::Edit {
 98        replica_id: operation.timestamp.replica_id as u32,
 99        lamport_timestamp: operation.timestamp.value,
100        version: serialize_version(&operation.version),
101        ranges: operation.ranges.iter().map(serialize_range).collect(),
102        new_text: operation
103            .new_text
104            .iter()
105            .map(|text| text.to_string())
106            .collect(),
107    }
108}
109
110/// Serializes an entry in the undo map to be sent over RPC.
111pub fn serialize_undo_map_entry(
112    (edit_id, counts): (&clock::Lamport, &[(clock::Lamport, u32)]),
113) -> proto::UndoMapEntry {
114    proto::UndoMapEntry {
115        replica_id: edit_id.replica_id as u32,
116        local_timestamp: edit_id.value,
117        counts: counts
118            .iter()
119            .map(|(undo_id, count)| proto::UndoCount {
120                replica_id: undo_id.replica_id as u32,
121                lamport_timestamp: undo_id.value,
122                count: *count,
123            })
124            .collect(),
125    }
126}
127
128/// Splits the given list of operations into chunks.
129pub fn split_operations(
130    mut operations: Vec<proto::Operation>,
131) -> impl Iterator<Item = Vec<proto::Operation>> {
132    #[cfg(any(test, feature = "test-support"))]
133    const CHUNK_SIZE: usize = 5;
134
135    #[cfg(not(any(test, feature = "test-support")))]
136    const CHUNK_SIZE: usize = 100;
137
138    let mut done = false;
139    std::iter::from_fn(move || {
140        if done {
141            return None;
142        }
143
144        let operations = operations
145            .drain(..std::cmp::min(CHUNK_SIZE, operations.len()))
146            .collect::<Vec<_>>();
147        if operations.is_empty() {
148            done = true;
149        }
150        Some(operations)
151    })
152}
153
154/// Serializes selections to be sent over RPC.
155pub fn serialize_selections(selections: &Arc<[Selection<Anchor>]>) -> Vec<proto::Selection> {
156    selections.iter().map(serialize_selection).collect()
157}
158
159/// Serializes a [`Selection`] to be sent over RPC.
160pub fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
161    proto::Selection {
162        id: selection.id as u64,
163        start: Some(proto::EditorAnchor {
164            anchor: Some(serialize_anchor(&selection.start)),
165            excerpt_id: 0,
166        }),
167        end: Some(proto::EditorAnchor {
168            anchor: Some(serialize_anchor(&selection.end)),
169            excerpt_id: 0,
170        }),
171        reversed: selection.reversed,
172    }
173}
174
175/// Serializes a [`CursorShape`] to be sent over RPC.
176pub fn serialize_cursor_shape(cursor_shape: &CursorShape) -> proto::CursorShape {
177    match cursor_shape {
178        CursorShape::Bar => proto::CursorShape::CursorBar,
179        CursorShape::Block => proto::CursorShape::CursorBlock,
180        CursorShape::Underline => proto::CursorShape::CursorUnderscore,
181        CursorShape::Hollow => proto::CursorShape::CursorHollow,
182    }
183}
184
185/// Deserializes a [`CursorShape`] from the RPC representation.
186pub fn deserialize_cursor_shape(cursor_shape: proto::CursorShape) -> CursorShape {
187    match cursor_shape {
188        proto::CursorShape::CursorBar => CursorShape::Bar,
189        proto::CursorShape::CursorBlock => CursorShape::Block,
190        proto::CursorShape::CursorUnderscore => CursorShape::Underline,
191        proto::CursorShape::CursorHollow => CursorShape::Hollow,
192    }
193}
194
195/// Serializes a list of diagnostics to be sent over RPC.
196pub fn serialize_diagnostics<'a>(
197    diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<Anchor>>,
198) -> Vec<proto::Diagnostic> {
199    diagnostics
200        .into_iter()
201        .map(|entry| proto::Diagnostic {
202            source: entry.diagnostic.source.clone(),
203            source_kind: match entry.diagnostic.source_kind {
204                DiagnosticSourceKind::Pulled => proto::diagnostic::SourceKind::Pulled,
205                DiagnosticSourceKind::Pushed => proto::diagnostic::SourceKind::Pushed,
206                DiagnosticSourceKind::Other => proto::diagnostic::SourceKind::Other,
207            } as i32,
208            start: Some(serialize_anchor(&entry.range.start)),
209            end: Some(serialize_anchor(&entry.range.end)),
210            message: entry.diagnostic.message.clone(),
211            markdown: entry.diagnostic.markdown.clone(),
212            severity: match entry.diagnostic.severity {
213                DiagnosticSeverity::ERROR => proto::diagnostic::Severity::Error,
214                DiagnosticSeverity::WARNING => proto::diagnostic::Severity::Warning,
215                DiagnosticSeverity::INFORMATION => proto::diagnostic::Severity::Information,
216                DiagnosticSeverity::HINT => proto::diagnostic::Severity::Hint,
217                _ => proto::diagnostic::Severity::None,
218            } as i32,
219            group_id: entry.diagnostic.group_id as u64,
220            is_primary: entry.diagnostic.is_primary,
221            underline: entry.diagnostic.underline,
222            code: entry.diagnostic.code.as_ref().map(|s| s.to_string()),
223            code_description: entry
224                .diagnostic
225                .code_description
226                .as_ref()
227                .map(|s| s.to_string()),
228            is_disk_based: entry.diagnostic.is_disk_based,
229            is_unnecessary: entry.diagnostic.is_unnecessary,
230            data: entry.diagnostic.data.as_ref().map(|data| data.to_string()),
231        })
232        .collect()
233}
234
235/// Serializes an [`Anchor`] to be sent over RPC.
236pub fn serialize_anchor(anchor: &Anchor) -> proto::Anchor {
237    proto::Anchor {
238        replica_id: anchor.timestamp.replica_id as u32,
239        timestamp: anchor.timestamp.value,
240        offset: anchor.offset as u64,
241        bias: match anchor.bias {
242            Bias::Left => proto::Bias::Left as i32,
243            Bias::Right => proto::Bias::Right as i32,
244        },
245        buffer_id: anchor.buffer_id.map(Into::into),
246    }
247}
248
249pub fn serialize_anchor_range(range: Range<Anchor>) -> proto::AnchorRange {
250    proto::AnchorRange {
251        start: Some(serialize_anchor(&range.start)),
252        end: Some(serialize_anchor(&range.end)),
253    }
254}
255
256/// Deserializes an [`Range<Anchor>`] from the RPC representation.
257pub fn deserialize_anchor_range(range: proto::AnchorRange) -> Result<Range<Anchor>> {
258    Ok(
259        deserialize_anchor(range.start.context("invalid anchor")?).context("invalid anchor")?
260            ..deserialize_anchor(range.end.context("invalid anchor")?).context("invalid anchor")?,
261    )
262}
263
264// This behavior is currently copied in the collab database, for snapshotting channel notes
265/// Deserializes an [`crate::Operation`] from the RPC representation.
266pub fn deserialize_operation(message: proto::Operation) -> Result<crate::Operation> {
267    Ok(
268        match message.variant.context("missing operation variant")? {
269            proto::operation::Variant::Edit(edit) => {
270                crate::Operation::Buffer(text::Operation::Edit(deserialize_edit_operation(edit)))
271            }
272            proto::operation::Variant::Undo(undo) => {
273                crate::Operation::Buffer(text::Operation::Undo(UndoOperation {
274                    timestamp: clock::Lamport {
275                        replica_id: undo.replica_id as ReplicaId,
276                        value: undo.lamport_timestamp,
277                    },
278                    version: deserialize_version(&undo.version),
279                    counts: undo
280                        .counts
281                        .into_iter()
282                        .map(|c| {
283                            (
284                                clock::Lamport {
285                                    replica_id: c.replica_id as ReplicaId,
286                                    value: c.lamport_timestamp,
287                                },
288                                c.count,
289                            )
290                        })
291                        .collect(),
292                }))
293            }
294            proto::operation::Variant::UpdateSelections(message) => {
295                let selections = message
296                    .selections
297                    .into_iter()
298                    .filter_map(|selection| {
299                        Some(Selection {
300                            id: selection.id as usize,
301                            start: deserialize_anchor(selection.start?.anchor?)?,
302                            end: deserialize_anchor(selection.end?.anchor?)?,
303                            reversed: selection.reversed,
304                            goal: SelectionGoal::None,
305                        })
306                    })
307                    .collect::<Vec<_>>();
308
309                crate::Operation::UpdateSelections {
310                    lamport_timestamp: clock::Lamport {
311                        replica_id: message.replica_id as ReplicaId,
312                        value: message.lamport_timestamp,
313                    },
314                    selections: Arc::from(selections),
315                    line_mode: message.line_mode,
316                    cursor_shape: deserialize_cursor_shape(
317                        proto::CursorShape::from_i32(message.cursor_shape)
318                            .context("Missing cursor shape")?,
319                    ),
320                }
321            }
322            proto::operation::Variant::UpdateDiagnostics(message) => {
323                crate::Operation::UpdateDiagnostics {
324                    lamport_timestamp: clock::Lamport {
325                        replica_id: message.replica_id as ReplicaId,
326                        value: message.lamport_timestamp,
327                    },
328                    server_id: LanguageServerId(message.server_id as usize),
329                    diagnostics: deserialize_diagnostics(message.diagnostics),
330                }
331            }
332            proto::operation::Variant::UpdateCompletionTriggers(message) => {
333                crate::Operation::UpdateCompletionTriggers {
334                    triggers: message.triggers,
335                    lamport_timestamp: clock::Lamport {
336                        replica_id: message.replica_id as ReplicaId,
337                        value: message.lamport_timestamp,
338                    },
339                    server_id: LanguageServerId::from_proto(message.language_server_id),
340                }
341            }
342        },
343    )
344}
345
346/// Deserializes an [`EditOperation`] from the RPC representation.
347pub fn deserialize_edit_operation(edit: proto::operation::Edit) -> EditOperation {
348    EditOperation {
349        timestamp: clock::Lamport {
350            replica_id: edit.replica_id as ReplicaId,
351            value: edit.lamport_timestamp,
352        },
353        version: deserialize_version(&edit.version),
354        ranges: edit.ranges.into_iter().map(deserialize_range).collect(),
355        new_text: edit.new_text.into_iter().map(Arc::from).collect(),
356    }
357}
358
359/// Deserializes an entry in the undo map from the RPC representation.
360pub fn deserialize_undo_map_entry(
361    entry: proto::UndoMapEntry,
362) -> (clock::Lamport, Vec<(clock::Lamport, u32)>) {
363    (
364        clock::Lamport {
365            replica_id: entry.replica_id as u16,
366            value: entry.local_timestamp,
367        },
368        entry
369            .counts
370            .into_iter()
371            .map(|undo_count| {
372                (
373                    clock::Lamport {
374                        replica_id: undo_count.replica_id as u16,
375                        value: undo_count.lamport_timestamp,
376                    },
377                    undo_count.count,
378                )
379            })
380            .collect(),
381    )
382}
383
384/// Deserializes selections from the RPC representation.
385pub fn deserialize_selections(selections: Vec<proto::Selection>) -> Arc<[Selection<Anchor>]> {
386    Arc::from(
387        selections
388            .into_iter()
389            .filter_map(deserialize_selection)
390            .collect::<Vec<_>>(),
391    )
392}
393
394/// Deserializes a [`Selection`] from the RPC representation.
395pub fn deserialize_selection(selection: proto::Selection) -> Option<Selection<Anchor>> {
396    Some(Selection {
397        id: selection.id as usize,
398        start: deserialize_anchor(selection.start?.anchor?)?,
399        end: deserialize_anchor(selection.end?.anchor?)?,
400        reversed: selection.reversed,
401        goal: SelectionGoal::None,
402    })
403}
404
405/// Deserializes a list of diagnostics from the RPC representation.
406pub fn deserialize_diagnostics(
407    diagnostics: Vec<proto::Diagnostic>,
408) -> Arc<[DiagnosticEntry<Anchor>]> {
409    diagnostics
410        .into_iter()
411        .filter_map(|diagnostic| {
412            let data = if let Some(data) = diagnostic.data {
413                Some(Value::from_str(&data).ok()?)
414            } else {
415                None
416            };
417            Some(DiagnosticEntry {
418                range: deserialize_anchor(diagnostic.start?)?..deserialize_anchor(diagnostic.end?)?,
419                diagnostic: Diagnostic {
420                    source: diagnostic.source,
421                    severity: match proto::diagnostic::Severity::from_i32(diagnostic.severity)? {
422                        proto::diagnostic::Severity::Error => DiagnosticSeverity::ERROR,
423                        proto::diagnostic::Severity::Warning => DiagnosticSeverity::WARNING,
424                        proto::diagnostic::Severity::Information => DiagnosticSeverity::INFORMATION,
425                        proto::diagnostic::Severity::Hint => DiagnosticSeverity::HINT,
426                        proto::diagnostic::Severity::None => return None,
427                    },
428                    message: diagnostic.message,
429                    markdown: diagnostic.markdown,
430                    group_id: diagnostic.group_id as usize,
431                    code: diagnostic.code.map(lsp::NumberOrString::from_string),
432                    code_description: diagnostic
433                        .code_description
434                        .and_then(|s| lsp::Url::parse(&s).ok()),
435                    is_primary: diagnostic.is_primary,
436                    is_disk_based: diagnostic.is_disk_based,
437                    is_unnecessary: diagnostic.is_unnecessary,
438                    underline: diagnostic.underline,
439                    source_kind: match proto::diagnostic::SourceKind::from_i32(
440                        diagnostic.source_kind,
441                    )? {
442                        proto::diagnostic::SourceKind::Pulled => DiagnosticSourceKind::Pulled,
443                        proto::diagnostic::SourceKind::Pushed => DiagnosticSourceKind::Pushed,
444                        proto::diagnostic::SourceKind::Other => DiagnosticSourceKind::Other,
445                    },
446                    data,
447                },
448            })
449        })
450        .collect()
451}
452
453/// Deserializes an [`Anchor`] from the RPC representation.
454pub fn deserialize_anchor(anchor: proto::Anchor) -> Option<Anchor> {
455    let buffer_id = if let Some(id) = anchor.buffer_id {
456        Some(BufferId::new(id).ok()?)
457    } else {
458        None
459    };
460    Some(Anchor {
461        timestamp: clock::Lamport {
462            replica_id: anchor.replica_id as ReplicaId,
463            value: anchor.timestamp,
464        },
465        offset: anchor.offset as usize,
466        bias: match proto::Bias::from_i32(anchor.bias)? {
467            proto::Bias::Left => Bias::Left,
468            proto::Bias::Right => Bias::Right,
469        },
470        buffer_id,
471    })
472}
473
474/// Returns a `[clock::Lamport`] timestamp for the given [`proto::Operation`].
475pub fn lamport_timestamp_for_operation(operation: &proto::Operation) -> Option<clock::Lamport> {
476    let replica_id;
477    let value;
478    match operation.variant.as_ref()? {
479        proto::operation::Variant::Edit(op) => {
480            replica_id = op.replica_id;
481            value = op.lamport_timestamp;
482        }
483        proto::operation::Variant::Undo(op) => {
484            replica_id = op.replica_id;
485            value = op.lamport_timestamp;
486        }
487        proto::operation::Variant::UpdateDiagnostics(op) => {
488            replica_id = op.replica_id;
489            value = op.lamport_timestamp;
490        }
491        proto::operation::Variant::UpdateSelections(op) => {
492            replica_id = op.replica_id;
493            value = op.lamport_timestamp;
494        }
495        proto::operation::Variant::UpdateCompletionTriggers(op) => {
496            replica_id = op.replica_id;
497            value = op.lamport_timestamp;
498        }
499    }
500
501    Some(clock::Lamport {
502        replica_id: replica_id as ReplicaId,
503        value,
504    })
505}
506
507/// Serializes a [`Transaction`] to be sent over RPC.
508pub fn serialize_transaction(transaction: &Transaction) -> proto::Transaction {
509    proto::Transaction {
510        id: Some(serialize_timestamp(transaction.id)),
511        edit_ids: transaction
512            .edit_ids
513            .iter()
514            .copied()
515            .map(serialize_timestamp)
516            .collect(),
517        start: serialize_version(&transaction.start),
518    }
519}
520
521/// Deserializes a [`Transaction`] from the RPC representation.
522pub fn deserialize_transaction(transaction: proto::Transaction) -> Result<Transaction> {
523    Ok(Transaction {
524        id: deserialize_timestamp(transaction.id.context("missing transaction id")?),
525        edit_ids: transaction
526            .edit_ids
527            .into_iter()
528            .map(deserialize_timestamp)
529            .collect(),
530        start: deserialize_version(&transaction.start),
531    })
532}
533
534/// Serializes a [`clock::Lamport`] timestamp to be sent over RPC.
535pub fn serialize_timestamp(timestamp: clock::Lamport) -> proto::LamportTimestamp {
536    proto::LamportTimestamp {
537        replica_id: timestamp.replica_id as u32,
538        value: timestamp.value,
539    }
540}
541
542/// Deserializes a [`clock::Lamport`] timestamp from the RPC representation.
543pub fn deserialize_timestamp(timestamp: proto::LamportTimestamp) -> clock::Lamport {
544    clock::Lamport {
545        replica_id: timestamp.replica_id as ReplicaId,
546        value: timestamp.value,
547    }
548}
549
550/// Serializes a range of [`FullOffset`]s to be sent over RPC.
551pub fn serialize_range(range: &Range<FullOffset>) -> proto::Range {
552    proto::Range {
553        start: range.start.0 as u64,
554        end: range.end.0 as u64,
555    }
556}
557
558/// Deserializes a range of [`FullOffset`]s from the RPC representation.
559pub fn deserialize_range(range: proto::Range) -> Range<FullOffset> {
560    FullOffset(range.start as usize)..FullOffset(range.end as usize)
561}
562
563/// Deserializes a clock version from the RPC representation.
564pub fn deserialize_version(message: &[proto::VectorClockEntry]) -> clock::Global {
565    let mut version = clock::Global::new();
566    for entry in message {
567        version.observe(clock::Lamport {
568            replica_id: entry.replica_id as ReplicaId,
569            value: entry.timestamp,
570        });
571    }
572    version
573}
574
575/// Serializes a clock version to be sent over RPC.
576pub fn serialize_version(version: &clock::Global) -> Vec<proto::VectorClockEntry> {
577    version
578        .iter()
579        .map(|entry| proto::VectorClockEntry {
580            replica_id: entry.replica_id as u32,
581            timestamp: entry.value,
582        })
583        .collect()
584}