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
|
use std::{
collections::VecDeque,
io::{Read, Write},
os::fd::{AsRawFd, OwnedFd, RawFd},
sync::{mpsc as std_mpsc, Arc, Mutex},
time::{Duration, Instant},
};
use bytes::Bytes;
use tokio::sync::mpsc::{self, error::TryRecvError as DataTryRecvError};
use tracing::{debug, warn};
use crate::pty::fd;
const ACTOR_POLL_MS: i32 = 50;
const ACTOR_COMMAND_BUFFER: usize = 1024;
const HANDOFF_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ActorState {
Running,
Quiesced,
Released,
}
pub(crate) struct PtyReadResult {
pub terminal_responses: Vec<Bytes>,
}
impl PtyReadResult {
#[cfg(test)]
pub(crate) fn empty() -> Self {
Self {
terminal_responses: Vec::new(),
}
}
}
type ReadCallback = Box<dyn FnMut(&[u8]) -> PtyReadResult + Send + 'static>;
type ReaderExitCallback = Box<dyn FnOnce() + Send + 'static>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PtyResize {
rows: u16,
cols: u16,
cell_width_px: u32,
cell_height_px: u32,
}
#[derive(Default)]
struct SharedPtyControls {
resize: Option<PtyResize>,
nudge: Option<PtyResize>,
}
pub(crate) struct PtyIoActorConfig {
pub pane_id: u32,
pub master_fd: OwnedFd,
pub initially_quiesced: bool,
pub on_read: ReadCallback,
pub on_reader_exit: Option<ReaderExitCallback>,
}
enum PtyIoDataCommand {
Wake,
WriteUserInput(Bytes),
}
enum PtyIoControlCommand {
BeginHandoff(std_mpsc::Sender<std::io::Result<()>>),
DuplicateForHandoff(std_mpsc::Sender<std::io::Result<RawFd>>),
ForegroundProcessGroup(std_mpsc::Sender<Option<u32>>),
RollbackHandoff(std_mpsc::Sender<std::io::Result<()>>),
ReleaseAfterCommit(std_mpsc::Sender<std::io::Result<()>>),
Shutdown,
}
#[derive(Clone)]
pub(crate) struct PtyIoActorHandle {
data_tx: mpsc::Sender<PtyIoDataCommand>,
control_tx: std_mpsc::Sender<PtyIoControlCommand>,
user_writes: Arc<Mutex<UserWriteGate>>,
controls: Arc<Mutex<SharedPtyControls>>,
}
#[derive(Debug)]
struct UserWriteGate {
accepting: bool,
}
impl PtyIoActorHandle {
pub(crate) async fn write_user_input(
&self,
bytes: Bytes,
) -> Result<(), mpsc::error::SendError<Bytes>> {
{
let user_writes = self
.user_writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !user_writes.accepting {
return Err(mpsc::error::SendError(bytes));
}
}
let permit = match self.data_tx.reserve().await {
Ok(permit) => permit,
Err(_) => return Err(mpsc::error::SendError(bytes)),
};
let user_writes = self
.user_writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !user_writes.accepting {
return Err(mpsc::error::SendError(bytes));
}
permit.send(PtyIoDataCommand::WriteUserInput(bytes));
Ok(())
}
pub(crate) fn try_write_user_input(
&self,
bytes: Bytes,
) -> Result<(), mpsc::error::TrySendError<Bytes>> {
let user_writes = self
.user_writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !user_writes.accepting {
return Err(mpsc::error::TrySendError::Closed(bytes));
}
self.data_tx
.try_send(PtyIoDataCommand::WriteUserInput(bytes))
.map_err(|err| match err {
mpsc::error::TrySendError::Full(PtyIoDataCommand::WriteUserInput(bytes)) => {
mpsc::error::TrySendError::Full(bytes)
}
mpsc::error::TrySendError::Closed(PtyIoDataCommand::WriteUserInput(bytes)) => {
mpsc::error::TrySendError::Closed(bytes)
}
mpsc::error::TrySendError::Full(PtyIoDataCommand::Wake) => {
mpsc::error::TrySendError::Full(Bytes::new())
}
mpsc::error::TrySendError::Closed(PtyIoDataCommand::Wake) => {
mpsc::error::TrySendError::Closed(Bytes::new())
}
})
}
pub(crate) fn resize(&self, rows: u16, cols: u16, cell_width_px: u32, cell_height_px: u32) {
{
let mut controls = self
.controls
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
controls.resize = Some(PtyResize {
rows,
cols,
cell_width_px,
cell_height_px,
});
}
let _ = self.data_tx.try_send(PtyIoDataCommand::Wake);
}
pub(crate) fn nudge_child_redraw_after_handoff(
&self,
rows: u16,
cols: u16,
cell_width_px: u32,
cell_height_px: u32,
) {
{
let mut controls = self
.controls
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
controls.nudge = Some(PtyResize {
rows,
cols,
cell_width_px,
cell_height_px,
});
}
let _ = self.data_tx.try_send(PtyIoDataCommand::Wake);
}
pub(crate) fn begin_handoff(&self, timeout: Duration) -> std::io::Result<()> {
let (reply_tx, reply_rx) = std_mpsc::channel();
{
let mut user_writes = self
.user_writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
user_writes.accepting = false;
if self
.control_tx
.send(PtyIoControlCommand::BeginHandoff(reply_tx))
.is_err()
{
user_writes.accepting = true;
return Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"pty actor closed",
));
}
}
match reply_rx.recv_timeout(timeout) {
Ok(Ok(())) => Ok(()),
Ok(Err(err)) => {
let _ = self.rollback_handoff();
Err(err)
}
Err(_) => {
let _ = self.rollback_handoff();
Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"timed out waiting for PTY actor to quiesce",
))
}
}
}
pub(crate) fn duplicate_for_handoff(&self) -> std::io::Result<RawFd> {
let (reply_tx, reply_rx) = std_mpsc::channel();
self.control_tx
.send(PtyIoControlCommand::DuplicateForHandoff(reply_tx))
.map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pty actor closed"))?;
reply_rx.recv_timeout(Duration::from_secs(1)).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
"timed out waiting for PTY handoff duplicate",
)
})?
}
pub(crate) fn foreground_process_group_id(&self) -> Option<u32> {
let (reply_tx, reply_rx) = std_mpsc::channel();
self.control_tx
.send(PtyIoControlCommand::ForegroundProcessGroup(reply_tx))
.ok()?;
reply_rx.recv_timeout(Duration::from_secs(1)).ok()?
}
pub(crate) fn rollback_handoff(&self) -> std::io::Result<()> {
let (reply_tx, reply_rx) = std_mpsc::channel();
self.control_tx
.send(PtyIoControlCommand::RollbackHandoff(reply_tx))
.map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pty actor closed"))?;
let result = reply_rx.recv_timeout(Duration::from_secs(1)).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
"timed out waiting for PTY handoff rollback",
)
})?;
if result.is_ok() {
let mut user_writes = self
.user_writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
user_writes.accepting = true;
}
result
}
pub(crate) fn release_after_commit(&self) -> std::io::Result<()> {
{
let mut user_writes = self
.user_writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
user_writes.accepting = false;
}
let (reply_tx, reply_rx) = std_mpsc::channel();
self.control_tx
.send(PtyIoControlCommand::ReleaseAfterCommit(reply_tx))
.map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pty actor closed"))?;
reply_rx.recv_timeout(Duration::from_secs(1)).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
"timed out waiting for PTY actor release",
)
})?
}
pub(crate) fn shutdown(&self) {
{
let mut user_writes = self
.user_writes
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
user_writes.accepting = false;
}
let _ = self.control_tx.send(PtyIoControlCommand::Shutdown);
}
}
pub(crate) struct PtyIoActor;
impl PtyIoActor {
pub(crate) fn spawn(config: PtyIoActorConfig) -> std::io::Result<PtyIoActorHandle> {
fd::set_cloexec(config.master_fd.as_raw_fd())?;
fd::set_nonblocking(config.master_fd.as_raw_fd())?;
let (data_tx, data_rx) = mpsc::channel(ACTOR_COMMAND_BUFFER);
let (control_tx, control_rx) = std_mpsc::channel();
let user_writes = Arc::new(Mutex::new(UserWriteGate {
accepting: !config.initially_quiesced,
}));
let controls = Arc::new(Mutex::new(SharedPtyControls::default()));
let handle = PtyIoActorHandle {
data_tx,
control_tx,
user_writes,
controls: Arc::clone(&controls),
};
let mut runner = PtyIoActorRunner {
pane_id: config.pane_id,
file: std::fs::File::from(config.master_fd),
data_rx,
control_rx,
state: if config.initially_quiesced {
ActorState::Quiesced
} else {
ActorState::Running
},
pending_writes: VecDeque::new(),
current_write_offset: 0,
controls,
on_read: config.on_read,
on_reader_exit: config.on_reader_exit,
};
std::thread::Builder::new()
.name(format!("herdr-pty-{}", config.pane_id))
.spawn(move || runner.run())
.map_err(|err| std::io::Error::other(err.to_string()))?;
Ok(handle)
}
}
struct PtyIoActorRunner {
pane_id: u32,
file: std::fs::File,
data_rx: mpsc::Receiver<PtyIoDataCommand>,
control_rx: std_mpsc::Receiver<PtyIoControlCommand>,
state: ActorState,
pending_writes: VecDeque<Bytes>,
current_write_offset: usize,
controls: Arc<Mutex<SharedPtyControls>>,
on_read: ReadCallback,
on_reader_exit: Option<ReaderExitCallback>,
}
impl PtyIoActorRunner {
fn run(&mut self) {
let mut should_exit = false;
while !should_exit {
should_exit = self.drain_commands();
if should_exit || self.state == ActorState::Released {
break;
}
self.apply_pending_controls();
if !self.pending_writes.is_empty() {
self.flush_pending_writes_once();
}
if self.state == ActorState::Running {
match fd::poll_read_ready(self.file.as_raw_fd(), ACTOR_POLL_MS) {
Ok(true) => {
if !self.read_once() {
break;
}
}
Ok(false) => {}
Err(err) => {
debug!(pane = self.pane_id, err = %err, "PTY actor poll failed");
break;
}
}
} else {
std::thread::sleep(Duration::from_millis(ACTOR_POLL_MS as u64));
}
}
if let Some(on_reader_exit) = self.on_reader_exit.take() {
on_reader_exit();
}
debug!(pane = self.pane_id, "PTY actor exiting");
}
fn drain_commands(&mut self) -> bool {
if self.drain_control_commands() {
return true;
}
self.drain_data_commands()
}
fn drain_control_commands(&mut self) -> bool {
let mut should_exit = false;
loop {
match self.control_rx.try_recv() {
Ok(command) => {
if self.handle_control_command(command) {
should_exit = true;
break;
}
}
Err(std_mpsc::TryRecvError::Empty) => break,
Err(std_mpsc::TryRecvError::Disconnected) => {
should_exit = true;
break;
}
}
}
should_exit
}
fn drain_data_commands(&mut self) -> bool {
let mut should_exit = false;
loop {
match self.data_rx.try_recv() {
Ok(command) => {
if self.handle_data_command(command) {
should_exit = true;
break;
}
}
Err(DataTryRecvError::Empty) => break,
Err(DataTryRecvError::Disconnected) => {
should_exit = true;
break;
}
}
}
should_exit
}
fn handle_data_command(&mut self, command: PtyIoDataCommand) -> bool {
match command {
PtyIoDataCommand::Wake => {}
PtyIoDataCommand::WriteUserInput(bytes) => {
if self.state == ActorState::Running {
self.pending_writes.push_back(bytes);
}
}
}
false
}
fn handle_control_command(&mut self, command: PtyIoControlCommand) -> bool {
match command {
PtyIoControlCommand::BeginHandoff(reply) => {
let result = self.begin_handoff();
let _ = reply.send(result);
}
PtyIoControlCommand::DuplicateForHandoff(reply) => {
let result = if self.state == ActorState::Quiesced {
fd::duplicate_cloexec_fd(self.file.as_raw_fd())
} else {
Err(std::io::Error::other(
"PTY actor must be quiesced before handoff duplication",
))
};
let _ = reply.send(result);
}
PtyIoControlCommand::ForegroundProcessGroup(reply) => {
let result =
crate::platform::foreground_process_group_id_for_tty_fd(self.file.as_raw_fd());
let _ = reply.send(result);
}
PtyIoControlCommand::RollbackHandoff(reply) => {
let result = if self.state == ActorState::Released {
Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"PTY actor was released before handoff rollback",
))
} else {
self.state = ActorState::Running;
Ok(())
};
let _ = reply.send(result);
}
PtyIoControlCommand::ReleaseAfterCommit(reply) => {
self.state = ActorState::Released;
self.pending_writes.clear();
let _ = reply.send(Ok(()));
return true;
}
PtyIoControlCommand::Shutdown => return true,
}
false
}
fn begin_handoff(&mut self) -> std::io::Result<()> {
self.drain_pre_quiesce_commands();
self.apply_pending_controls();
if self.state == ActorState::Released {
return Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"PTY actor was released before handoff quiesce",
));
}
let deadline = Instant::now() + HANDOFF_DRAIN_TIMEOUT;
while !self.pending_writes.is_empty() {
if Instant::now() >= deadline {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"timed out draining PTY writes before handoff",
));
}
self.flush_pending_writes_once();
}
self.state = ActorState::Quiesced;
Ok(())
}
fn drain_pre_quiesce_commands(&mut self) {
loop {
match self.data_rx.try_recv() {
Ok(PtyIoDataCommand::Wake) => {}
Ok(PtyIoDataCommand::WriteUserInput(bytes)) => {
if self.state != ActorState::Released {
self.pending_writes.push_back(bytes);
}
}
Err(DataTryRecvError::Empty | DataTryRecvError::Disconnected) => break,
}
}
}
fn apply_pending_controls(&mut self) {
let (resize, nudge) = {
let mut controls = self
.controls
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
(controls.resize.take(), controls.nudge.take())
};
if self.state == ActorState::Released {
return;
}
if let Some(resize) = resize {
self.resize(resize);
}
if let Some(nudge) = nudge {
self.nudge(nudge);
}
}
fn read_once(&mut self) -> bool {
let mut buf = [0u8; 8192];
match self.file.read(&mut buf) {
Ok(0) => false,
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => true,
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => true,
Err(err) => {
debug!(pane = self.pane_id, err = %err, "PTY actor read failed");
false
}
Ok(n) => {
let result = (self.on_read)(&buf[..n]);
for response in result.terminal_responses {
if self.state != ActorState::Released {
self.pending_writes.push_back(response);
}
}
true
}
}
}
fn flush_pending_writes_once(&mut self) {
while let Some(bytes) = self.pending_writes.front() {
let chunk = &bytes[self.current_write_offset..];
match self.file.write(chunk) {
Ok(0) => {
warn!(pane = self.pane_id, "PTY actor write returned zero bytes");
return;
}
Ok(written) => {
self.current_write_offset += written;
if self.current_write_offset >= bytes.len() {
self.pending_writes.pop_front();
self.current_write_offset = 0;
}
}
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
let _ = fd::poll_write_ready(self.file.as_raw_fd(), ACTOR_POLL_MS);
return;
}
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => return,
Err(err) => {
warn!(pane = self.pane_id, err = %err, "PTY actor write failed");
self.pending_writes.clear();
self.current_write_offset = 0;
return;
}
}
}
let _ = self.file.flush();
}
fn resize(&self, resize: PtyResize) {
self.log_resize_result(fd::resize_pty_fd(
self.file.as_raw_fd(),
resize.rows,
resize.cols,
resize.cell_width_px,
resize.cell_height_px,
));
}
fn nudge(&mut self, resize: PtyResize) {
if self.state == ActorState::Released {
return;
}
let nudge = if resize.rows > 2 {
(
resize.rows - 1,
resize.cols,
resize.cell_width_px,
resize.cell_height_px,
)
} else {
(
resize.rows,
resize.cols.saturating_sub(1).max(4),
resize.cell_width_px,
resize.cell_height_px,
)
};
if nudge
== (
resize.rows,
resize.cols,
resize.cell_width_px,
resize.cell_height_px,
)
{
return;
}
self.log_resize_result(fd::resize_pty_fd(
self.file.as_raw_fd(),
nudge.0,
nudge.1,
nudge.2,
nudge.3,
));
std::thread::sleep(Duration::from_millis(30));
self.log_resize_result(fd::resize_pty_fd(
self.file.as_raw_fd(),
resize.rows,
resize.cols,
resize.cell_width_px,
resize.cell_height_px,
));
}
fn log_resize_result(&self, result: std::io::Result<()>) {
if let Err(err) = result {
debug!(pane = self.pane_id, err = %err, "PTY resize failed");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{
io::{Read, Write},
os::fd::{FromRawFd, IntoRawFd},
os::unix::net::UnixStream,
};
fn actor_with_socket_pair(
initially_quiesced: bool,
) -> (PtyIoActorHandle, UnixStream, std_mpsc::Receiver<Bytes>) {
let (actor_socket, peer) = UnixStream::pair().expect("socket pair");
actor_socket
.set_nonblocking(true)
.expect("actor socket nonblocking");
peer.set_read_timeout(Some(Duration::from_secs(1)))
.expect("peer timeout");
let owned = unsafe { OwnedFd::from_raw_fd(actor_socket.into_raw_fd()) };
let (read_tx, read_rx) = std_mpsc::channel();
let handle = PtyIoActor::spawn(PtyIoActorConfig {
pane_id: 1,
master_fd: owned,
initially_quiesced,
on_read: Box::new(move |bytes| {
read_tx
.send(Bytes::copy_from_slice(bytes))
.expect("read callback receiver alive");
PtyReadResult::empty()
}),
on_reader_exit: None,
})
.expect("actor spawn");
(handle, peer, read_rx)
}
#[test]
fn actor_writes_user_input_to_owned_fd() {
let (handle, mut peer, _read_rx) = actor_with_socket_pair(false);
handle
.try_write_user_input(Bytes::from_static(b"hello"))
.expect("write command accepted");
let mut buf = [0u8; 5];
peer.read_exact(&mut buf).expect("peer receives write");
assert_eq!(&buf, b"hello");
handle.shutdown();
}
#[test]
fn actor_delivers_fd_reads_to_callback() {
let (handle, mut peer, read_rx) = actor_with_socket_pair(false);
peer.write_all(b"from-peer").expect("peer write");
let read = read_rx
.recv_timeout(Duration::from_secs(1))
.expect("actor read callback");
assert_eq!(read, Bytes::from_static(b"from-peer"));
handle.shutdown();
}
#[test]
fn begin_handoff_stops_reads_and_rejects_user_writes_until_rollback() {
let (handle, mut peer, read_rx) = actor_with_socket_pair(false);
handle
.begin_handoff(Duration::from_secs(1))
.expect("handoff quiesced");
assert!(handle
.try_write_user_input(Bytes::from_static(b"blocked"))
.is_err());
peer.write_all(b"held").expect("peer write during quiesce");
assert!(
read_rx.recv_timeout(Duration::from_millis(150)).is_err(),
"actor must not read while quiesced"
);
handle.rollback_handoff().expect("rollback resumes actor");
let read = read_rx
.recv_timeout(Duration::from_secs(1))
.expect("actor reads held bytes after rollback");
assert_eq!(read, Bytes::from_static(b"held"));
handle
.try_write_user_input(Bytes::from_static(b"after"))
.expect("write accepted after rollback");
let mut buf = [0u8; 5];
peer.read_exact(&mut buf).expect("peer receives after");
assert_eq!(&buf, b"after");
handle.shutdown();
}
#[test]
fn duplicate_for_handoff_requires_quiesced_actor() {
let (handle, mut peer, read_rx) = actor_with_socket_pair(false);
assert!(handle.duplicate_for_handoff().is_err());
handle
.begin_handoff(Duration::from_secs(1))
.expect("handoff quiesced");
let duplicate = handle
.duplicate_for_handoff()
.expect("handoff duplicate created");
assert!(duplicate >= 0);
unsafe {
libc::close(duplicate);
}
handle.rollback_handoff().expect("rollback resumes actor");
peer.write_all(b"still-live").expect("peer write");
let read = read_rx
.recv_timeout(Duration::from_secs(1))
.expect("actor still reads after duplicate closes");
assert_eq!(read, Bytes::from_static(b"still-live"));
handle.shutdown();
}
#[test]
fn resize_and_nudge_keep_latest_request_when_command_queue_is_full() {
let (data_tx, _data_rx) = mpsc::channel(1);
let (control_tx, _control_rx) = std_mpsc::channel();
data_tx
.try_send(PtyIoDataCommand::Wake)
.expect("fill command queue");
let controls = Arc::new(Mutex::new(SharedPtyControls::default()));
let handle = PtyIoActorHandle {
data_tx,
control_tx,
user_writes: Arc::new(Mutex::new(UserWriteGate { accepting: true })),
controls: Arc::clone(&controls),
};
handle.resize(20, 80, 8, 16);
handle.resize(40, 120, 9, 18);
handle.nudge_child_redraw_after_handoff(41, 121, 10, 20);
let controls = controls.lock().expect("controls lock");
assert_eq!(
controls.resize,
Some(PtyResize {
rows: 40,
cols: 120,
cell_width_px: 9,
cell_height_px: 18,
})
);
assert_eq!(
controls.nudge,
Some(PtyResize {
rows: 41,
cols: 121,
cell_width_px: 10,
cell_height_px: 20,
})
);
}
#[tokio::test]
async fn async_user_input_waits_for_queue_capacity() {
let (data_tx, mut data_rx) = mpsc::channel(1);
let (control_tx, _control_rx) = std_mpsc::channel();
data_tx
.try_send(PtyIoDataCommand::Wake)
.expect("fill data queue");
let handle = PtyIoActorHandle {
data_tx,
control_tx,
user_writes: Arc::new(Mutex::new(UserWriteGate { accepting: true })),
controls: Arc::new(Mutex::new(SharedPtyControls::default())),
};
let write = tokio::spawn(async move {
handle
.write_user_input(Bytes::from_static(b"wait-for-capacity"))
.await
});
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(
!write.is_finished(),
"async input should wait for queue capacity"
);
assert!(matches!(data_rx.recv().await, Some(PtyIoDataCommand::Wake)));
write
.await
.expect("write task joins")
.expect("write succeeds after capacity opens");
match data_rx.recv().await {
Some(PtyIoDataCommand::WriteUserInput(bytes)) => {
assert_eq!(bytes, Bytes::from_static(b"wait-for-capacity"));
}
_ => panic!("expected queued user input"),
}
}
#[tokio::test]
async fn async_user_input_waiting_for_capacity_is_rejected_after_handoff_begins() {
let (data_tx, mut data_rx) = mpsc::channel(1);
let (control_tx, control_rx) = std_mpsc::channel();
data_tx
.try_send(PtyIoDataCommand::Wake)
.expect("fill data queue");
let handle = PtyIoActorHandle {
data_tx,
control_tx,
user_writes: Arc::new(Mutex::new(UserWriteGate { accepting: true })),
controls: Arc::new(Mutex::new(SharedPtyControls::default())),
};
let write_handle = handle.clone();
let write = tokio::spawn(async move {
write_handle
.write_user_input(Bytes::from_static(b"after-handoff-start"))
.await
});
tokio::time::sleep(Duration::from_millis(50)).await;
let handoff = std::thread::spawn(move || handle.begin_handoff(Duration::from_secs(1)));
match control_rx
.recv_timeout(Duration::from_secs(1))
.expect("handoff control command")
{
PtyIoControlCommand::BeginHandoff(reply) => {
reply.send(Ok(())).expect("handoff waiter alive");
}
_ => panic!("expected begin handoff command"),
}
handoff
.join()
.expect("handoff thread joins")
.expect("handoff succeeds");
assert!(matches!(data_rx.recv().await, Some(PtyIoDataCommand::Wake)));
let err = write.await.expect("write task joins").expect_err(
"write waiting for capacity must be rejected after handoff closes the input gate",
);
assert_eq!(err.0, Bytes::from_static(b"after-handoff-start"));
match tokio::time::timeout(Duration::from_millis(50), data_rx.recv()).await {
Err(_) | Ok(None) => {}
Ok(Some(_)) => panic!("rejected write must not be queued"),
}
}
#[test]
fn handoff_control_is_not_blocked_by_full_data_queue() {
let (data_tx, _data_rx) = mpsc::channel(1);
let (control_tx, control_rx) = std_mpsc::channel();
data_tx
.try_send(PtyIoDataCommand::Wake)
.expect("fill data queue");
let handle = PtyIoActorHandle {
data_tx,
control_tx,
user_writes: Arc::new(Mutex::new(UserWriteGate { accepting: true })),
controls: Arc::new(Mutex::new(SharedPtyControls::default())),
};
let handoff = std::thread::spawn(move || handle.begin_handoff(Duration::from_secs(1)));
match control_rx
.recv_timeout(Duration::from_secs(1))
.expect("handoff control command")
{
PtyIoControlCommand::BeginHandoff(reply) => {
reply.send(Ok(())).expect("handoff waiter alive");
}
_ => panic!("expected begin handoff command"),
}
handoff
.join()
.expect("handoff thread joins")
.expect("handoff succeeds despite full data queue");
}
#[test]
fn begin_handoff_drains_user_writes_already_in_command_queue() {
let (actor_socket, mut peer) = UnixStream::pair().expect("socket pair");
actor_socket
.set_nonblocking(true)
.expect("actor socket nonblocking");
peer.set_read_timeout(Some(Duration::from_secs(1)))
.expect("peer timeout");
let (data_tx, data_rx) = mpsc::channel(ACTOR_COMMAND_BUFFER);
let (_control_tx, control_rx) = std_mpsc::channel();
data_tx
.try_send(PtyIoDataCommand::WriteUserInput(Bytes::from_static(
b"queued-before-ack",
)))
.expect("queued write");
let mut runner = PtyIoActorRunner {
pane_id: 1,
file: std::fs::File::from(unsafe { OwnedFd::from_raw_fd(actor_socket.into_raw_fd()) }),
data_rx,
control_rx,
state: ActorState::Running,
pending_writes: VecDeque::new(),
current_write_offset: 0,
controls: Arc::new(Mutex::new(SharedPtyControls::default())),
on_read: Box::new(|_| PtyReadResult::empty()),
on_reader_exit: None,
};
runner.begin_handoff().expect("handoff drains queued write");
let mut buf = [0u8; 17];
peer.read_exact(&mut buf)
.expect("queued write reaches peer before quiesce ack");
assert_eq!(&buf, b"queued-before-ack");
assert_eq!(runner.state, ActorState::Quiesced);
}
#[test]
fn release_after_commit_prevents_further_io() {
let (handle, mut peer, read_rx) = actor_with_socket_pair(false);
handle.release_after_commit().expect("actor released");
assert!(handle
.try_write_user_input(Bytes::from_static(b"blocked"))
.is_err());
let _ = peer.write_all(b"ignored");
assert!(read_rx.recv_timeout(Duration::from_millis(150)).is_err());
}
}
|