-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathtranslation.rs
More file actions
1748 lines (1673 loc) · 80.6 KB
/
Copy pathtranslation.rs
File metadata and controls
1748 lines (1673 loc) · 80.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2026 Bryan A. Jones.
//
// This file is part of the CodeChat Editor. The CodeChat Editor is free
// software: you can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// The CodeChat Editor is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// the CodeChat Editor. If not, see
// [http://www.gnu.org/licenses](http://www.gnu.org/licenses).
//! `translation.rs` -- translate messages between the IDE and the Client
//! =====================================================================
//!
//! The IDE extension client (IDE for short) and the CodeChat Editor Client (or
//! Editor for short) exchange messages with each other, mediated by the
//! CodeChat Server. The Server forwards messages from one client to the other,
//! translating as necessary (for example, between source code and the Editor
//! format). This module implements the protocol for this forwarding and
//! translation logic; the actuation translation algorithms are implemented in
//! the processing module.
//!
//! Overview
//! --------
//!
//! ### Architecture
//!
//! It uses a set of queues to decouple websocket protocol activity from the
//! core processing needed to translate source code between a CodeChat Editor
//! Client and an IDE client. The following diagram illustrates this approach:
//!
//! ```graphviz
//! digraph {
//! ccc -> client_task [ label = "websocket" dir = "both" ]
//! ccc -> http_task [ label = "HTTP\nrequest/response" dir = "both"]
//! client_task -> from_client
//! http_task -> http_to_client
//! http_to_client -> processing
//! processing -> http_from_client
//! http_from_client -> http_task
//! from_client -> processing
//! processing -> to_client
//! to_client -> client_task
//! ide -> ide_task [ dir = "both" ]
//! ide_task -> from_ide
//! from_ide -> processing
//! processing -> to_ide
//! to_ide -> ide_task
//! { rank = same; client_task; http_task }
//! { rank = same; to_client; from_client; http_from_client; http_to_client }
//! { rank = same; to_ide; from_ide }
//! { rank = max; ide }
//! ccc [ label = "CodeChat Editor\nClient"]
//! client_task [ label = "Client websocket\ntask"]
//! http_task [ label = "HTTP endpoint"]
//! from_client [ label = "queue from client" shape="rectangle"]
//! processing [ label = "Processing task" ]
//! to_client [ label = "queue to client" shape="rectangle"]
//! http_to_client [ label = "http queue to client" shape = "rectangle"]
//! http_from_client [ label = "oneshot from client" shape = "box"]
//! ide [ label = "CodeChat Editor\nIDE plugin"]
//! ide_task [ label = "IDE task" ]
//! from_ide [ label = "queue from IDE" shape="rectangle" ]
//! to_ide [ label = "queue to IDE" shape="rectangle" ]
//! }
//! ```
//!
//! The queues use multiple-sender, single receiver (mpsc) types. The exception
//! to this pattern is the HTTP endpoint. This endpoint is invoked with each
//! HTTP request, rather than operating as a single, long-running task. It sends
//! the request to the processing task using an mpsc queue; this request
//! includes a one-shot channel which enables the request to return a response
//! to this specific request instance. The endpoint then returns the provided
//! response.
//!
//! ### Protocol
//!
//! The following diagrams formally define the forwarding and translation
//! protocol which this module implements.
//!
//! * The startup phase loads the Client framework into a browser:
//!
//! ```mermaid
//! sequenceDiagram
//! participant IDE
//! participant Server
//! participant Client
//! note over IDE, Client: Startup
//! IDE ->> Server: Opened(IdeType)
//! Server ->> IDE: Result(String: OK)
//! Server ->> IDE: ClientHtml(String: HTML or URL)
//! IDE ->> Server: Result(String: OK)
//! note over IDE, Client: Open browser (Client framework HTML or URL)
//! loop
//! Client -> Server: HTTP request(/static URL)
//! Server -> Client: HTTP response(/static data)
//! end
//! ```
//!
//! * If the current file in the IDE changes (including the initial startup,
//! when the change is from no file to the current file), or a link is
//! followed in the Client's iframe:
//!
//! ```mermaid
//! sequenceDiagram
//! participant IDE
//! participant Server
//! participant Client
//! alt IDE loads file
//! IDE ->> Client: CurrentFile(String: Path of main.py)
//! opt If Client document is dirty
//! Client ->> IDE: Update(String: contents of main.py)
//! IDE ->> Client: Response(OK)
//! end
//! Client ->> IDE: Response(OK)
//! else Client loads file
//! Client ->> IDE: CurrentFile(String: URL of main.py)
//! IDE ->> Client: Response(OK)
//! end
//! Client ->> Server: HTTP request(URL of main.py)
//! Server ->> IDE: LoadFile(String: path to main.py)
//! IDE ->> Server: Response(LoadFile(String: file contents of main.py))
//! alt main.py is editable
//! Server ->> Client: HTTP response(contents of Client)
//! Server ->> Client: Update(String: contents of main.py)
//! Client ->> Server: Response(OK)
//! loop
//! Client ->> Server: HTTP request(URL of supporting file in main.py)
//! Server ->> IDE: LoadFile(String: path of supporting file)
//! alt Supporting file in IDE
//! IDE ->> Server: Response(LoadFile(contents of supporting file)
//! Server ->> Client: HTTP response(contents of supporting file)
//! else Supporting file not in IDE
//! IDE ->> Server: Response(LoadFile(None))
//! Server ->> Client: HTTP response(contents of supporting file from /// filesystem)
//! end
//! end
//! else main.py not editable and not a project
//! Server ->> Client: HTTP response(contents of main.py)
//! else main.py not editable and is a project
//! Server ->> Client: HTTP response(contents of Client Simple Viewer)
//! Client ->> Server: HTTP request (URL?raw of main.py)
//! Server ->> Client: HTTP response(contents of main.py)
//! end
//! ```
//!
//! * If the current file's contents in the IDE are edited:
//!
//! ```mermaid
//! sequenceDiagram
//! participant IDE
//! participant Server
//! participant Client
//! IDE ->> Server: Update(String: new text contents)
//! alt Main file is editable
//! Server ->> Client: Update(String: new Client contents)
//! else Main file is not editable
//! Server ->> Client: Update(String: new text contents)
//! end
//! Client ->> IDE: Response(String: OK)
//! ```
//!
//! * If the current file's contents in the Client are edited, the Client sends
//! the IDE an `Update` with the revised contents.
//!
//! * When the PC goes to sleep then wakes up, the IDE client and the Editor
//! client both reconnect to the websocket URL containing their assigned ID.
//!
//! * If the Editor client or the IDE client are closed, they close their
//! websocket, which sends a `Close` message to the other websocket, causes it
//! to also close and ending the session.
//!
//! * If the server is stopped (or crashes), both clients shut down after
//! several reconnect retries.
//!
//! ### Editor-overlay filesystem
//!
//! When the Client displays a file provided by the IDE, that file may not exist
//! in the filesystem (a newly-created document), the IDE's content may be newer
//! than the filesystem content (an unsaved file), or the file may exist only in
//! the filesystem (for examples, images referenced by a file). The Client loads
//! files by sending HTTP requests to the Server with a URL which includes the
//! path to the desired file. Therefore, the Server must first ask the IDE if it
//! has the requested file; if so, it must deliver the IDE's file contents; if
//! not, it must load thee requested file from the filesystem. This process --
//! fetching from the IDE if possible, then falling back to the filesystem --
//! defines the editor-overlay filesystem.
//!
//! #### Message IDs
//!
//! The message system connects the IDE, Server, and Client; all three can serve
//! as the source or destination for a message. Any message sent should produce
//! a Response message in return. Therefore, we need globally unique IDs for
//! each message. To achieve this, the Server uses IDs that are multiples of 3
//! (0, 3, 6, ...), the Client multiples of 3 + 1 (1, 4, 7, ...) and the IDE
//! multiples of 3 + 2 (2, 5, 8, ...). A double-precision floating point number
//! (the standard
//! [numeric type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type)
//! in JavaScript) has a 53-bit mantissa, meaning IDs won't wrap around for a
//! very long time.
// Imports
// -------
//
// ### Standard library
use std::{
collections::HashMap,
ffi::OsStr,
fmt::Debug,
path::{Path, PathBuf},
rc::Rc,
sync::LazyLock,
};
// ### Third-party
use htmd::Node;
use log::{debug, error, warn};
use rand::random;
use regex::Regex;
use tokio::{
fs::File,
select,
sync::mpsc::{self, Receiver, Sender},
};
// ### Local
use crate::{
capture::{CaptureContext, CaptureEventType, capture_control_only},
lexer::{CodeDocBlock, DocBlock, supported_languages::MARKDOWN_MODE},
processing::{
CodeChatForWeb, CodeMirror, CodeMirrorDiff, CodeMirrorDiffable, CodeMirrorDocBlock,
CodeMirrorDocBlockVec, SourceFileMetadata, TranslationResultsString, UNICODE_CURSOR_MARKER,
byte_index_of, cache::CacheMap, codechat_for_web_to_source, diff_code_mirror_doc_blocks,
diff_str, doc_block_html_to_markdown, minify, remove_tinymce_data,
source_to_codechat_for_web_string, transform_html,
},
queue_send, queue_send_func,
webserver::{
CursorPosition, EditorMessage, EditorMessageContents, INITIAL_MESSAGE_ID,
MESSAGE_ID_INCREMENT, ProcessingTaskHttpRequest, ProcessingTaskHttpRequestFlags,
ResultErrTypes, ResultOkTypes, SimpleHttpResponse, SimpleHttpResponseError,
UpdateMessageContents, WebAppState, WebsocketQueues, file_to_response, log_capture_event,
path_to_url, send_response, try_canonicalize, try_read_as_text, url_to_path,
},
};
// Globals
// -------
//
// The max length of a message to show in the console.
const MAX_MESSAGE_LENGTH: usize = 50000;
/// A regex to determine the type of the first EOL. See 'PROCESSINGS\`.
pub static EOL_FINDER: LazyLock<Regex> = LazyLock::new(|| Regex::new("[^\r\n]*(\r?\n)").unwrap());
// Data structures
// ---------------
#[derive(Clone, Debug, PartialEq)]
pub enum EolType {
Lf,
Crlf,
}
// Code
// ----
#[must_use]
pub fn find_eol_type(s: &str) -> EolType {
match EOL_FINDER.captures(s) {
// Assume a line type for strings with no newlines.
None => {
if cfg!(windows) {
EolType::Crlf
} else {
EolType::Lf
}
}
Some(captures) => match captures.get(1) {
None => panic!("No capture group!"),
Some(match_) => {
if match_.as_str() == "\n" {
EolType::Lf
} else {
EolType::Crlf
}
}
},
}
}
#[derive(Debug, thiserror::Error)]
pub enum CreateTranslationQueuesError {
#[error("Connection ID {0} already in use.")]
IdInUse(String),
#[error("IDE queue {0} already in use.")]
IdeInUse(String),
}
pub struct CreatedTranslationQueues {
pub from_ide_rx: Receiver<EditorMessage>,
pub to_ide_tx: Sender<EditorMessage>,
pub from_client_rx: Receiver<EditorMessage>,
pub to_client_tx: Sender<EditorMessage>,
}
pub fn create_translation_queues(
connection_id: String,
app_state: &WebAppState,
) -> Result<CreatedTranslationQueues, CreateTranslationQueuesError> {
// There are three cases for this `connection_id`:
//
// 1. It hasn't been used before. In this case, create the appropriate
// queues and start websocket and processing tasks.
// 2. It's in use, but was disconnected. Return this as an error; the caller
// can resume the connection if appropriate.
// 3. It's in use by another IDE. Return this as an error.
//
// Check case 3.
if app_state
.connection_id
.lock()
.unwrap()
.contains(&connection_id)
{
return Err(CreateTranslationQueuesError::IdInUse(connection_id));
}
// Now case 2.
if app_state
.ide_queues
.lock()
.unwrap()
.contains_key(&connection_id)
{
return Err(CreateTranslationQueuesError::IdeInUse(connection_id));
}
// Then this is case 1. Add the connection ID to the list of active
// connections.
let (from_ide_tx, from_ide_rx) = mpsc::channel(10);
let (to_ide_tx, to_ide_rx) = mpsc::channel(10);
assert!(
app_state
.ide_queues
.lock()
.unwrap()
.insert(
connection_id.clone(),
WebsocketQueues {
from_websocket_tx: from_ide_tx,
to_websocket_rx: to_ide_rx,
pending_messages: HashMap::new(),
},
)
.is_none()
);
let (from_client_tx, from_client_rx) = mpsc::channel(10);
let (to_client_tx, to_client_rx) = mpsc::channel(10);
assert!(
app_state
.client_queues
.lock()
.unwrap()
.insert(
connection_id.clone(),
WebsocketQueues {
from_websocket_tx: from_client_tx,
to_websocket_rx: to_client_rx,
pending_messages: HashMap::new(),
},
)
.is_none()
);
assert!(
app_state
.connection_id
.lock()
.unwrap()
.insert(connection_id.clone())
);
Ok(CreatedTranslationQueues {
from_ide_rx,
to_ide_tx,
from_client_rx,
to_client_tx,
})
}
/// This holds the state used by the main loop of the translation task; this
/// allows factoring out lengthy contents in the loop into subfunctions.
struct TranslationTask {
// These parameters are passed to us.
app_state: WebAppState,
connection_id_raw: String,
prefix: &'static [&'static str],
allow_source_diffs: bool,
to_ide_tx: Sender<EditorMessage>,
from_ide_rx: Receiver<EditorMessage>,
to_client_tx: Sender<EditorMessage>,
from_client_rx: Receiver<EditorMessage>,
from_http_rx: Receiver<ProcessingTaskHttpRequest>,
cache: CacheMap,
// These parameters are internal state.
/// The file currently loaded in the Client.
current_file: PathBuf,
/// A map of `LoadFile` requests sent to the IDE, awaiting its response.
load_file_requests: HashMap<u64, ProcessingTaskHttpRequest>,
/// The id for messages created by the server. Leave space for a server
/// message during the init phase.
id: f64,
/// The source code, provided by the IDE. It will use whatever the IDE
/// provides for EOLs, which is stored in `eol` below.
source_code: String,
code_mirror_doc: String,
eol: EolType,
/// Some means this contains valid HTML; None means don't use it (since it
/// would have contained Markdown).
code_mirror_doc_blocks: Option<Vec<CodeMirrorDocBlock>>,
prefix_str: String,
/// To support sending diffs, we must provide a way to determine if the
/// sender and receiver have the same file contents before applying a diff.
/// File contents can become unsynced due to:
///
/// 1. A dropped/lost message between the IDE and Client.
/// 2. Edits to file contents in two locations before updates from one
/// location (the Client, for example) propagate to the other location
/// (the IDE).
///
/// Therefore, assign each file a version number. All files are sent with a
/// unique, randomly-generated version number which define the file's
/// version after this update is applied. Diffs also include the version
/// number of the file before applying the diff; the receiver's current
/// version number must match with the sender's pre-diff version number in
/// order to apply the diff. When the versions don't match, the IDE must
/// send a full text file to the Server and Client to re-sync. When a file
/// is first loaded, its version number is None, signaling that the sender
/// must always provide the full text, not a diff.
version: f64,
/// Has the full (non-diff) version of the current file been sent? Don't
/// send diffs until this is sent.
sent_full: bool,
/// Most recent capture metadata supplied by the IDE. Server-generated
/// capture events reuse this so translated write events retain the same
/// participant/session identity as the extension events.
capture_context: CaptureContext,
}
/// This is the processing task for the Visual Studio Code IDE. It handles all
/// the core logic to moving data between the IDE and the client.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_lines)]
pub async fn translation_task(
connection_id_prefix: String,
connection_id_raw: String,
prefix: &'static [&'static str],
app_state: WebAppState,
shutdown_only: bool,
allow_source_diffs: bool,
to_ide_tx: Sender<EditorMessage>,
mut from_ide_rx: Receiver<EditorMessage>,
to_client_tx: Sender<EditorMessage>,
mut from_client_rx: Receiver<EditorMessage>,
) {
let connection_id = format!("{connection_id_prefix}{connection_id_raw}");
if !shutdown_only {
debug!("VSCode processing task started.");
// Create a queue for HTTP requests to communicate with this task.
let (from_http_tx, from_http_rx) = mpsc::channel(10);
app_state
.processing_task_queue_tx
.lock()
.unwrap()
.insert(connection_id.clone(), from_http_tx);
let mut continue_loop = true;
let mut tt = TranslationTask {
app_state: app_state.clone(),
connection_id_raw,
prefix,
allow_source_diffs,
to_ide_tx,
from_ide_rx,
to_client_tx,
from_client_rx,
from_http_rx,
cache: app_state.cache.clone(),
current_file: PathBuf::new(),
load_file_requests: HashMap::new(),
id: INITIAL_MESSAGE_ID + MESSAGE_ID_INCREMENT,
source_code: String::new(),
code_mirror_doc: String::new(),
// The initial state will be overwritten by the first `Update` or
// `LoadFile`, so this value doesn't matter.
eol: EolType::Lf,
// Some means this contains valid HTML; None means don't use it
// (since it would have contained Markdown).
code_mirror_doc_blocks: Some(Vec::new()),
prefix_str: "/".to_string() + &prefix.join("/"),
version: 0.0,
// Don't send diffs until this is sent.
sent_full: false,
capture_context: CaptureContext::default(),
};
while continue_loop {
select! {
// Look for messages from the IDE.
Some(ide_message) = tt.from_ide_rx.recv() => {
debug!("Received IDE message id = {}, message = {}", ide_message.id, debug_shorten(&ide_message.message));
match ide_message.message {
// Handle messages that the IDE must not send.
EditorMessageContents::Opened(_) |
EditorMessageContents::OpenUrl(_) |
EditorMessageContents::LoadFile(..) |
EditorMessageContents::ClientHtml(_) => {
let err = ResultErrTypes::IdeIllegalMessage;
error!("{err:?}");
send_response(&tt.to_ide_tx, ide_message.id, Err(err)).await;
},
// Handle messages that are simply passed through.
EditorMessageContents::Closed |
EditorMessageContents::RequestClose => {
debug!("Forwarding it to the Client.");
queue_send!(tt.to_client_tx.send(ide_message));
},
EditorMessageContents::Result(_) => continue_loop = tt.ide_result(ide_message).await,
EditorMessageContents::Update(_) => continue_loop = tt.ide_update(ide_message).await,
EditorMessageContents::Capture(capture_event) => {
// Capture messages affect both upload spooling and
// the translation-layer context used for future
// server-classified write events.
let control_only = capture_control_only(&capture_event);
tt.capture_context.update_from_wire(&capture_event);
if control_only {
debug!("Updated capture context from control-only IDE event.");
} else {
log_capture_event(&app_state, *capture_event);
}
send_response(&tt.to_ide_tx, ide_message.id, Ok(ResultOkTypes::Void)).await;
},
// Update the current file; translate it to a URL then
// pass it to the Client.
EditorMessageContents::CurrentFile(file_path, _is_text) => {
debug!("Translating and forwarding it to the Client.");
match try_canonicalize(&file_path) {
Ok(clean_file_path) => {
queue_send!(tt.to_client_tx.send(EditorMessage {
id: ide_message.id,
message: EditorMessageContents::CurrentFile(
path_to_url(&tt.prefix_str, Some(&tt.connection_id_raw), &clean_file_path), Some(true)
)
}));
// Store the canonicalized path, not the
// path the IDE sent: the comparisons
// against `current_file` below assume every
// path has one spelling.
tt.current_file = clean_file_path;
// Since this is a new file, mark it as
// unsent in full.
tt.sent_full = false;
}
Err(err) => {
error!("{err:?}");
send_response(&tt.to_client_tx, ide_message.id, Err(ResultErrTypes::TryCanonicalizeError(err.to_string()))).await;
}
}
}
}
},
// Handle HTTP requests.
Some(http_request) = tt.from_http_rx.recv() => {
debug!("Received HTTP request for {} and sending LoadFile to IDE, id = {}.", http_request.file_path.display(), tt.id);
// Convert the request into a `LoadFile` message.
queue_send!(tt.to_ide_tx.send(EditorMessage {
id: tt.id,
message: EditorMessageContents::LoadFile
(http_request.file_path.clone(),
// Assign a version to this `LoadFile` request only
// if it's the current file and loaded as the file
// to edit, not as the sidebar TOC. We can use a
// simple comparison, since both file names have
// already been canonicalized.
http_request.file_path == tt.current_file &&
http_request.flags == ProcessingTaskHttpRequestFlags::None
)
}));
// Store the ID and request, which are needed to send a
// response when the `LoadFile` result is received.
tt.load_file_requests.insert(tt.id.to_bits(), http_request);
tt.id += MESSAGE_ID_INCREMENT;
}
// Handle messages from the client.
Some(client_message) = tt.from_client_rx.recv() => {
debug!("Received Client message id = {}, message = {}", client_message.id, debug_shorten(&client_message.message));
match client_message.message {
// Handle messages that the client must not send.
EditorMessageContents::Opened(_) |
EditorMessageContents::LoadFile(..) |
EditorMessageContents::RequestClose |
EditorMessageContents::ClientHtml(_) => {
let err = ResultErrTypes::ClientIllegalMessage;
error!("{err:?}");
send_response(&tt.to_client_tx, client_message.id, Err(err)).await;
},
// Handle messages that are simply passed through.
EditorMessageContents::Closed => {
debug!("Forwarding it to the IDE.");
queue_send!(tt.to_ide_tx.send(client_message));
},
EditorMessageContents::Result(ref result) => {
debug!("Forwarding it to the IDE.");
// If the Client can't read our diff, send the full
// text next time.
if matches!(result, Err(ResultErrTypes::OutOfSync(..))) {
tt.sent_full = false;
}
queue_send!(tt.to_ide_tx.send(client_message));
},
// Open a web browser when requested.
EditorMessageContents::OpenUrl(url) => {
// This doesn't work in Codespaces. TODO: send this
// back to the VSCode window, then call
// `vscode.env.openExternal(vscode.Uri.parse(url))`.
if let Err(err) = webbrowser::open(&url) {
let err = ResultErrTypes::WebBrowserOpenFailed(err.to_string());
error!("{err:?}");
send_response(&tt.to_client_tx, client_message.id, Err(err)).await;
} else {
send_response(&tt.to_client_tx, client_message.id, Ok(ResultOkTypes::Void)).await;
}
},
EditorMessageContents::Update(_) => continue_loop = tt.client_update(client_message).await,
EditorMessageContents::Capture(capture_event) => {
// Same capture handling as IDE messages: update the
// context first, then store only non-control
// events.
let control_only = capture_control_only(&capture_event);
tt.capture_context.update_from_wire(&capture_event);
if control_only {
debug!("Updated capture context from control-only Client event.");
} else {
log_capture_event(&app_state, *capture_event);
}
send_response(&tt.to_client_tx, client_message.id, Ok(ResultOkTypes::Void)).await;
},
// Update the current file; translate it to a URL then
// pass it to the IDE.
EditorMessageContents::CurrentFile(url_string, _is_text) => {
debug!("Forwarding translated path to IDE.");
let result = match url_to_path(&url_string, tt.prefix) {
Err(err) => Err(ResultErrTypes::UrlToPathError(url_string.clone(), err.to_string())),
Ok(file_path) => {
match file_path.to_str() {
None => Err(ResultErrTypes::NoPathToString(file_path)),
Some(file_path_string) => {
// Use a
// [binary file sniffer](#binary-file-sniffer)
// to determine if the file is text or
// binary.
let is_text = if let Ok(mut fc) = File::open(&file_path).await {
try_read_as_text(&mut fc).await.is_some()
} else {
false
};
queue_send!(tt.to_ide_tx.send(EditorMessage {
id: client_message.id,
message: EditorMessageContents::CurrentFile(file_path_string.to_string(), Some(is_text))
}));
tt.current_file = file_path;
// Since this is a new file, the full text
// hasn't been sent yet.
tt.sent_full = false;
Ok(())
}
}
}
};
if let Err(msg) = result {
error!("{msg}");
send_response(&tt.to_client_tx, client_message.id, Err(msg)).await;
}
}
}
},
else => break
}
}
(from_ide_rx, from_client_rx) = (tt.from_ide_rx, tt.from_client_rx);
}
debug!("VSCode processing task shutting down.");
if app_state
.processing_task_queue_tx
.lock()
.unwrap()
.remove(&connection_id)
.is_none()
{
error!("Unable to remove connection ID {connection_id} from processing task queue.");
}
if app_state
.client_queues
.lock()
.unwrap()
.remove(&connection_id)
.is_none()
{
error!("Unable to remove connection ID {connection_id} from client queues.");
}
if app_state
.ide_queues
.lock()
.unwrap()
.remove(&connection_id)
.is_none()
{
error!("Unable to remove connection ID {connection_id} from IDE queues.");
}
from_ide_rx.close();
from_client_rx.close();
// Drain any remaining messages after closing the queue.
while let Some(m) = from_ide_rx.recv().await {
warn!("Dropped queued message {m:?}");
}
while let Some(m) = from_client_rx.recv().await {
warn!("Dropped queued message {m:?}");
}
debug!("VSCode processing task exited.");
}
// These provide translation for messages passing through the Server.
impl TranslationTask {
fn capture_file_path(file_path: &Path) -> Option<String> {
file_path.to_str().map(str::to_string)
}
fn log_server_capture_event(
&mut self,
event_type: CaptureEventType,
file_path: &Path,
data: serde_json::Value,
) {
let Some(capture_event) = self.capture_context.capture_event(
event_type,
Self::capture_file_path(file_path),
data,
) else {
debug!("Skipping server-classified capture event; capture identity is not known yet.");
return;
};
log_capture_event(&self.app_state, capture_event);
}
fn log_raw_write_event(&mut self, file_path: &Path, after: &str) {
let before = self.source_code.as_str();
if before == after {
return;
}
let code_diff = diff_str(before, after);
self.log_server_capture_event(
CaptureEventType::WriteCode,
file_path,
serde_json::json!({
"source": "server_translation",
"classification_basis": "raw_text",
"diff": &code_diff,
}),
);
}
fn log_code_mirror_write_events(
&mut self,
file_path: &Path,
metadata: &SourceFileMetadata,
after: &CodeMirror,
after_source: Option<&str>,
source: &str,
) {
if metadata.mode == MARKDOWN_MODE {
let markdown_diff = {
let before_source = self.source_code.as_str();
let after_source = after_source.unwrap_or(&after.doc);
(before_source != after_source).then(|| diff_str(before_source, after_source))
};
if let Some(diff) = markdown_diff {
self.log_server_capture_event(
CaptureEventType::WriteDoc,
file_path,
serde_json::json!({
"source": source,
"classification_basis": "markdown_source",
"mode": metadata.mode,
"diff": diff,
}),
);
}
return;
}
let code_diff = {
let before_doc = self.code_mirror_doc.as_str();
(before_doc != after.doc).then(|| diff_str(before_doc, &after.doc))
};
let (doc_blocks_changed, doc_block_count_before, doc_block_diff) = {
let before_doc_blocks = self.code_mirror_doc_blocks.as_ref();
let doc_blocks_changed = match before_doc_blocks {
Some(before) => !doc_blocks_compare(before, &after.doc_blocks),
None => !after.doc_blocks.is_empty(),
};
let doc_block_diff = before_doc_blocks.map(|before| {
serde_json::json!(diff_code_mirror_doc_blocks(before, &after.doc_blocks))
});
(
doc_blocks_changed,
before_doc_blocks.map_or(0, Vec::len),
doc_block_diff,
)
};
if let Some(diff) = code_diff {
self.log_server_capture_event(
CaptureEventType::WriteCode,
file_path,
serde_json::json!({
"source": source,
"classification_basis": "codemirror_code_text",
"mode": metadata.mode,
"diff": &diff,
}),
);
}
if doc_blocks_changed {
self.log_server_capture_event(
CaptureEventType::WriteDoc,
file_path,
serde_json::json!({
"source": source,
"classification_basis": "codemirror_doc_blocks",
"mode": metadata.mode,
"doc_block_count_before": doc_block_count_before,
"doc_block_count_after": after.doc_blocks.len(),
"doc_block_diff": doc_block_diff,
}),
);
}
}
// Pass a `Result` message to the Client, unless it's a `LoadFile` result.
#[allow(clippy::too_many_lines)]
async fn ide_result(&mut self, ide_message: EditorMessage) -> bool {
let EditorMessageContents::Result(ref result) = ide_message.message else {
panic!("Should only be called with a result.");
};
let is_loadfile = match result {
// See if this error was produced by a `LoadFile` result.
Err(_) => self
.load_file_requests
.contains_key(&ide_message.id.to_bits()),
Ok(result_ok) => match result_ok {
ResultOkTypes::Void => false,
ResultOkTypes::LoadFile(_) => true,
},
};
// Pass the message to the client if this isn't a `LoadFile` result (the
// only type of result which the Server should handle).
if !is_loadfile {
debug!("Forwarding it to the Client.");
// If the Server can't read our diff, send the full text next time.
if matches!(result, Err(ResultErrTypes::OutOfSync(..))) {
self.sent_full = false;
}
queue_send_func!(self.to_client_tx.send(ide_message));
return true;
}
// Ensure there's an HTTP request for this `LoadFile` result.
let Some(http_request) = self.load_file_requests.remove(&ide_message.id.to_bits()) else {
error!(
"Error: no HTTP request found for LoadFile result ID {}.",
ide_message.id
);
return true;
};
// Take ownership of the result after sending it above (which requires
// ownership).
let EditorMessageContents::Result(result) = ide_message.message else {
panic!("Not a result.");
};
// Get the file contents from a `LoadFile` result; otherwise, this is
// None.
let file_contents_option = match result {
Err(err) => {
error!("{err:?}");
None
}
Ok(result_ok) => match result_ok {
ResultOkTypes::Void => panic!("LoadFile result should not be void."),
ResultOkTypes::LoadFile(file_contents) => file_contents,
},
};
// Process the file contents. Since VSCode doesn't have a PDF viewer,
// determine if this is a PDF file. (TODO: look at the magic number also
// -- "%PDF").
let use_pdf_js = http_request.file_path.extension() == Some(OsStr::new("pdf"));
let ((simple_http_response, option_update), file_contents) = match file_contents_option {
Some((file_contents, new_version)) => {
// Only pay attention to the version if this is an editable
// Client file.
if http_request.file_path == self.current_file
&& http_request.flags == ProcessingTaskHttpRequestFlags::None
{
self.version = new_version;
}
// The IDE just sent the full contents; we're sending full
// contents to the Client.
self.sent_full = true;
(
file_to_response(
&http_request,
&self.cache,
new_version,
&self.current_file,
Some(&file_contents),
use_pdf_js,
)
.await,
file_contents,
)
}
None => {
// The file wasn't available in the IDE. Look for it in the
// filesystem.
match File::open(&http_request.file_path).await {
Err(err) => (
(
SimpleHttpResponse::Err(SimpleHttpResponseError::Io(err)),
None,
),
// There's no file, so return empty contents, which will
// be ignored.
String::new(),
),
Ok(mut fc) => {
let option_file_contents = try_read_as_text(&mut fc).await;
(
file_to_response(
&http_request,
&self.cache,
self.version,
&self.current_file,
option_file_contents.as_ref(),
use_pdf_js,
)
.await,
// If the file is binary, return empty contents,
// which will be ignored.
option_file_contents.unwrap_or(String::new()),
)
}
}
}
};
if let Some(update) = option_update {
let Some(ref tmp) = update.contents else {
panic!("Contents must always be provided.");
};
let CodeMirrorDiffable::Plain(ref plain) = tmp.source else {
panic!("Diff not supported.");
};
self.source_code = file_contents;
self.eol = find_eol_type(&self.source_code);
// We must clone here, since the original is placed in the TX queue.
self.code_mirror_doc.clone_from(&plain.doc);
self.code_mirror_doc_blocks = Some(plain.doc_blocks.clone());
debug!("Sending Update from LoadFile to Client, id = {}.", self.id);
queue_send_func!(self.to_client_tx.send(EditorMessage {
id: self.id,
message: EditorMessageContents::Update(update)
}));
self.id += MESSAGE_ID_INCREMENT;
}