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 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
//! A Rust client for the NATS.io ecosystem. //! //! `git clone https://github.com/nats-io/nats.rs` //! //! NATS.io is a simple, secure and high performance open source messaging system for cloud native //! applications, `IoT` messaging, and microservices architectures. //! //! For more information see [https://nats.io/]. //! //! [https://nats.io/]: https://nats.io/ //! //! ## Examples //! //! `> cargo run --example nats-box -- -h` //! //! Basic connections, and those with options. The compiler will force these to be correct. //! //! ```no_run //! # fn main() -> Result<(), Box<dyn std::error::Error>> { //! let nc = nats::connect("demo.nats.io")?; //! //! let nc2 = nats::ConnectionOptions::new() //! .with_name("My Rust NATS App") //! .with_user_pass("derek", "s3cr3t!") //! .connect("127.0.0.1")?; //! //! let nc3 = nats::ConnectionOptions::new() //! .with_credentials("path/to/my.creds") //! .connect("connect.ngs.global")?; //! //! let tls_connector = nats::tls::builder() //! .identity(nats::tls::Identity::from_pkcs12(b"der_bytes", "my_password")?) //! .add_root_certificate(nats::tls::Certificate::from_pem(b"my_pem_bytes")?) //! .build()?; //! //! let nc4 = nats::ConnectionOptions::new() //! .tls_connector(tls_connector) //! .connect("tls://demo.nats.io:4443")?; //! # Ok(()) } //! ``` //! //! ### Publish //! //! ```no_run //! # fn main() -> std::io::Result<()> { //! let nc = nats::connect("demo.nats.io")?; //! nc.publish("my.subject", "Hello World!")?; //! //! nc.publish("my.subject", "my message")?; //! //! // Publish a request manually. //! let reply = nc.new_inbox(); //! let rsub = nc.subscribe(&reply)?; //! nc.publish_request("my.subject", &reply, "Help me!")?; //! # Ok(()) } //! ``` //! //! ### Subscribe //! //! ```no_run //! # fn main() -> std::io::Result<()> { //! # use std::time::Duration; //! let nc = nats::connect("demo.nats.io")?; //! let sub = nc.subscribe("foo")?; //! for msg in sub.messages() {} //! //! // Using next. //! if let Some(msg) = sub.next() {} //! //! // Other iterators. //! for msg in sub.try_iter() {} //! for msg in sub.timeout_iter(Duration::from_secs(10)) {} //! //! // Using a threaded handler. //! let sub = nc.subscribe("bar")?.with_handler(move |msg| { //! println!("Received {}", &msg); //! Ok(()) //! }); //! //! // Queue subscription. //! let qsub = nc.queue_subscribe("foo", "my_group")?; //! # Ok(()) } //! ``` //! //! ### Request/Response //! //! ```no_run //! # use std::time::Duration; //! # fn main() -> std::io::Result<()> { //! let nc = nats::connect("demo.nats.io")?; //! let resp = nc.request("foo", "Help me?")?; //! //! // With a timeout. //! let resp = nc.request_timeout("foo", "Help me?", Duration::from_secs(2))?; //! //! // With multiple responses. //! for msg in nc.request_multi("foo", "Help")?.iter() {} //! //! // Publish a request manually. //! let reply = nc.new_inbox(); //! let rsub = nc.subscribe(&reply)?; //! nc.publish_request("foo", &reply, "Help me!")?; //! let response = rsub.iter().take(1); //! # Ok(()) } //! ``` #![cfg_attr(test, deny(warnings))] #![deny( missing_docs, future_incompatible, nonstandard_style, rust_2018_idioms, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unused_qualifications )] #![deny( // over time, consider enabling the following commented-out lints: // clippy::else_if_without_else, // clippy::indexing_slicing, // clippy::multiple_crate_versions, // clippy::multiple_inherent_impl, // clippy::missing_const_for_fn, clippy::cast_lossless, clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_precision_loss, clippy::cast_sign_loss, clippy::checked_conversions, clippy::decimal_literal_representation, clippy::doc_markdown, clippy::empty_enum, clippy::explicit_into_iter_loop, clippy::explicit_iter_loop, clippy::expl_impl_clone_on_copy, clippy::fallible_impl_from, clippy::filter_map, clippy::filter_map_next, clippy::find_map, clippy::float_arithmetic, clippy::get_unwrap, clippy::if_not_else, clippy::inline_always, clippy::invalid_upcast_comparisons, clippy::items_after_statements, clippy::map_flatten, clippy::match_same_arms, clippy::maybe_infinite_iter, clippy::mem_forget, clippy::module_name_repetitions, clippy::mut_mut, clippy::needless_borrow, clippy::needless_continue, clippy::needless_pass_by_value, clippy::non_ascii_literal, clippy::option_map_unwrap_or, clippy::option_map_unwrap_or_else, clippy::path_buf_push_overwrite, clippy::print_stdout, clippy::pub_enum_variant_names, clippy::redundant_closure_for_method_calls, clippy::result_map_unwrap_or_else, clippy::shadow_reuse, clippy::shadow_same, clippy::shadow_unrelated, clippy::single_match_else, clippy::string_add, clippy::string_add_assign, clippy::type_repetition_in_bounds, clippy::unicode_not_nfc, clippy::unimplemented, clippy::unseparated_literal_suffix, clippy::used_underscore_binding, clippy::wildcard_dependencies, clippy::wildcard_enum_match_arm, clippy::wrong_pub_self_convention, )] const DEFAULT_FLUSH_TIMEOUT: Duration = Duration::from_secs(10); mod connect; mod creds_utils; mod inbound; mod outbound; mod parser; mod secure_wipe; mod shared_state; #[cfg(feature = "fault_injection")] mod fault_injection; #[cfg(feature = "fault_injection")] use fault_injection::{inject_delay, inject_io_failure}; #[cfg(not(feature = "fault_injection"))] fn inject_delay() {} #[cfg(not(feature = "fault_injection"))] fn inject_io_failure() -> io::Result<()> { Ok(()) } /// Functionality relating to TLS configuration pub mod tls; /// Functionality relating to subscribing to a /// subject. pub mod subscription; use std::{ convert::TryFrom, fmt, io::{self, Error, ErrorKind}, marker::PhantomData, path::Path, sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, time::{Duration, Instant}, }; use rand::{thread_rng, Rng}; use serde::Deserialize; pub use subscription::Subscription; #[doc(hidden)] pub use connect::ConnectInfo; use { inbound::{Inbound, Reader}, outbound::{Outbound, Writer}, secure_wipe::{SecureString, SecureVec}, shared_state::{parse_server_addresses, Server, SharedState, SubscriptionState}, tls::{split_tls, TlsReader, TlsWriter}, }; const VERSION: &str = env!("CARGO_PKG_VERSION"); const LANG: &str = "rust"; /// Information sent by the server back to this client /// during initial connection, and possibly again later. #[derive(Deserialize, Debug, Clone)] pub struct ServerInfo { /// The unique identifier of the NATS server. pub server_id: String, /// Generated Server Name. #[serde(default)] pub server_name: String, /// The host specified in the cluster parameter/options. pub host: String, /// The port number specified in the cluster parameter/options. pub port: i16, /// The version of the NATS server. pub version: String, /// If this is set, then the server should try to authenticate upon connect. #[serde(default)] pub auth_required: bool, /// If this is set, then the server must authenticate using TLS. #[serde(default)] pub tls_required: bool, /// Maximum payload size that the server will accept. pub max_payload: i32, /// The protocol version in use. pub proto: i8, /// The server-assigned client ID. This may change during reconnection. pub client_id: u64, /// The version of golang the NATS server was built with. pub go: String, #[serde(default)] /// The nonce used for nkeys. pub nonce: String, /// A list of server urls that a client can connect to. #[serde(default)] pub connect_urls: Vec<String>, /// The client IP as known by the server. #[serde(default)] pub client_ip: String, } impl ServerInfo { pub(crate) fn learned_servers(&self) -> Vec<Server> { parse_server_addresses(&self.connect_urls) } } pub(crate) struct ReconnectDelayCallback(Box<dyn Fn(usize) -> Duration + Send + Sync + 'static>); #[derive(Default)] pub(crate) struct Callback(Option<Box<dyn Fn() + Send + Sync + 'static>>); impl fmt::Debug for Callback { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.debug_map() .entry( &"callback", if self.0.is_some() { &"set" } else { &"unset" }, ) .finish() } } mod options_typestate { /// `ConnectionOptions` typestate indicating /// that there has not yet been /// any auth-related configuration /// provided yet. #[derive(Debug, Copy, Clone, Default)] pub struct NoAuth; /// `ConnectionOptions` typestate indicating /// that auth-related configuration /// has been provided, and may not /// be provided again. #[derive(Debug, Copy, Clone)] pub struct Authenticated; /// `ConnectionOptions` typestate indicating that /// this `ConnectionOptions` has been used to create /// a `Connection` and may not be changed. #[derive(Debug, Copy, Clone)] pub struct Finalized; } type FinalizedOptions = ConnectionOptions<options_typestate::Finalized>; /// A configuration object for a NATS connection. pub struct ConnectionOptions<TypeState> { typestate: PhantomData<TypeState>, auth: AuthStyle, name: Option<String>, no_echo: bool, max_reconnects: Option<usize>, reconnect_buffer_size: usize, disconnect_callback: Callback, reconnect_callback: Callback, reconnect_delay_callback: ReconnectDelayCallback, close_callback: Callback, tls_connector: Option<tls::TlsConnector>, tls_required: bool, } fn default_reconnect_delay_callback(reconnects: usize) -> Duration { if reconnects > 0 { let log_2_four_seconds_in_ms = 12_u32; let truncated_exponent = std::cmp::min( log_2_four_seconds_in_ms, u32::try_from(std::cmp::min(u32::max_value() as usize, reconnects)).unwrap(), ); let jitter = thread_rng().gen_range(0, 1000); Duration::from_millis(jitter + 2_u64.checked_pow(truncated_exponent).unwrap()) } else { Duration::from_millis(0) } } impl Default for ConnectionOptions<options_typestate::NoAuth> { fn default() -> ConnectionOptions<options_typestate::NoAuth> { ConnectionOptions { typestate: PhantomData, auth: AuthStyle::None, name: None, no_echo: false, reconnect_buffer_size: 8 * 1024 * 1024, max_reconnects: Some(60), disconnect_callback: Callback(None), reconnect_callback: Callback(None), reconnect_delay_callback: ReconnectDelayCallback(Box::new( default_reconnect_delay_callback, )), close_callback: Callback(None), tls_connector: None, tls_required: false, } } } impl<T> fmt::Debug for ConnectionOptions<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.debug_map() .entry(&"auth", &self.auth) .entry(&"name", &self.name) .entry(&"no_echo", &self.no_echo) .entry(&"reconnect_buffer_size", &self.reconnect_buffer_size) .entry(&"max_reconnects", &self.max_reconnects) .entry(&"disconnect_callback", &self.disconnect_callback) .entry(&"reconnect_callback", &self.reconnect_callback) .entry(&"reconnect_delay_callback", &"set") .entry(&"close_callback", &self.close_callback) .entry( &"tls_connector", if self.tls_connector.is_some() { &"set" } else { &"unset" }, ) .entry(&"tls_required", &self.tls_required) .finish() } } impl ConnectionOptions<options_typestate::NoAuth> { /// `ConnectionOptions` for establishing a new NATS `Connection`. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// let options = nats::ConnectionOptions::new(); /// let nc = options.connect("demo.nats.io")?; /// # Ok(()) /// # } /// ``` pub fn new() -> ConnectionOptions<options_typestate::NoAuth> { ConnectionOptions::default() } /// Authenticate with NATS using a token. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// let nc = nats::ConnectionOptions::new() /// .with_token("t0k3n!") /// .connect("demo.nats.io")?; /// # Ok(()) /// # } /// ``` pub fn with_token(self, token: &str) -> ConnectionOptions<options_typestate::Authenticated> { ConnectionOptions { auth: AuthStyle::Token(token.to_string()), typestate: PhantomData, no_echo: self.no_echo, name: self.name, close_callback: self.close_callback, disconnect_callback: self.disconnect_callback, reconnect_callback: self.reconnect_callback, reconnect_delay_callback: self.reconnect_delay_callback, reconnect_buffer_size: self.reconnect_buffer_size, max_reconnects: self.max_reconnects, tls_connector: self.tls_connector, tls_required: self.tls_required, } } /// Authenticate with NATS using a username and password. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// let nc = nats::ConnectionOptions::new() /// .with_user_pass("derek", "s3cr3t!") /// .connect("demo.nats.io")?; /// # Ok(()) /// # } /// ``` pub fn with_user_pass( self, user: &str, password: &str, ) -> ConnectionOptions<options_typestate::Authenticated> { ConnectionOptions { auth: AuthStyle::UserPass(user.to_string(), password.to_string()), typestate: PhantomData, no_echo: self.no_echo, name: self.name, reconnect_buffer_size: self.reconnect_buffer_size, close_callback: self.close_callback, disconnect_callback: self.disconnect_callback, reconnect_callback: self.reconnect_callback, reconnect_delay_callback: self.reconnect_delay_callback, max_reconnects: self.max_reconnects, tls_connector: self.tls_connector, tls_required: self.tls_required, } } /// Authenticate with NATS using a credentials file /// /// # Example /// ```no_run /// # fn main() -> std::io::Result<()> { /// let nc = nats::ConnectionOptions::new() /// .with_credentials("path/to/my.creds") /// .connect("connect.ngs.global")?; /// # Ok(()) /// # } /// ``` pub fn with_credentials( self, path: impl AsRef<Path>, ) -> ConnectionOptions<options_typestate::Authenticated> { ConnectionOptions { auth: AuthStyle::Credentials { jwt_cb: { let path = path.as_ref().to_owned(); Arc::new(move || creds_utils::user_jwt_from_file(&path)) }, sig_cb: { let path = path.as_ref().to_owned(); Arc::new(move |nonce| creds_utils::sign_nonce_with_file(nonce, &path)) }, }, typestate: PhantomData, no_echo: self.no_echo, name: self.name, reconnect_buffer_size: self.reconnect_buffer_size, disconnect_callback: self.disconnect_callback, reconnect_callback: self.reconnect_callback, reconnect_delay_callback: self.reconnect_delay_callback, max_reconnects: self.max_reconnects, close_callback: self.close_callback, tls_connector: self.tls_connector, tls_required: self.tls_required, } } } impl<TypeState> ConnectionOptions<TypeState> { /// Add a name option to this configuration. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// let nc = nats::ConnectionOptions::new() /// .with_name("My App") /// .connect("demo.nats.io")?; /// # Ok(()) /// # } /// ``` pub fn with_name(mut self, name: &str) -> ConnectionOptions<TypeState> { self.name = Some(name.to_string()); self } /// Select option to not deliver messages that we have published. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// let nc = nats::ConnectionOptions::new() /// .no_echo() /// .connect("demo.nats.io")?; /// # Ok(()) /// # } /// ``` pub const fn no_echo(mut self) -> ConnectionOptions<TypeState> { self.no_echo = true; self } /// Set the maximum number of reconnect attempts. /// If no servers remain that are under this threshold, /// all servers will still be attempted. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// let nc = nats::ConnectionOptions::new() /// .max_reconnects(Some(3)) /// .connect("demo.nats.io")?; /// # Ok(()) /// # } /// ``` pub const fn max_reconnects( mut self, max_reconnects: Option<usize>, ) -> ConnectionOptions<TypeState> { self.max_reconnects = max_reconnects; self } /// Set the maximum amount of bytes to buffer /// when accepting outgoing traffic in disconnected /// mode. /// /// The default value is 8mb. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// let nc = nats::ConnectionOptions::new() /// .reconnect_buffer_size(64 * 1024) /// .connect("demo.nats.io")?; /// # Ok(()) /// # } /// ``` pub const fn reconnect_buffer_size( mut self, reconnect_buffer_size: usize, ) -> ConnectionOptions<TypeState> { self.reconnect_buffer_size = reconnect_buffer_size; self } /// Establish a `Connection` with a NATS server. /// /// Multiple servers may be specified by separating /// them with commas. /// /// # Example /// /// ``` /// # fn main() -> std::io::Result<()> { /// let options = nats::ConnectionOptions::new(); /// let nc = options.connect("demo.nats.io")?; /// # Ok(()) /// # } /// ``` /// /// In the below case, the second server is configured /// to use TLS but the first one is not. Using the /// `tls_required` method can ensure that all /// servers are connected to with TLS, if that is /// your intention. /// /// /// ``` /// # fn main() -> std::io::Result<()> { /// let options = nats::ConnectionOptions::new(); /// let nc = options.connect("nats://demo.nats.io:4222,tls://demo.nats.io:4443")?; /// # Ok(()) /// # } /// ``` pub fn connect(self, nats_url: &str) -> io::Result<Connection> { let options = ConnectionOptions { auth: self.auth, no_echo: self.no_echo, name: self.name, reconnect_buffer_size: self.reconnect_buffer_size, max_reconnects: self.max_reconnects, disconnect_callback: self.disconnect_callback, reconnect_callback: self.reconnect_callback, reconnect_delay_callback: self.reconnect_delay_callback, close_callback: self.close_callback, tls_connector: self.tls_connector, tls_required: self.tls_required, // move options into the Finalized state by setting // `typestate` to `PhantomData<Finalized>` typestate: PhantomData, }; let shared_state = SharedState::connect(options, nats_url)?; let conn = Connection { sid: Arc::new(AtomicUsize::new(1)), shutdown_dropper: Arc::new(ShutdownDropper { shared_state: shared_state.clone(), }), shared_state, }; Ok(conn) } /// Set a callback to be executed when connectivity to /// a server has been lost. pub fn set_disconnect_callback<F>(mut self, cb: F) -> Self where F: Fn() + Send + Sync + 'static, { self.disconnect_callback = Callback(Some(Box::new(cb))); self } /// Set a callback to be executed when connectivity to a /// server has been established. pub fn set_reconnect_callback<F>(mut self, cb: F) -> Self where F: Fn() + Send + Sync + 'static, { self.disconnect_callback = Callback(Some(Box::new(cb))); self } /// Set a callback to be executed when the client has been /// closed due to exhausting reconnect retries to known servers /// or by completing a drain request. pub fn set_close_callback<F>(mut self, cb: F) -> Self where F: Fn() + Send + Sync + 'static, { self.close_callback = Callback(Some(Box::new(cb))); self } /// Set a callback to be executed for calculating the backoff duration /// to wait before a server reconnection attempt. /// /// The function takes the number of reconnects as an argument /// and returns the `Duration` that should be waited before /// making the next connection attempt. /// /// It is recommended that some random jitter is added to /// your returned `Duration`. pub fn set_reconnect_delay_callback<F>(mut self, cb: F) -> Self where F: Fn(usize) -> Duration + Send + Sync + 'static, { self.reconnect_delay_callback = ReconnectDelayCallback(Box::new(cb)); self } /// Setting this requires that TLS be set for all server connections. /// /// If you only want to use TLS for some server connections, you may /// declare them separately in the connect string by prefixing them /// with `tls://host:port` instead of `nats://host:port`. /// /// If you want to use a particular TLS configuration, see /// the `nats::tls::tls_connector` method and the /// `nats::ConnectionOptions::tls_connector` method below /// to apply the desired configuration to all server connections. /// /// # Examples /// ```no_run /// # fn main() -> std::io::Result<()> { /// /// let nc = nats::ConnectionOptions::new() /// .tls_required(true) /// .connect("tls://demo.nats.io:4443")?; /// # Ok(()) /// # } /// ``` pub const fn tls_required(mut self, tls_required: bool) -> Self { self.tls_required = tls_required; self } /// Allows a particular TLS configuration to be set /// for upgrading TCP connections to TLS connections. /// /// Note that this also enforces that TLS will be /// enabled for all connections to all servers. /// /// # Examples /// ```no_run /// # fn main() -> Result<(), Box<dyn std::error::Error>> { /// let tls_connector = nats::tls::builder() /// .identity(nats::tls::Identity::from_pkcs12(b"der_bytes", "my_password")?) /// .add_root_certificate(nats::tls::Certificate::from_pem(b"my_pem_bytes")?) /// .build()?; /// /// let nc = nats::ConnectionOptions::new() /// .tls_connector(tls_connector) /// .connect("tls://demo.nats.io:4443")?; /// # Ok(()) /// # } /// ``` pub fn tls_connector(mut self, connector: tls::TlsConnector) -> Self { self.tls_connector = Some(connector); self.tls_required = true; self } } // This type exists to hold a reference count // for all high-level user-controlled structures. // Once all of the user structures drop, // the background IO system should flush // everything and shut down. #[derive(Debug)] pub(crate) struct ShutdownDropper { shared_state: Arc<SharedState>, } impl Drop for ShutdownDropper { fn drop(&mut self) { self.shared_state.close(); inject_delay(); if let Some(mut threads) = self.shared_state.threads.lock().take() { let inbound = threads.inbound.take().unwrap(); let outbound = threads.outbound.take().unwrap(); if let Err(error) = inbound.join() { log::error!("error encountered in inbound thread: {:?}", error); } if let Err(error) = outbound.join() { log::error!("error encountered in outbound thread: {:?}", error); } } } } /// A NATS connection. #[derive(Debug, Clone)] pub struct Connection { sid: Arc<AtomicUsize>, shared_state: Arc<SharedState>, // we split the `ShutdownDropper` into // a separate Arc from the `SharedState` // because the `ShutdownDropper` will only // be held by "user-facing" structures, and // the `SharedState` may be held by background // threads that we wish to terminate once // all of the user-held structures are destroyed. shutdown_dropper: Arc<ShutdownDropper>, } #[derive(Clone)] enum AuthStyle { /// Authenticate using a token. Token(String), /// Authenticate using a username and password. UserPass(String, String), /// Authenticate using a `.creds` file. Credentials { /// Securely loads the user JWT. jwt_cb: Arc<dyn Fn() -> io::Result<SecureString> + Send + Sync>, /// Securely loads the nkey and signs the nonce passed as an argument. sig_cb: Arc<dyn Fn(&[u8]) -> io::Result<SecureString> + Send + Sync>, }, /// No authentication. None, } impl fmt::Debug for AuthStyle { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match self { AuthStyle::Token(s) => f.debug_tuple("Token").field(s).finish(), AuthStyle::UserPass(user, pass) => { f.debug_tuple("Token").field(user).field(pass).finish() } AuthStyle::Credentials { .. } => f.debug_struct("Credentials").finish(), AuthStyle::None => f.debug_struct("None").finish(), } } } impl Default for AuthStyle { fn default() -> AuthStyle { AuthStyle::None } } /// Connect to a NATS server at the given url. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// let nc = nats::connect("demo.nats.io")?; /// # Ok(()) /// # } /// ``` pub fn connect(nats_url: &str) -> io::Result<Connection> { ConnectionOptions::new().connect(nats_url) } /// A `Message` that has been published to a NATS `Subject`. #[derive(Debug)] pub struct Message { /// The NATS `Subject` that this `Message` has been published to. pub subject: String, /// The optional reply `Subject` that may be used for sending /// responses when using the request/reply pattern. pub reply: Option<String>, /// The `Message` contents. pub data: Vec<u8>, pub(crate) responder: Option<Arc<SharedState>>, } impl Message { /// Respond to a request message. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// nc.subscribe("help.request")?.with_handler(move |m| { /// m.respond("ans=42")?; Ok(()) /// }); /// # Ok(()) /// # } /// ``` pub fn respond(&self, msg: impl AsRef<[u8]>) -> io::Result<()> { match (&self.responder, &self.reply) { (Some(shared_state), Some(reply)) => { shared_state.outbound.send_response(reply, msg.as_ref()) } (None, None) => Err(Error::new( ErrorKind::InvalidInput, "No reply subject available", )), (Some(_), None) | (None, Some(_)) => unreachable!( "`reply` and `shared_state` should either both be `Some` or both be `None`" ), } } } impl fmt::Display for Message { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut body = format!("[{} bytes]", self.data.len()); if let Ok(str) = std::str::from_utf8(&self.data) { body = str.to_string(); } if let Some(reply) = &self.reply { write!( f, "Message {{\n subject: \"{}\",\n reply: \"{}\",\n data: \"{}\"\n}}", self.subject, reply, body ) } else { write!( f, "Message {{\n subject: \"{}\",\n data: \"{}\"\n}}", self.subject, body ) } } } impl Connection { /// Create a subscription for the given NATS connection. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// let sub = nc.subscribe("foo")?; /// # Ok(()) /// # } /// ``` pub fn subscribe(&self, subject: &str) -> io::Result<Subscription> { self.do_subscribe(subject, None) } /// Create a queue subscription for the given NATS connection. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// let sub = nc.queue_subscribe("foo", "production")?; /// # Ok(()) /// # } /// ``` pub fn queue_subscribe(&self, subject: &str, queue: &str) -> io::Result<Subscription> { self.do_subscribe(subject, Some(queue)) } fn do_subscribe(&self, subject: &str, queue: Option<&str>) -> io::Result<Subscription> { let sid = self.sid.fetch_add(1, Ordering::Relaxed); self.shared_state .outbound .send_sub_msg(subject, queue, sid, &self.shared_state)?; let (sub, recv) = crossbeam_channel::unbounded(); { let mut subs = self.shared_state.subs.write(); subs.insert( sid, SubscriptionState { subject: subject.to_string(), queue: queue.map(ToString::to_string), sender: sub, }, ); } // TODO(dlc) - Should we do a flush and check errors? Ok(Subscription { subject: subject.to_string(), sid, recv, shared_state: self.shared_state.clone(), shutdown_dropper: self.shutdown_dropper.clone(), do_unsub: true, }) } /// Publish a message on the given subject. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// nc.publish("foo", "Hello World!")?; /// # Ok(()) /// # } /// ``` pub fn publish(&self, subject: &str, msg: impl AsRef<[u8]>) -> io::Result<()> { self.shared_state .outbound .send_pub_msg(subject, None, msg.as_ref(), &self.shared_state) } /// Publish a message on the given subject with a reply subject for responses. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// let reply = nc.new_inbox(); /// let rsub = nc.subscribe(&reply)?; /// nc.publish_request("foo", &reply, "Help me!")?; /// # Ok(()) /// # } /// ``` pub fn publish_request( &self, subject: &str, reply: &str, msg: impl AsRef<[u8]>, ) -> io::Result<()> { self.shared_state.outbound.send_pub_msg( subject, Some(reply), msg.as_ref(), &self.shared_state, ) } /// Create a new globally unique inbox which can be used for replies. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// let reply = nc.new_inbox(); /// let rsub = nc.subscribe(&reply)?; /// # Ok(()) /// # } /// ``` pub fn new_inbox(&self) -> String { format!("_INBOX.{}.{}", self.shared_state.id, nuid::next()) } /// Publish a message on the given subject as a request and receive the response. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # nc.subscribe("foo")?.with_handler(move |m| { m.respond("ans=42")?; Ok(()) }); /// let resp = nc.request("foo", "Help me?")?; /// # Ok(()) /// # } /// ``` pub fn request(&self, subject: &str, msg: impl AsRef<[u8]>) -> io::Result<Message> { let reply = self.new_inbox(); let sub = self.subscribe(&reply)?; self.publish_request(subject, &reply, msg)?; match sub.next() { Some(msg) => Ok(msg), None => Err(Error::new(ErrorKind::NotConnected, "No response")), } } /// Publish a message on the given subject as a request and receive the response. /// This call will return after the timeout duration if no response is received. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # nc.subscribe("foo")?.with_handler(move |m| { m.respond("ans=42")?; Ok(()) }); /// let resp = nc.request_timeout("foo", "Help me?", std::time::Duration::from_secs(2))?; /// # Ok(()) /// # } /// ``` pub fn request_timeout( &self, subject: &str, msg: impl AsRef<[u8]>, timeout: Duration, ) -> io::Result<Message> { let reply = self.new_inbox(); let sub = self.subscribe(&reply)?; self.publish_request(subject, &reply, msg)?; match sub.next_timeout(timeout) { Ok(msg) => Ok(msg), Err(_) => Err(Error::new(ErrorKind::TimedOut, "No response")), } } /// Publish a message on the given subject as a request and allow multiple responses. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// # nc.subscribe("foo")?.with_handler(move |m| { m.respond("ans=42")?; Ok(()) }); /// for msg in nc.request_multi("foo", "Help")?.iter().take(1) {} /// # Ok(()) /// # } /// ``` pub fn request_multi(&self, subject: &str, msg: impl AsRef<[u8]>) -> io::Result<Subscription> { let reply = self.new_inbox(); let sub = self.subscribe(&reply)?; self.publish_request(subject, &reply, msg)?; Ok(sub) } /// Flush a NATS connection by sending a `PING` protocol and waiting for the responding `PONG`. /// Will fail with `TimedOut` if the server does not respond with in 10 seconds. /// Will fail with `NotConnected` if the server is not currently connected. /// Will fail with `BrokenPipe` if the connection to the server is lost. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// nc.flush()?; /// # Ok(()) /// # } /// ``` pub fn flush(&self) -> io::Result<()> { self.flush_timeout(DEFAULT_FLUSH_TIMEOUT) } /// Flush a NATS connection by sending a `PING` protocol and waiting for the responding `PONG`. /// Will fail with `TimedOut` if the server takes longer than this duration to respond. /// Will fail with `NotConnected` if the server is not currently connected. /// Will fail with `BrokenPipe` if the connection to the server is lost. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// nc.flush()?; /// # Ok(()) /// # } /// ``` pub fn flush_timeout(&self, duration: Duration) -> io::Result<()> { self.shared_state.flush_timeout(duration) } /// Close a NATS connection. All clones of /// this `Connection` will also be closed, /// as the backing IO threads are shared. /// /// If the client is currently connected /// to a server, the outbound write buffer /// will be flushed in the process of /// shutting down. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// nc.close(); /// # Ok(()) /// # } /// ``` pub fn close(self) { self.shared_state.close() } /// Calculates the round trip time between this client and the server, /// if the server is currently connected. Fails with `TimedOut` if /// the server takes more than 10 seconds to respond. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// println!("server rtt: {:?}", nc.rtt()); /// # Ok(()) /// # } /// ``` pub fn rtt(&self) -> io::Result<Duration> { let start = Instant::now(); self.flush_timeout(DEFAULT_FLUSH_TIMEOUT)?; Ok(start.elapsed()) } /// Returns the client IP as known by the server. /// Supported as of server version 2.1.6. /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// println!("ip: {:?}", nc.client_ip()); /// # Ok(()) /// # } /// ``` pub fn client_ip(&self) -> io::Result<std::net::IpAddr> { let info = self.shared_state.info.read(); if info.client_ip.is_empty() { return Err(Error::new( ErrorKind::Other, &*format!( "client_ip was not provided by the server. \ It is supported on servers above version 2.1.6. \ The server version is {}", info.version ), )); } match info.client_ip.parse() { Ok(addr) => Ok(addr), Err(_) => Err(Error::new( ErrorKind::InvalidData, &*format!( "client_ip provided by the server cannot be parsed. The server provided IP: {}", info.client_ip ), )), } } /// Returns the client ID as known by the most recently connected server. /// /// # Example /// ``` /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// println!("ip: {:?}", nc.client_id()); /// # Ok(()) /// # } /// ``` pub fn client_id(&self) -> u64 { let info = self.shared_state.info.read(); info.client_id } /// Send an unsubscription for all subs then flush the connection, allowing any unprocessed /// messages to be handled by a handler function if one is configured. /// /// After the flush returns, we know that a round-trip to the server has happened after it /// received our unsubscription, so we shut down the subscriber afterwards. /// /// A similar method exists for the `Subscription` struct which will drain /// a single `Subscription` without shutting down the entire connection /// afterward. /// /// # Example /// ``` /// # use std::sync::{Arc, atomic::{AtomicBool, Ordering::SeqCst}}; /// # fn main() -> std::io::Result<()> { /// # let nc = nats::connect("demo.nats.io")?; /// let received = Arc::new(AtomicBool::new(false)); /// let received_2 = received.clone(); /// /// nc.subscribe("test.drain")?.with_handler(move |m| { /// received_2.store(true, SeqCst); /// Ok(()) /// }); /// /// nc.publish("test.drain", "message")?; /// nc.drain()?; /// /// # std::thread::sleep(std::time::Duration::from_secs(1)); /// /// assert!(received.load(SeqCst)); /// /// # Ok(()) /// # } /// ``` pub fn drain(&self) -> io::Result<()> { self.shared_state.drain() } }