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
//! The set of core ØMQ socket traits. mod raw; mod recv; mod send; pub(crate) mod sockopt; pub(crate) use raw::*; pub use recv::*; pub use send::*; /// Prevent users from implementing the AsRawSocket trait. mod private { use super::*; use crate::socket::*; pub trait Sealed {} impl Sealed for SocketConfig {} impl Sealed for SendConfig {} impl Sealed for RecvConfig {} impl Sealed for Client {} impl Sealed for ClientConfig {} impl Sealed for ClientBuilder {} impl Sealed for Server {} impl Sealed for ServerConfig {} impl Sealed for ServerBuilder {} impl Sealed for Radio {} impl Sealed for RadioConfig {} impl Sealed for RadioBuilder {} impl Sealed for Dish {} impl Sealed for DishConfig {} impl Sealed for DishBuilder {} impl Sealed for Scatter {} impl Sealed for ScatterConfig {} impl Sealed for ScatterBuilder {} impl Sealed for Gather {} impl Sealed for GatherConfig {} impl Sealed for GatherBuilder {} impl Sealed for SocketType {} // Pub crate use crate::old::OldSocket; impl Sealed for OldSocket {} } use crate::{addr::Endpoint, auth::*, error::Error}; use humantime_serde::Serde; use serde::{Deserialize, Serialize}; use std::{sync::MutexGuard, time::Duration}; /// Represents a period of time. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(from = "Serde<Option<Duration>>")] #[serde(into = "Serde<Option<Duration>>")] pub enum Period { /// A unbounded period of time. Infinite, /// A bounded period of time. Finite(Duration), } pub use Period::*; impl Default for Period { fn default() -> Self { Infinite } } #[doc(hidden)] impl From<Period> for Option<Duration> { fn from(period: Period) -> Self { match period { Finite(duration) => Some(duration), Infinite => None, } } } #[doc(hidden)] impl From<Option<Duration>> for Period { fn from(option: Option<Duration>) -> Self { match option { None => Infinite, Some(duration) => Finite(duration), } } } #[doc(hidden)] impl From<Serde<Option<Duration>>> for Period { fn from(serde: Serde<Option<Duration>>) -> Self { match serde.into_inner() { None => Infinite, Some(duration) => Finite(duration), } } } #[doc(hidden)] impl From<Period> for Serde<Option<Duration>> { fn from(period: Period) -> Self { let inner = match period { Finite(duration) => Some(duration), Infinite => None, }; Serde::from(inner) } } /// Represents a quantity. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(from = "Option<i32>")] #[serde(into = "Option<i32>")] pub enum Quantity { /// A fixed quantity. Limited(i32), /// A unlimited quantity. Unlimited, } pub use Quantity::*; impl Default for Quantity { fn default() -> Self { Unlimited } } #[doc(hidden)] impl From<Quantity> for Option<i32> { fn from(qty: Quantity) -> Self { match qty { Limited(qty) => Some(qty), Unlimited => None, } } } #[doc(hidden)] impl From<Option<i32>> for Quantity { fn from(option: Option<i32>) -> Self { match option { None => Unlimited, Some(qty) => Limited(qty), } } } /// Socket heartbeating configuration. /// /// # Example /// ``` /// use libzmq::Heartbeat; /// use std::time::Duration; /// /// let duration = Duration::from_millis(300); /// /// let hb = Heartbeat::new(duration) /// .add_timeout(2 * duration); /// ``` #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Heartbeat { #[serde(with = "humantime_serde")] pub(crate) interval: Duration, pub(crate) timeout: Period, pub(crate) ttl: Period, } impl Heartbeat { /// Create a new `Heartbeat` from the given interval. /// /// This interval specifies the duration between each heartbeat. pub fn new<D>(interval: D) -> Self where D: Into<Duration>, { Self { interval: interval.into(), timeout: Infinite, ttl: Infinite, } } /// Returns the interval between each heartbeat. pub fn interval(&self) -> Duration { self.interval } /// Set a timeout for the `Heartbeat`. /// /// This timeout specifies how long to wait before timing out a connection /// with a peer for not receiving any traffic. pub fn add_timeout<D>(mut self, timeout: D) -> Self where D: Into<Duration>, { self.timeout = Finite(timeout.into()); self } /// Returns the heartbeat timeout. pub fn timeout(&self) -> Period { self.timeout } /// Set a ttl for the `Heartbeat` /// /// This ttl is equivalent to a `heartbeat_timeout` for the remote /// side for this specific connection. pub fn add_ttl<D>(mut self, ttl: D) -> Self where D: Into<Duration>, { self.ttl = Finite(ttl.into()); self } /// Returns the heartbeat ttl. pub fn ttl(&self) -> Period { self.ttl } } impl<'a> From<&'a Heartbeat> for Heartbeat { fn from(hb: &'a Heartbeat) -> Self { hb.to_owned() } } /// Methods shared by all thread-safe sockets. pub trait Socket: GetRawSocket { /// Schedules a connection to one or more [`Endpoints`] and then accepts /// incoming connections. /// /// Since ØMQ handles all connections behind the curtain, one cannot know /// exactly when the connection is truly established a blocking `send` /// or `recv` call is made on that connection. /// /// When any of the connection attempt fail, the `Error` will contain the position /// of the iterator before the failure. This represents the number of /// connections that succeeded before the failure. /// /// # Usage Contract /// * The endpoint's protocol must be supported by the socket. /// /// # Returned Errors /// * [`InvalidInput`] (transport incompatible or not supported) /// * [`CtxTerminated`] /// /// # Example /// ``` /// # use failure::Error; /// # /// # fn main() -> Result<(), Error> { /// use libzmq::{prelude::*, Client, TcpAddr}; /// use std::convert::TryInto; /// /// let addr1: TcpAddr = "127.0.0.1:420".try_into()?; /// let addr2: TcpAddr = "127.0.0.1:69".try_into()?; /// /// let client = Client::new()?; /// // Connect to multiple endpoints at once. /// client.connect(&[addr1, addr2])?; /// # /// # Ok(()) /// # } /// ``` /// [`Endpoints`]: ../endpoint/enum.Endpoint.html /// [`InvalidInput`]: ../enum.ErrorKind.html#variant.InvalidInput /// [`CtxTerminated`]: ../enum.ErrorKind.html#variant.CtxTerminated fn connect<I, E>(&self, endpoints: I) -> Result<(), Error<usize>> where I: IntoIterator<Item = E>, E: Into<Endpoint>, { let mut count = 0; let raw_socket = self.raw_socket(); for endpoint in endpoints.into_iter().map(E::into) { raw_socket .connect(&endpoint) .map_err(|err| Error::with_content(err.kind(), count))?; count += 1; } Ok(()) } /// Schedules a bind to one or more [`Endpoints`] and then accepts /// incoming connections. /// /// As opposed to `connect`, the socket will straight await and start /// accepting connections. /// /// When any of the connection attempt fail, the `Error` will contain the position /// of the iterator before the failure. This represents the number of /// binds that succeeded before the failure. /// /// # Usage Contract /// * The transport must be supported by the socket type. /// * The endpoint must not be in use. /// * The endpoint must be local. /// /// # Returned Errors /// * [`InvalidInput`] (transport incompatible or not supported) /// * [`AddrInUse`] (addr already in use) /// * [`AddrNotAvailable`] (addr not local) /// * [`CtxTerminated`] /// /// # Example /// ``` /// # use failure::Error; /// # /// # fn main() -> Result<(), Error> { /// use libzmq::{prelude::*, Server, TcpAddr}; /// use std::convert::TryInto; /// /// // Use a system-assigned port. /// let addr: TcpAddr = "127.0.0.1:*".try_into()?; /// /// let server = Server::new()?; /// server.bind(addr)?; /// # /// # Ok(()) /// # } /// ``` /// [`Endpoints`]: ../endpoint/enum.Endpoint.html /// [`InvalidInput`]: ../enum.ErrorKind.html#variant.InvalidInput /// [`AddrInUse`]: ../enum.ErrorKind.html#variant.AddrInUse /// [`AddrNotAvailable`]: ../enum.ErrorKind.html#variant.AddrNotAvailable /// [`CtxTerminated`]: ../enum.ErrorKind.html#variant.CtxTerminated fn bind<I, E>(&self, endpoints: I) -> Result<(), Error<usize>> where I: IntoIterator<Item = E>, E: Into<Endpoint>, { let mut count = 0; let raw_socket = self.raw_socket(); for endpoint in endpoints.into_iter().map(E::into) { raw_socket .bind(&endpoint) .map_err(|err| Error::with_content(err.kind(), count))?; count += 1; } Ok(()) } /// Disconnect the socket from one or more [`Endpoints`]. /// /// The behavior of `disconnect` varies depending whether the endpoint /// was connected or bound to. Note that, in both cases, the disconnection /// is not immediate. /// /// When any of the connection attempt fail, the `Error` will contain the position /// of the iterator before the failure. This represents the number of /// disconnections that succeeded before the failure. /// /// ## Disconnect from a connected endpoint /// The socket stops receiving and sending messages to the remote. /// The incoming and outgoing queue of the socket associated to the endpoint are discarded. /// However, the remote server might still have outstanding messages from /// the socket sent prior to the disconnection in its incoming queue. /// /// ## Disconnect from a bound endpoint /// The socket stops receiving and sending messages to peers connected to the /// now unbound endpoint. The outgoing queue of the socket associated to the /// endpoint is discarded, but incoming queue is kept. /// /// # Usage Contract /// * The endpoint must be currently connected or bound to. /// /// # Returned Errors /// * [`NotFound`] (endpoint was not bound to) /// * [`CtxTerminated`] /// /// /// [`Endpoints`]: ../endpoint/enum.Endpoint.html /// [`CtxTerminated`]: ../enum.ErrorKind.html#variant.CtxTerminated /// [`NotFound`]: ../enum.ErrorKind.html#variant.NotFound fn disconnect<I, E>(&self, endpoints: I) -> Result<(), Error<usize>> where I: IntoIterator<Item = E>, E: Into<Endpoint>, { let mut count = 0; let raw_socket = self.raw_socket(); for endpoint in endpoints.into_iter().map(E::into) { raw_socket .disconnect(&endpoint) .map_err(|err| Error::with_content(err.kind(), count))?; count += 1; } Ok(()) } /// Retrieve the last endpoint connected or bound to. /// /// This is the only way to retreive the value of a bound `Dynamic` port. /// /// # Example /// ``` /// # use failure::Error; /// # /// # fn main() -> Result<(), Error> { /// use libzmq::{prelude::*, Server, TcpAddr, addr::Endpoint}; /// /// // We create a tcp addr with an unspecified port. /// // This port will be assigned by the OS upon connection. /// let addr: TcpAddr = "127.0.0.1:*".try_into()?; /// assert!(addr.host().port().is_unspecified()); /// /// let server = Server::new()?; /// assert!(server.last_endpoint()?.is_none()); /// /// server.bind(&addr)?; /// /// if let Endpoint::Tcp(tcp) = server.last_endpoint()?.unwrap() { /// // The port was indeed assigned by the OS. /// assert!(tcp.host().port().is_specified()); /// } else { /// unreachable!(); /// } /// # /// # Ok(()) /// # } /// ``` fn last_endpoint(&self) -> Result<Option<Endpoint>, Error> { self.raw_socket().last_endpoint() } /// Returns the socket's [`Mechanism`]. /// /// # Example /// ``` /// # use failure::Error; /// # /// # fn main() -> Result<(), Error> { /// use libzmq::{prelude::*, Server, auth::Mechanism}; /// /// let server = Server::new()?; /// assert_eq!(server.mechanism(), Mechanism::Null); /// # /// # Ok(()) /// # } /// ``` /// /// [`Mechanism`]: ../auth/enum.Mechanism.html fn mechanism(&self) -> Mechanism { self.raw_socket().mechanism().lock().unwrap().to_owned() } /// Set the socket's [`Mechanism`]. /// # Example /// ``` /// # use failure::Error; /// # /// # fn main() -> Result<(), Error> { /// use libzmq::{prelude::*, Client, auth::*}; /// /// let client = Client::new()?; /// assert_eq!(client.mechanism(), Mechanism::Null); /// /// let server_cert = CurveCert::new_unique(); /// // We do not specify a client certificate, so it /// // will be automatically generated. /// let creds = CurveClientCreds::new(server_cert.public()); /// /// client.set_mechanism(&creds)?; /// /// if let Mechanism::CurveClient(creds) = client.mechanism() { /// assert_eq!(creds.server(), server_cert.public()); /// assert!(creds.cert().is_some()); /// } else { /// unreachable!() /// } /// # /// # Ok(()) /// # } /// ``` /// /// [`Mechanism`]: ../auth/enum.Mechanism.html fn set_mechanism<M>(&self, mechanism: M) -> Result<(), Error> where M: Into<Mechanism>, { let raw_socket = self.raw_socket(); let mechanism = mechanism.into(); let mutex = raw_socket.mechanism().lock().unwrap(); set_mechanism(raw_socket, mechanism, mutex) } /// Returns a the socket's heartbeat configuration. fn heartbeat(&self) -> Option<Heartbeat> { self.raw_socket().heartbeat().lock().unwrap().to_owned() } /// Set the socket's heartbeat configuration. /// /// Only applies to connection based transports such as `TCP`. /// A value of `None` means no heartbeating. /// /// # Contract /// * timeout and interval duration in ms cannot exceed i32::MAX /// * ttl duration in ms cannot exceed 6553599 /// /// # Default value /// `None` /// /// # Return Errors /// * [InvalidInput`]: (if contract no respected) /// /// # Example /// ``` /// # use failure::Error; /// # /// # fn main() -> Result<(), Error> { /// use libzmq::{prelude::*, Client, Heartbeat, auth::*}; /// use std::time::Duration; /// /// let client = Client::new()?; /// assert_eq!(client.heartbeat(), None); /// /// let duration = Duration::from_millis(300); /// let hb = Heartbeat::new(duration) /// .add_timeout(2 * duration); /// let expected = hb.clone(); /// /// client.set_heartbeat(Some(hb))?; /// assert_eq!(client.heartbeat(), Some(expected)); /// # /// # Ok(()) /// # } /// ``` /// /// [`Mechanism`]: ../auth/enum.Mechanism.html fn set_heartbeat(&self, maybe: Option<Heartbeat>) -> Result<(), Error> { let raw_socket = self.raw_socket(); let mutex = raw_socket.heartbeat().lock().unwrap(); set_heartbeat(raw_socket, maybe, mutex) } } fn set_mechanism( raw_socket: &RawSocket, mut mechanism: Mechanism, mut mutex: MutexGuard<Mechanism>, ) -> Result<(), Error> { if *mutex == mechanism { return Ok(()); } // Undo the previous mechanism. match &*mutex { Mechanism::Null => (), Mechanism::PlainClient(_) => { raw_socket.set_username(None)?; raw_socket.set_password(None)?; } Mechanism::PlainServer => { raw_socket.set_plain_server(false)?; } Mechanism::CurveClient(_) => { raw_socket.set_curve_server_key(None)?; raw_socket.set_curve_public_key(None)?; raw_socket.set_curve_secret_key(None)?; } Mechanism::CurveServer(_) => { raw_socket.set_curve_secret_key(None)?; raw_socket.set_curve_server(false)?; } } // Check if we need to generate a client cert. let mut missing_client_cert = false; if let Mechanism::CurveClient(creds) = &mechanism { if creds.client.is_none() { missing_client_cert = true; } } // Generate a client certificate if it was not supplied. if missing_client_cert { let cert = CurveCert::new_unique(); let server_key = if let Mechanism::CurveClient(creds) = mechanism { creds.server } else { unreachable!() }; let creds = CurveClientCreds { client: Some(cert), server: server_key, }; mechanism = Mechanism::CurveClient(creds); } // Apply the new mechanism. match &mechanism { Mechanism::Null => (), Mechanism::PlainClient(creds) => { raw_socket.set_username(Some(&creds.username))?; raw_socket.set_password(Some(&creds.password))?; } Mechanism::PlainServer => { raw_socket.set_plain_server(true)?; } Mechanism::CurveClient(creds) => { let server_key: BinCurveKey = (&creds.server).into(); raw_socket.set_curve_server_key(Some(&server_key))?; // Cannot fail since we would have generated a cert. let cert = creds.client.as_ref().unwrap(); let public_key: BinCurveKey = cert.public().into(); raw_socket.set_curve_public_key(Some(&public_key))?; let secret_key: BinCurveKey = cert.secret().into(); raw_socket.set_curve_secret_key(Some(&secret_key))?; } Mechanism::CurveServer(creds) => { let secret_key: BinCurveKey = (&creds.secret).into(); raw_socket.set_curve_secret_key(Some(&secret_key))?; raw_socket.set_curve_server(true)?; } } // Update mechanism *mutex = mechanism; Ok(()) } fn set_heartbeat( raw_socket: &RawSocket, maybe: Option<Heartbeat>, mut mutex: MutexGuard<Option<Heartbeat>>, ) -> Result<(), Error> { if *mutex == maybe { return Ok(()); } if let Some(heartbeat) = &maybe { raw_socket.set_heartbeat_interval(heartbeat.interval)?; if let Finite(timeout) = heartbeat.timeout { raw_socket.set_heartbeat_timeout(timeout)?; } if let Finite(ttl) = heartbeat.ttl { raw_socket.set_heartbeat_timeout(ttl)?; } } else { raw_socket.set_heartbeat_interval(Duration::from_millis(0))?; raw_socket.set_heartbeat_timeout(Duration::from_millis(0))?; raw_socket.set_heartbeat_ttl(Duration::from_millis(0))?; } *mutex = maybe; Ok(()) } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash)] #[doc(hidden)] pub struct SocketConfig { pub(crate) connect: Option<Vec<Endpoint>>, pub(crate) bind: Option<Vec<Endpoint>>, pub(crate) heartbeat: Option<Heartbeat>, pub(crate) mechanism: Option<Mechanism>, } impl SocketConfig { pub(crate) fn apply<S: Socket>( &self, socket: &S, ) -> Result<(), Error<usize>> { socket .set_heartbeat(self.heartbeat.clone()) .map_err(Error::cast)?; if let Some(ref mechanism) = self.mechanism { socket.set_mechanism(mechanism).map_err(Error::cast)?; } // We connect as the last step because some socket options // only affect subsequent connections. if let Some(ref endpoints) = self.connect { socket.connect(endpoints)?; } if let Some(ref endpoints) = self.bind { socket.bind(endpoints)?; } Ok(()) } } #[doc(hidden)] pub trait GetSocketConfig: private::Sealed { fn socket_config(&self) -> &SocketConfig; fn socket_config_mut(&mut self) -> &mut SocketConfig; } impl GetSocketConfig for SocketConfig { fn socket_config(&self) -> &SocketConfig { self } fn socket_config_mut(&mut self) -> &mut SocketConfig { self } } /// A set of provided methods for a socket configuration. pub trait ConfigureSocket: GetSocketConfig { fn connect(&self) -> Option<&[Endpoint]> { self.socket_config().connect.as_ref().map(Vec::as_slice) } fn set_connect<I, E>(&mut self, maybe: Option<I>) where I: IntoIterator<Item = E>, E: Into<Endpoint>, { let maybe: Option<Vec<Endpoint>> = maybe.map(|e| e.into_iter().map(E::into).collect()); self.socket_config_mut().connect = maybe; } fn bind(&self) -> Option<&[Endpoint]> { self.socket_config().bind.as_ref().map(Vec::as_slice) } fn set_bind<I, E>(&mut self, maybe: Option<I>) where I: IntoIterator<Item = E>, E: Into<Endpoint>, { let maybe: Option<Vec<Endpoint>> = maybe.map(|e| e.into_iter().map(E::into).collect()); self.socket_config_mut().bind = maybe; } fn mechanism(&self) -> Option<&Mechanism> { self.socket_config().mechanism.as_ref() } fn set_mechanism(&mut self, maybe: Option<Mechanism>) { self.socket_config_mut().mechanism = maybe; } fn heartbeat(&self) -> Option<&Heartbeat> { self.socket_config().heartbeat.as_ref() } fn set_heartbeat(&mut self, maybe: Option<Heartbeat>) { self.socket_config_mut().heartbeat = maybe; } } impl ConfigureSocket for SocketConfig {} /// A set of provided methods for a socket builder. pub trait BuildSocket: GetSocketConfig + Sized { fn connect<I, E>(&mut self, endpoints: I) -> &mut Self where I: IntoIterator<Item = E>, E: Into<Endpoint>, { self.socket_config_mut().set_connect(Some(endpoints)); self } fn bind<I, E>(&mut self, endpoints: I) -> &mut Self where I: IntoIterator<Item = E>, E: Into<Endpoint>, { self.socket_config_mut().set_bind(Some(endpoints)); self } fn mechanism<M>(&mut self, mechanism: M) -> &mut Self where M: Into<Mechanism>, { self.socket_config_mut() .set_mechanism(Some(mechanism.into())); self } fn heartbeat<H>(&mut self, heartbeat: H) -> &mut Self where H: Into<Heartbeat>, { self.socket_config_mut() .set_heartbeat(Some(heartbeat.into())); self } } #[cfg(test)] mod test { #[test] fn test_disconnect_connection() { use crate::{prelude::*, *}; use std::{convert::TryInto, thread, time::Duration}; // Use a system-assigned port. let addr: TcpAddr = "127.0.0.1:*".try_into().unwrap(); let server = ServerBuilder::new() .bind(addr) .recv_high_water_mark(1) .build() .unwrap(); let bound = server.last_endpoint().unwrap(); let client = ClientBuilder::new().connect(&bound).build().unwrap(); for _ in 0..3 { client.send("").unwrap(); } // Confirm that we can indeed recv messages. let mut msg = server.recv_msg().unwrap(); let id = msg.routing_id().unwrap(); server.route("", id).unwrap(); // Since the server has a recv high water mark of 1, // this means that is only one outstanding message. client.disconnect(bound).unwrap(); // Let the client some time to disconnect. thread::sleep(Duration::from_millis(50)); // The client's incoming message queue was discarded. client.try_recv(&mut msg).unwrap_err(); // We received this message before the disconnection. server.recv(&mut msg).unwrap(); // The client's outgoing message queue was discarded. server.try_recv(&mut msg).unwrap_err(); } #[test] fn test_disconnect_bind() { use crate::{prelude::*, *}; use std::{convert::TryInto, thread, time::Duration}; // Use a system-assigned port. let addr: TcpAddr = "127.0.0.1:*".try_into().unwrap(); let server = ServerBuilder::new().bind(addr).build().unwrap(); let bound = server.last_endpoint().unwrap(); let client = ClientBuilder::new().connect(&bound).build().unwrap(); for _ in 0..3 { client.send("").unwrap(); } // Confirm that we can indeed recv messages. let mut msg = server.recv_msg().unwrap(); let id = msg.routing_id().unwrap(); server.route("", id).unwrap(); server.disconnect(bound).unwrap(); // Let the server some time to disconnect. thread::sleep(Duration::from_millis(50)); // The client can recv messages sent before the disconnection. client.recv(&mut msg).unwrap(); // The server's incoming queue was not discarded. for _ in 0..2 { server.recv(&mut msg).unwrap(); } client.send("").unwrap(); // However the socket no longer accepts new messages. server.try_recv(&mut msg).unwrap_err(); // And we can't reply to the client anymore. let err = server.route("", id).unwrap_err(); match err.kind() { ErrorKind::HostUnreachable => (), _ => panic!(), } } }