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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
#![deny(warnings)]
pub mod expr;
pub mod fields;
mod named_pipe;
pub mod pdu;
use bytes::{Bytes, BytesMut};
use futures::{future::FutureExt, stream::StreamExt};
use serde_bser::de::{Bunser, SliceRead};
use serde_bser::value::Value;
use std::collections::{HashMap, VecDeque};
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use thiserror::Error;
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
#[cfg(unix)]
use tokio::net::UnixStream;
use tokio::process::Command;
use tokio::sync::mpsc::{Receiver, Sender, UnboundedReceiver, UnboundedSender};
use tokio::sync::Mutex;
use tokio_util::codec::{Decoder, FramedRead};
static SUB_ID: AtomicUsize = AtomicUsize::new(1);
pub mod prelude {
pub use crate::expr::*;
pub use crate::fields::*;
pub use crate::pdu::*;
pub use crate::query_result_type;
pub use crate::{CanonicalPath, Client, Connector, ResolvedRoot};
}
use prelude::*;
#[derive(Error, Debug)]
pub enum ConnectionLost {
#[error("Client task exited")]
ClientTaskExited,
#[error("Client task failed: {0}")]
Error(String),
}
#[derive(Error, Debug)]
pub enum Error {
#[error("Failed to connect to Watchman: {0}")]
ConnectionError(tokio::io::Error),
#[error("Lost connection to watchman")]
ConnectionLost(#[from] ConnectionLost),
#[error(
"While invoking the {watchman_path} CLI to discover the server connection details: {reason}, stderr=`{stderr}`"
)]
ConnectionDiscovery {
watchman_path: PathBuf,
reason: String,
stderr: String,
},
#[error("The watchman server reported an error: \"{}\", while executing command: {}", .message, .command)]
WatchmanServerError { message: String, command: String },
#[error("The watchman server reported an error: \"{}\"", .message)]
WatchmanResponseError { message: String },
#[error("The watchman server didn't return a value for field `{}` in response to a `{}` command. {:?}", .fieldname, .command, .response)]
MissingField {
fieldname: &'static str,
command: String,
response: String,
},
#[error("Deserialization error (data: {data:x?})")]
Deserialize {
data: Vec<u8>,
#[source]
source: anyhow::Error,
},
#[error("Seriaization error")]
Serialize {
#[source]
source: anyhow::Error,
},
#[error("Failed to connect to {endpoint}")]
Connect {
endpoint: PathBuf,
#[source]
source: Box<std::io::Error>,
},
}
#[derive(Error, Debug)]
enum TaskError {
#[error("IO Error: {0}")]
Io(#[from] std::io::Error),
#[error("Task is shutting down")]
Shutdown,
#[error("EOF on Watchman socket")]
Eof,
#[error("Received a unilateral PDU from the server")]
UnilateralPdu,
#[error("Deserialization error (data: {data:x?})")]
Deserialize {
#[source]
source: anyhow::Error,
data: Vec<u8>,
},
}
#[derive(Default)]
pub struct Connector {
watchman_cli_path: Option<PathBuf>,
unix_domain: Option<PathBuf>,
}
impl Connector {
pub fn new() -> Self {
let connector = Self::default();
if let Some(val) = std::env::var_os("WATCHMAN_SOCK") {
connector.unix_domain_socket(val)
} else {
connector
}
}
pub fn watchman_cli_path<P: AsRef<Path>>(mut self, path: P) -> Self {
self.watchman_cli_path = Some(path.as_ref().to_path_buf());
self
}
pub fn unix_domain_socket<P: AsRef<Path>>(mut self, path: P) -> Self {
self.unix_domain = Some(path.as_ref().to_path_buf());
self
}
async fn resolve_unix_domain_path(&self) -> Result<PathBuf, Error> {
if let Some(path) = self.unix_domain.as_ref() {
Ok(path.clone())
} else {
let watchman_path = self
.watchman_cli_path
.as_ref()
.map(|p| p.as_ref())
.unwrap_or_else(|| Path::new("watchman"));
let output = Command::new(watchman_path)
.args(&["--output-encoding", "bser-v2", "get-sockname"])
.output()
.await
.map_err(|source| Error::ConnectionDiscovery {
watchman_path: watchman_path.to_path_buf(),
reason: source.to_string(),
stderr: "".to_string(),
})?;
let info: GetSockNameResponse =
serde_bser::from_slice(&output.stdout).map_err(|source| {
Error::ConnectionDiscovery {
watchman_path: watchman_path.to_path_buf(),
reason: source.to_string(),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
}
})?;
let debug = format!("{:#?}", info);
if let Some(message) = info.error {
return Err(Error::WatchmanServerError {
message,
command: "get-sockname".into(),
});
}
info.sockname.ok_or_else(|| Error::MissingField {
fieldname: "sockname",
command: "get-sockname".into(),
response: debug,
})
}
}
pub async fn connect(&self) -> Result<Client, Error> {
let sock_path = self.resolve_unix_domain_path().await?;
#[cfg(unix)]
let stream = UnixStream::connect(sock_path)
.await
.map_err(Error::ConnectionError)?;
#[cfg(windows)]
let stream = named_pipe::NamedPipe::connect(sock_path).await?;
let stream: Box<dyn ReadWriteStream> = Box::new(stream);
let (reader, writer) = tokio::io::split(stream);
let (request_tx, request_rx) = tokio::sync::mpsc::channel(128);
let mut task = ClientTask {
writer,
reader: FramedRead::new(reader, BserSplitter),
request_rx,
request_queue: VecDeque::new(),
waiting_response: false,
subscriptions: HashMap::new(),
};
tokio::spawn(async move {
if let Err(err) = task.run().await {
eprintln!("watchman client task failed: {}", err);
}
});
let inner = Arc::new(Mutex::new(ClientInner { request_tx }));
Ok(Client { inner })
}
}
#[derive(Debug, Clone)]
pub struct CanonicalPath(PathBuf);
impl CanonicalPath {
pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<Self, std::io::Error> {
let path = std::fs::canonicalize(path)?;
Ok(Self(Self::strip_unc_escape(path)))
}
pub fn with_canonicalized_path(path: PathBuf) -> Self {
assert!(
path.is_absolute(),
"attempted to call \
CanonicalPath::with_canonicalized_path on a non-canonical path! \
You probably want to call CanonicalPath::canonicalize instead!"
);
Self(Self::strip_unc_escape(path))
}
#[cfg(windows)]
#[inline]
fn strip_unc_escape(path: PathBuf) -> PathBuf {
match path.to_str() {
Some(s) if s.starts_with("\\\\?\\") => PathBuf::from(&s[4..]),
_ => path,
}
}
#[cfg(unix)]
#[inline]
fn strip_unc_escape(path: PathBuf) -> PathBuf {
path
}
}
#[derive(Debug, Clone)]
pub struct ResolvedRoot {
root: PathBuf,
relative: Option<PathBuf>,
watcher: String,
}
impl ResolvedRoot {
pub fn watcher(&self) -> &str {
self.watcher.as_str()
}
pub fn project_root(&self) -> &Path {
&self.root
}
pub fn path(&self) -> PathBuf {
if let Some(relative) = self.relative.as_ref() {
self.root.join(relative)
} else {
self.root.clone()
}
}
pub fn project_relative_path(&self) -> Option<&Path> {
self.relative.as_ref().map(PathBuf::as_ref)
}
}
trait ReadWriteStream: AsyncRead + AsyncWrite + std::marker::Unpin + Send {}
#[cfg(unix)]
impl ReadWriteStream for UnixStream {}
struct SendRequest {
buf: Vec<u8>,
tx: tokio::sync::oneshot::Sender<Result<Bytes, String>>,
}
impl SendRequest {
fn respond(self, result: Result<Bytes, String>) {
let _ = self.tx.send(result);
}
}
enum SubscriptionNotification {
Pdu(Bytes),
Canceled,
}
enum TaskItem {
QueueRequest(SendRequest),
RegisterSubscription(String, UnboundedSender<SubscriptionNotification>),
}
struct BserSplitter;
impl Decoder for BserSplitter {
type Item = Bytes;
type Error = TaskError;
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let mut bunser = Bunser::new(SliceRead::new(buf.as_ref()));
let pdu = match bunser.read_pdu() {
Ok(pdu) => pdu,
Err(source) => {
const BUF_SIZE: usize = 16;
let missing = BUF_SIZE.saturating_sub(buf.len());
if missing > 0 {
buf.reserve(missing);
return Ok(None);
}
return Err(TaskError::Deserialize {
source: source.into(),
data: buf.to_vec(),
});
}
};
let total_size = (pdu.start + pdu.len) as usize;
let missing = total_size.saturating_sub(buf.len());
if missing > 0 {
buf.reserve(missing);
return Ok(None);
}
let ret = buf.split_to(total_size);
Ok(Some(ret.freeze()))
}
}
pub struct Client {
inner: Arc<Mutex<ClientInner>>,
}
struct ClientTask {
writer: tokio::io::WriteHalf<Box<dyn ReadWriteStream>>,
reader: FramedRead<tokio::io::ReadHalf<Box<dyn ReadWriteStream>>, BserSplitter>,
request_rx: Receiver<TaskItem>,
request_queue: VecDeque<SendRequest>,
waiting_response: bool,
subscriptions: HashMap<String, UnboundedSender<SubscriptionNotification>>,
}
impl Drop for ClientTask {
fn drop(&mut self) {
self.fail_all(&TaskError::Shutdown)
}
}
impl ClientTask {
async fn run(&mut self) -> Result<(), TaskError> {
match self.run_loop().await {
Err(err) => {
self.fail_all(&err);
Err(err)
}
ok => ok,
}
}
async fn run_loop(&mut self) -> Result<(), TaskError> {
loop {
futures::select_biased! {
pdu = self.reader.next().fuse() => {
match pdu {
Some(pdu) => self.process_pdu(pdu?).await?,
None => return Err(TaskError::Eof),
}
}
task = self.request_rx.recv().fuse() => {
match task {
Some(TaskItem::QueueRequest(request)) => self.queue_request(request).await?,
Some(TaskItem::RegisterSubscription(name, tx)) => {
self.register_subscription(name, tx)
}
None => break,
}
}
}
}
Ok(())
}
fn register_subscription(
&mut self,
name: String,
tx: UnboundedSender<SubscriptionNotification>,
) {
self.subscriptions.insert(name, tx);
}
fn fail_all(&mut self, err: &TaskError) {
while let Some(request) = self.request_queue.pop_front() {
request.respond(Err(err.to_string()));
}
}
async fn send_next_request(&mut self) -> Result<(), TaskError> {
if !self.waiting_response && !self.request_queue.is_empty() {
match self
.writer
.write_all(&self.request_queue.front().expect("not empty").buf)
.await
{
Err(err) => {
return Err(err.into());
}
Ok(_) => self.waiting_response = true,
}
}
Ok(())
}
async fn queue_request(&mut self, request: SendRequest) -> Result<(), TaskError> {
self.request_queue.push_back(request);
self.send_next_request().await?;
Ok(())
}
async fn process_pdu(&mut self, pdu: Bytes) -> Result<(), TaskError> {
use serde::Deserialize;
#[derive(Deserialize, Debug)]
pub struct Unilateral {
pub unilateral: bool,
pub subscription: String,
#[serde(default)]
pub canceled: bool,
}
if let Ok(unilateral) = bunser::<Unilateral>(&pdu) {
if let Some(subscription) = self.subscriptions.get_mut(&unilateral.subscription) {
let msg = if unilateral.canceled {
SubscriptionNotification::Canceled
} else {
SubscriptionNotification::Pdu(pdu)
};
if subscription.send(msg).is_err() || unilateral.canceled {
self.subscriptions.remove(&unilateral.subscription);
}
}
} else if self.waiting_response {
let request = self
.request_queue
.pop_front()
.expect("waiting_response is only true when request_queue is not empty");
self.waiting_response = false;
request.respond(Ok(pdu));
} else {
return Err(TaskError::UnilateralPdu);
}
self.send_next_request().await?;
Ok(())
}
}
fn bunser<T>(buf: &[u8]) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let response: T = serde_bser::from_slice(&buf).map_err(|source| Error::Deserialize {
source: source.into(),
data: buf.to_vec(),
})?;
Ok(response)
}
struct ClientInner {
request_tx: Sender<TaskItem>,
}
impl ClientInner {
pub(crate) async fn generic_request<Request, Response>(
&mut self,
request: Request,
) -> Result<Response, Error>
where
Request: serde::Serialize + std::fmt::Debug,
Response: serde::de::DeserializeOwned,
{
let mut request_data = vec![];
serde_bser::ser::serialize(&mut request_data, &request).map_err(|source| {
Error::Serialize {
source: source.into(),
}
})?;
let (tx, rx) = tokio::sync::oneshot::channel();
self.request_tx
.send(TaskItem::QueueRequest(SendRequest {
buf: request_data,
tx,
}))
.await
.map_err(|_| ConnectionLost::ClientTaskExited)?;
let pdu_data = rx
.await
.map_err(|_| ConnectionLost::ClientTaskExited)?
.map_err(ConnectionLost::Error)?;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct MaybeError {
#[serde(default)]
error: Option<String>,
}
let maybe_err: MaybeError = bunser(&pdu_data)?;
if let Some(message) = maybe_err.error {
return Err(Error::WatchmanServerError {
message,
command: format!("{:#?}", request),
});
}
let response: Response = bunser(&pdu_data)?;
Ok(response)
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum SubscriptionData<F>
where
F: serde::de::DeserializeOwned + std::fmt::Debug + Clone + QueryFieldList,
{
Canceled,
FilesChanged(QueryResult<F>),
StateEnter {
state_name: String,
metadata: Option<Value>,
},
StateLeave {
state_name: String,
metadata: Option<Value>,
},
}
pub struct Subscription<F>
where
F: serde::de::DeserializeOwned + std::fmt::Debug + Clone + QueryFieldList,
{
name: String,
inner: Arc<Mutex<ClientInner>>,
root: ResolvedRoot,
responses: UnboundedReceiver<SubscriptionNotification>,
_phantom: PhantomData<F>,
}
impl<F> Subscription<F>
where
F: serde::de::DeserializeOwned + std::fmt::Debug + Clone + QueryFieldList,
{
pub fn name(&self) -> &str {
&self.name
}
#[allow(clippy::should_implement_trait)]
pub async fn next(&mut self) -> Result<SubscriptionData<F>, Error> {
let msg = self
.responses
.recv()
.await
.ok_or(ConnectionLost::ClientTaskExited)?;
match msg {
SubscriptionNotification::Pdu(pdu) => {
let response: QueryResult<F> = bunser(&pdu)?;
if let Some(state_name) = response.state_enter {
Ok(SubscriptionData::StateEnter {
state_name,
metadata: response.state_metadata,
})
} else if let Some(state_name) = response.state_leave {
Ok(SubscriptionData::StateLeave {
state_name,
metadata: response.state_metadata,
})
} else {
Ok(SubscriptionData::FilesChanged(response))
}
}
SubscriptionNotification::Canceled => {
self.responses.close();
Ok(SubscriptionData::Canceled)
}
}
}
pub async fn cancel(self) -> Result<(), Error> {
let mut inner = self.inner.lock().await;
let _: UnsubscribeResponse = inner
.generic_request(Unsubscribe("unsubscribe", self.root.root, self.name))
.await?;
Ok(())
}
}
impl Client {
#[doc(hidden)]
pub async fn generic_request<Request, Response>(
&self,
request: Request,
) -> Result<Response, Error>
where
Request: serde::Serialize + std::fmt::Debug,
Response: serde::de::DeserializeOwned,
{
let mut inner = self.inner.lock().await;
let response: Response = inner.generic_request(request).await?;
Ok(response)
}
pub async fn resolve_root(&self, path: CanonicalPath) -> Result<ResolvedRoot, Error> {
let response: WatchProjectResponse = self
.generic_request(WatchProjectRequest("watch-project", path.0.clone()))
.await?;
Ok(ResolvedRoot {
root: response.watch,
relative: response.relative_path,
watcher: response.watcher,
})
}
pub async fn query<F>(
&self,
root: &ResolvedRoot,
query: QueryRequestCommon,
) -> Result<QueryResult<F>, Error>
where
F: serde::de::DeserializeOwned + std::fmt::Debug + Clone + QueryFieldList,
{
let query = QueryRequest(
"query",
root.root.clone(),
QueryRequestCommon {
relative_root: root.relative.clone(),
fields: F::field_list(),
..query
},
);
let response: QueryResult<F> = self.generic_request(query.clone()).await?;
Ok(response)
}
pub async fn subscribe<F>(
&self,
root: &ResolvedRoot,
query: SubscribeRequest,
) -> Result<(Subscription<F>, SubscribeResponse), Error>
where
F: serde::de::DeserializeOwned + std::fmt::Debug + Clone + QueryFieldList,
{
let name = format!(
"sub-[{}]-{}",
std::env::args()
.next()
.unwrap_or_else(|| "<no-argv-0>".to_string()),
SUB_ID.fetch_add(1, Ordering::Relaxed)
);
let query = SubscribeCommand(
"subscribe",
root.root.clone(),
name.clone(),
SubscribeRequest {
relative_root: root.relative.clone(),
fields: F::field_list(),
..query
},
);
let (tx, responses) = tokio::sync::mpsc::unbounded_channel();
{
let inner = self.inner.lock().await;
inner
.request_tx
.send(TaskItem::RegisterSubscription(name.clone(), tx))
.await
.map_err(|_| ConnectionLost::ClientTaskExited)?;
}
let subscription = Subscription::<F> {
name,
inner: Arc::clone(&self.inner),
root: root.clone(),
responses,
_phantom: PhantomData,
};
let response: SubscribeResponse = self.generic_request(query).await?;
Ok((subscription, response))
}
pub async fn glob(&self, root: &ResolvedRoot, globs: &[&str]) -> Result<Vec<PathBuf>, Error> {
let response: QueryResult<NameOnly> = self
.query(
root,
QueryRequestCommon {
relative_root: root.relative.clone(),
glob: Some(globs.iter().map(|&s| s.to_string()).collect()),
..Default::default()
},
)
.await?;
Ok(response
.files
.unwrap_or_else(Vec::new)
.into_iter()
.map(|f| f.name.into_inner())
.collect())
}
pub async fn clock(
&self,
root: &ResolvedRoot,
sync_timeout: SyncTimeout,
) -> Result<ClockSpec, Error> {
let response: ClockResponse = self
.generic_request(ClockRequest(
"clock",
root.root.clone(),
ClockRequestParams { sync_timeout },
))
.await?;
Ok(response.clock)
}
pub async fn get_config(&self, root: &ResolvedRoot) -> Result<WatchmanConfig, Error> {
let response: GetConfigResponse = self
.generic_request(GetConfigRequest("get-config", root.root.clone()))
.await?;
Ok(response.config)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::stream::{self, TryStreamExt};
use serde::{Deserialize, Serialize};
use std::io;
use tokio_util::io::StreamReader;
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct TestStruct {
value: i32,
}
#[test]
fn connection_builder_paths() {
let builder = Connector::new().unix_domain_socket("/some/path");
assert_eq!(builder.unix_domain, Some(PathBuf::from("/some/path")));
}
#[tokio::test]
async fn test_decoder() {
async fn read_bser(buf: &[u8], chunk_size: usize) -> Vec<TestStruct> {
let chunks = buf
.chunks(chunk_size)
.map(|c| Result::<_, io::Error>::Ok(Bytes::copy_from_slice(c)));
let reader = StreamReader::new(stream::iter(chunks));
let decoded = FramedRead::new(reader, BserSplitter)
.map_err(TaskError::from)
.and_then(|bytes| async move {
Ok(serde_bser::from_slice::<TestStruct>(&bytes).unwrap())
})
.try_collect()
.await
.unwrap();
decoded
}
let msgs = vec![
TestStruct { value: 1 },
TestStruct { value: 2 },
TestStruct { value: 3 },
];
let mut buf = vec![];
for msg in msgs.iter() {
serde_bser::ser::serialize(&mut buf, msg).expect("Failed to write to a Vec");
}
assert_eq!(msgs, read_bser(&buf, 1).await);
assert_eq!(msgs, read_bser(&buf, 2).await);
assert_eq!(msgs, read_bser(&buf, 10).await);
assert_eq!(msgs, read_bser(&buf, buf.len()).await);
}
#[test]
fn test_decoder_err() {
let mut bytes = BytesMut::new();
bytes.extend_from_slice(&[0; 10]);
let r1 = BserSplitter.decode(&mut bytes);
assert!(r1.is_ok());
assert!(r1.unwrap().is_none());
bytes.extend_from_slice(&[0; 10]);
let r1 = BserSplitter.decode(&mut bytes);
assert!(r1.is_err());
}
#[test]
fn test_bounds() {
fn assert_bounds<T: std::error::Error + Sync + Send + 'static>() {}
assert_bounds::<Error>();
assert_bounds::<TaskError>();
}
}