async_nats/jetstream/context.rs
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 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
// Copyright 2020-2022 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//! Manage operations on [Context], create/delete/update [Stream]
use crate::error::Error;
use crate::header::{IntoHeaderName, IntoHeaderValue};
use crate::jetstream::account::Account;
use crate::jetstream::publish::PublishAck;
use crate::jetstream::response::Response;
use crate::subject::ToSubject;
use crate::{
header, is_valid_subject, Client, Command, HeaderMap, HeaderValue, Message, StatusCode,
};
use bytes::Bytes;
use futures::future::BoxFuture;
use futures::{Future, StreamExt, TryFutureExt};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{self, json};
use std::borrow::Borrow;
use std::fmt::Display;
use std::future::IntoFuture;
use std::pin::Pin;
use std::str::from_utf8;
use std::task::Poll;
use std::time::Duration;
use tokio::sync::oneshot;
use tracing::debug;
use super::consumer::{self, Consumer, FromConsumer, IntoConsumerConfig};
use super::errors::ErrorCode;
use super::is_valid_name;
use super::kv::{Store, MAX_HISTORY};
use super::object_store::{is_valid_bucket_name, ObjectStore};
use super::stream::{
self, Config, ConsumerError, ConsumerErrorKind, DeleteStatus, DiscardPolicy, External, Info,
Stream,
};
#[cfg(feature = "server_2_10")]
use super::stream::{Compression, ConsumerCreateStrictError, ConsumerUpdateError};
/// A context which can perform jetstream scoped requests.
#[derive(Debug, Clone)]
pub struct Context {
pub(crate) client: Client,
pub(crate) prefix: String,
pub(crate) timeout: Duration,
}
impl Context {
pub(crate) fn new(client: Client) -> Context {
Context {
client,
prefix: "$JS.API".to_string(),
timeout: Duration::from_secs(5),
}
}
pub fn set_timeout(&mut self, timeout: Duration) {
self.timeout = timeout
}
pub(crate) fn with_prefix<T: ToString>(client: Client, prefix: T) -> Context {
Context {
client,
prefix: prefix.to_string(),
timeout: Duration::from_secs(5),
}
}
pub(crate) fn with_domain<T: AsRef<str>>(client: Client, domain: T) -> Context {
Context {
client,
prefix: format!("$JS.{}.API", domain.as_ref()),
timeout: Duration::from_secs(5),
}
}
/// Publishes [jetstream::Message][super::message::Message] to the [Stream] without waiting for
/// acknowledgment from the server that the message has been successfully delivered.
///
/// Acknowledgment future that can be polled is returned instead.
///
/// If the stream does not exist, `no responders` error will be returned.
///
/// # Examples
///
/// Publish, and after each publish, await for acknowledgment.
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let ack = jetstream.publish("events", "data".into()).await?;
/// ack.await?;
/// jetstream.publish("events", "data".into()).await?.await?;
/// # Ok(())
/// # }
/// ```
///
/// Publish and do not wait for the acknowledgment. Await can be deferred to when needed or
/// ignored entirely.
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let first_ack = jetstream.publish("events", "data".into()).await?;
/// let second_ack = jetstream.publish("events", "data".into()).await?;
/// first_ack.await?;
/// second_ack.await?;
/// # Ok(())
/// # }
/// ```
pub async fn publish<S: ToSubject>(
&self,
subject: S,
payload: Bytes,
) -> Result<PublishAckFuture, PublishError> {
self.send_publish(subject, Publish::build().payload(payload))
.await
}
/// Publish a message with headers to a given subject associated with a stream and returns an acknowledgment from
/// the server that the message has been successfully delivered.
///
/// If the stream does not exist, `no responders` error will be returned.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let mut headers = async_nats::HeaderMap::new();
/// headers.append("X-key", "Value");
/// let ack = jetstream
/// .publish_with_headers("events", headers, "data".into())
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn publish_with_headers<S: ToSubject>(
&self,
subject: S,
headers: crate::header::HeaderMap,
payload: Bytes,
) -> Result<PublishAckFuture, PublishError> {
self.send_publish(subject, Publish::build().payload(payload).headers(headers))
.await
}
/// Publish a message built by [Publish] and returns an acknowledgment future.
///
/// If the stream does not exist, `no responders` error will be returned.
///
/// # Examples
///
/// ```no_run
/// # use async_nats::jetstream::context::Publish;
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let ack = jetstream
/// .send_publish(
/// "events",
/// Publish::build().payload("data".into()).message_id("uuid"),
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn send_publish<S: ToSubject>(
&self,
subject: S,
publish: Publish,
) -> Result<PublishAckFuture, PublishError> {
let subject = subject.to_subject();
let (sender, receiver) = oneshot::channel();
let respond = self.client.new_inbox().into();
let send_fut = self
.client
.sender
.send(Command::Request {
subject,
payload: publish.payload,
respond,
headers: publish.headers,
sender,
})
.map_err(|err| PublishError::with_source(PublishErrorKind::Other, err));
tokio::time::timeout(self.timeout, send_fut)
.map_err(|_elapsed| PublishError::new(PublishErrorKind::TimedOut))
.await??;
Ok(PublishAckFuture {
timeout: self.timeout,
subscription: receiver,
})
}
/// Query the server for account information
pub async fn query_account(&self) -> Result<Account, AccountError> {
let response: Response<Account> = self.request("INFO", b"").await?;
match response {
Response::Err { error } => Err(AccountError::new(AccountErrorKind::JetStream(error))),
Response::Ok(account) => Ok(account),
}
}
/// Create a JetStream [Stream] with given config and return a handle to it.
/// That handle can be used to manage and use [Consumer].
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::stream::Config;
/// use async_nats::jetstream::stream::DiscardPolicy;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream
/// .create_stream(Config {
/// name: "events".to_string(),
/// max_messages: 100_000,
/// discard: DiscardPolicy::Old,
/// ..Default::default()
/// })
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn create_stream<S>(
&self,
stream_config: S,
) -> Result<Stream<Info>, CreateStreamError>
where
Config: From<S>,
{
let mut config: Config = stream_config.into();
if config.name.is_empty() {
return Err(CreateStreamError::new(
CreateStreamErrorKind::EmptyStreamName,
));
}
if !is_valid_name(config.name.as_str()) {
return Err(CreateStreamError::new(
CreateStreamErrorKind::InvalidStreamName,
));
}
if let Some(ref mut mirror) = config.mirror {
if let Some(ref mut domain) = mirror.domain {
if mirror.external.is_some() {
return Err(CreateStreamError::new(
CreateStreamErrorKind::DomainAndExternalSet,
));
}
mirror.external = Some(External {
api_prefix: format!("$JS.{domain}.API"),
delivery_prefix: None,
})
}
}
if let Some(ref mut sources) = config.sources {
for source in sources {
if let Some(ref mut domain) = source.domain {
if source.external.is_some() {
return Err(CreateStreamError::new(
CreateStreamErrorKind::DomainAndExternalSet,
));
}
source.external = Some(External {
api_prefix: format!("$JS.{domain}.API"),
delivery_prefix: None,
})
}
}
}
let subject = format!("STREAM.CREATE.{}", config.name);
let response: Response<Info> = self.request(subject, &config).await?;
match response {
Response::Err { error } => Err(error.into()),
Response::Ok(info) => Ok(Stream {
context: self.clone(),
info,
name: config.name,
}),
}
}
/// Checks for [Stream] existence on the server and returns handle to it.
/// That handle can be used to manage and use [Consumer].
/// This variant does not fetch [Stream] info from the server.
/// It means it does not check if the stream actually exists.
/// If you run more operations on few streams, it is better to use [Context::get_stream] instead.
/// If you however run single operations on many streams, this method is more efficient.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.get_stream_no_info("events").await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_stream_no_info<T: AsRef<str>>(
&self,
stream: T,
) -> Result<Stream<()>, GetStreamError> {
let stream = stream.as_ref();
if stream.is_empty() {
return Err(GetStreamError::new(GetStreamErrorKind::EmptyName));
}
if !is_valid_name(stream) {
return Err(GetStreamError::new(GetStreamErrorKind::InvalidStreamName));
}
Ok(Stream {
context: self.clone(),
info: (),
name: stream.to_string(),
})
}
/// Checks for [Stream] existence on the server and returns handle to it.
/// That handle can be used to manage and use [Consumer].
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.get_stream("events").await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_stream<T: AsRef<str>>(&self, stream: T) -> Result<Stream, GetStreamError> {
let stream = stream.as_ref();
if stream.is_empty() {
return Err(GetStreamError::new(GetStreamErrorKind::EmptyName));
}
if !is_valid_name(stream) {
return Err(GetStreamError::new(GetStreamErrorKind::InvalidStreamName));
}
let subject = format!("STREAM.INFO.{stream}");
let request: Response<Info> = self
.request(subject, &())
.await
.map_err(|err| GetStreamError::with_source(GetStreamErrorKind::Request, err))?;
match request {
Response::Err { error } => {
Err(GetStreamError::new(GetStreamErrorKind::JetStream(error)))
}
Response::Ok(info) => Ok(Stream {
context: self.clone(),
info,
name: stream.to_string(),
}),
}
}
/// Create a stream with the given configuration on the server if it is not present. Returns a handle to the stream on the server.
///
/// Note: This does not validate if the Stream on the server is compatible with the configuration passed in.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::stream::Config;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream
/// .get_or_create_stream(Config {
/// name: "events".to_string(),
/// max_messages: 10_000,
/// ..Default::default()
/// })
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_or_create_stream<S>(
&self,
stream_config: S,
) -> Result<Stream, CreateStreamError>
where
S: Into<Config>,
{
let config: Config = stream_config.into();
if config.name.is_empty() {
return Err(CreateStreamError::new(
CreateStreamErrorKind::EmptyStreamName,
));
}
if !is_valid_name(config.name.as_str()) {
return Err(CreateStreamError::new(
CreateStreamErrorKind::InvalidStreamName,
));
}
let subject = format!("STREAM.INFO.{}", config.name);
let request: Response<Info> = self.request(subject, &()).await?;
match request {
Response::Err { error } if error.code() == 404 => self.create_stream(&config).await,
Response::Err { error } => Err(error.into()),
Response::Ok(info) => Ok(Stream {
context: self.clone(),
info,
name: config.name,
}),
}
}
/// Deletes a [Stream] with a given name.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::stream::Config;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream.delete_stream("events").await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete_stream<T: AsRef<str>>(
&self,
stream: T,
) -> Result<DeleteStatus, DeleteStreamError> {
let stream = stream.as_ref();
if stream.is_empty() {
return Err(DeleteStreamError::new(DeleteStreamErrorKind::EmptyName));
}
if !is_valid_name(stream) {
return Err(DeleteStreamError::new(
DeleteStreamErrorKind::InvalidStreamName,
));
}
let subject = format!("STREAM.DELETE.{stream}");
match self
.request(subject, &json!({}))
.await
.map_err(|err| DeleteStreamError::with_source(DeleteStreamErrorKind::Request, err))?
{
Response::Err { error } => Err(DeleteStreamError::new(
DeleteStreamErrorKind::JetStream(error),
)),
Response::Ok(delete_response) => Ok(delete_response),
}
}
/// Updates a [Stream] with a given config. If specific field cannot be updated,
/// error is returned.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::stream::Config;
/// use async_nats::jetstream::stream::DiscardPolicy;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let stream = jetstream
/// .update_stream(&Config {
/// name: "events".to_string(),
/// discard: DiscardPolicy::New,
/// max_messages: 50_000,
/// ..Default::default()
/// })
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn update_stream<S>(&self, config: S) -> Result<Info, UpdateStreamError>
where
S: Borrow<Config>,
{
let config = config.borrow();
if config.name.is_empty() {
return Err(CreateStreamError::new(
CreateStreamErrorKind::EmptyStreamName,
));
}
if !is_valid_name(config.name.as_str()) {
return Err(CreateStreamError::new(
CreateStreamErrorKind::InvalidStreamName,
));
}
let subject = format!("STREAM.UPDATE.{}", config.name);
match self.request(subject, config).await? {
Response::Err { error } => Err(error.into()),
Response::Ok(info) => Ok(info),
}
}
/// Looks up Stream that contains provided subject.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::TryStreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let stream_name = jetstream.stream_by_subject("foo.>");
/// # Ok(())
/// # }
/// ```
pub async fn stream_by_subject<T: Into<String>>(
&self,
subject: T,
) -> Result<String, GetStreamByNameError> {
let subject = subject.into();
if !is_valid_subject(subject.as_str()) {
return Err(GetStreamByNameError::new(
GetStreamByNameErrorKind::InvalidSubject,
));
}
let mut names = StreamNames {
context: self.clone(),
offset: 0,
page_request: None,
streams: Vec::new(),
subject: Some(subject),
done: false,
};
match names.next().await {
Some(name) => match name {
Ok(name) => Ok(name),
Err(err) => Err(GetStreamByNameError::with_source(
GetStreamByNameErrorKind::Request,
err,
)),
},
None => Err(GetStreamByNameError::new(
GetStreamByNameErrorKind::NotFound,
)),
}
}
/// Lists names of all streams for current context.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::TryStreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let mut names = jetstream.stream_names();
/// while let Some(stream) = names.try_next().await? {
/// println!("stream: {}", stream);
/// }
/// # Ok(())
/// # }
/// ```
pub fn stream_names(&self) -> StreamNames {
StreamNames {
context: self.clone(),
offset: 0,
page_request: None,
streams: Vec::new(),
subject: None,
done: false,
}
}
/// Lists all streams info for current context.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use futures::TryStreamExt;
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let mut streams = jetstream.streams();
/// while let Some(stream) = streams.try_next().await? {
/// println!("stream: {:?}", stream);
/// }
/// # Ok(())
/// # }
/// ```
pub fn streams(&self) -> Streams {
Streams {
context: self.clone(),
offset: 0,
page_request: None,
streams: Vec::new(),
done: false,
}
}
/// Returns an existing key-value bucket.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let kv = jetstream.get_key_value("bucket").await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_key_value<T: Into<String>>(&self, bucket: T) -> Result<Store, KeyValueError> {
let bucket: String = bucket.into();
if !crate::jetstream::kv::is_valid_bucket_name(&bucket) {
return Err(KeyValueError::new(KeyValueErrorKind::InvalidStoreName));
}
let stream_name = format!("KV_{}", &bucket);
let stream = self
.get_stream(stream_name.clone())
.map_err(|err| KeyValueError::with_source(KeyValueErrorKind::GetBucket, err))
.await?;
if stream.info.config.max_messages_per_subject < 1 {
return Err(KeyValueError::new(KeyValueErrorKind::InvalidStoreName));
}
let mut store = Store {
prefix: format!("$KV.{}.", &bucket),
name: bucket,
stream_name,
stream: stream.clone(),
put_prefix: None,
use_jetstream_prefix: self.prefix != "$JS.API",
};
if let Some(ref mirror) = stream.info.config.mirror {
let bucket = mirror.name.trim_start_matches("KV_");
if let Some(ref external) = mirror.external {
if !external.api_prefix.is_empty() {
store.use_jetstream_prefix = false;
store.prefix = format!("$KV.{bucket}.");
store.put_prefix = Some(format!("{}.$KV.{}.", external.api_prefix, bucket));
} else {
store.put_prefix = Some(format!("$KV.{bucket}."));
}
}
};
Ok(store)
}
/// Creates a new key-value bucket.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let kv = jetstream
/// .create_key_value(async_nats::jetstream::kv::Config {
/// bucket: "kv".to_string(),
/// history: 10,
/// ..Default::default()
/// })
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn create_key_value(
&self,
mut config: crate::jetstream::kv::Config,
) -> Result<Store, CreateKeyValueError> {
if !crate::jetstream::kv::is_valid_bucket_name(&config.bucket) {
return Err(CreateKeyValueError::new(
CreateKeyValueErrorKind::InvalidStoreName,
));
}
let history = if config.history > 0 {
if config.history > MAX_HISTORY {
return Err(CreateKeyValueError::new(
CreateKeyValueErrorKind::TooLongHistory,
));
}
config.history
} else {
1
};
let num_replicas = if config.num_replicas == 0 {
1
} else {
config.num_replicas
};
let mut subjects = Vec::new();
if let Some(ref mut mirror) = config.mirror {
if !mirror.name.starts_with("KV_") {
mirror.name = format!("KV_{}", mirror.name);
}
config.mirror_direct = true;
} else if let Some(ref mut sources) = config.sources {
for source in sources {
if !source.name.starts_with("KV_") {
source.name = format!("KV_{}", source.name);
}
}
} else {
subjects = vec![format!("$KV.{}.>", config.bucket)];
}
let stream = self
.create_stream(stream::Config {
name: format!("KV_{}", config.bucket),
description: Some(config.description),
subjects,
max_messages_per_subject: history,
max_bytes: config.max_bytes,
max_age: config.max_age,
max_message_size: config.max_value_size,
storage: config.storage,
republish: config.republish,
allow_rollup: true,
deny_delete: true,
deny_purge: false,
allow_direct: true,
sources: config.sources,
mirror: config.mirror,
num_replicas,
discard: stream::DiscardPolicy::New,
mirror_direct: config.mirror_direct,
#[cfg(feature = "server_2_10")]
compression: if config.compression {
Some(stream::Compression::S2)
} else {
None
},
placement: config.placement,
..Default::default()
})
.await
.map_err(|err| {
if err.kind() == CreateStreamErrorKind::TimedOut {
CreateKeyValueError::with_source(CreateKeyValueErrorKind::TimedOut, err)
} else {
CreateKeyValueError::with_source(CreateKeyValueErrorKind::BucketCreate, err)
}
})?;
let mut store = Store {
prefix: format!("$KV.{}.", &config.bucket),
name: config.bucket,
stream: stream.clone(),
stream_name: stream.info.config.name,
put_prefix: None,
use_jetstream_prefix: self.prefix != "$JS.API",
};
if let Some(ref mirror) = stream.info.config.mirror {
let bucket = mirror.name.trim_start_matches("KV_");
if let Some(ref external) = mirror.external {
if !external.api_prefix.is_empty() {
store.use_jetstream_prefix = false;
store.prefix = format!("$KV.{bucket}.");
store.put_prefix = Some(format!("{}.$KV.{}.", external.api_prefix, bucket));
} else {
store.put_prefix = Some(format!("$KV.{bucket}."));
}
}
};
Ok(store)
}
/// Deletes given key-value bucket.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let kv = jetstream
/// .create_key_value(async_nats::jetstream::kv::Config {
/// bucket: "kv".to_string(),
/// history: 10,
/// ..Default::default()
/// })
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete_key_value<T: AsRef<str>>(
&self,
bucket: T,
) -> Result<DeleteStatus, KeyValueError> {
if !crate::jetstream::kv::is_valid_bucket_name(bucket.as_ref()) {
return Err(KeyValueError::new(KeyValueErrorKind::InvalidStoreName));
}
let stream_name = format!("KV_{}", bucket.as_ref());
self.delete_stream(stream_name)
.map_err(|err| KeyValueError::with_source(KeyValueErrorKind::JetStream, err))
.await
}
// pub async fn update_key_value<C: Borrow<kv::Config>>(&self, config: C) -> Result<(), crate::Error> {
// let config = config.borrow();
// if !crate::jetstream::kv::is_valid_bucket_name(&config.bucket) {
// return Err(Box::new(std::io::Error::new(
// ErrorKind::Other,
// "invalid bucket name",
// )));
// }
// let stream_name = format!("KV_{}", config.bucket);
// self.update_stream()
// .await
// .and_then(|info| Ok(()))
// }
/// Get a [crate::jetstream::consumer::Consumer] straight from [Context], without binding to a [Stream] first.
///
/// It has one less interaction with the server when binding to only one
/// [crate::jetstream::consumer::Consumer].
///
/// # Examples:
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer::PullConsumer;
///
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let consumer: PullConsumer = jetstream
/// .get_consumer_from_stream("consumer", "stream")
/// .await?;
///
/// # Ok(())
/// # }
/// ```
pub async fn get_consumer_from_stream<T, C, S>(
&self,
consumer: C,
stream: S,
) -> Result<Consumer<T>, ConsumerError>
where
T: FromConsumer + IntoConsumerConfig,
S: AsRef<str>,
C: AsRef<str>,
{
if !is_valid_name(stream.as_ref()) {
return Err(ConsumerError::with_source(
ConsumerErrorKind::InvalidName,
"invalid stream",
));
}
if !is_valid_name(consumer.as_ref()) {
return Err(ConsumerError::new(ConsumerErrorKind::InvalidName));
}
let subject = format!("CONSUMER.INFO.{}.{}", stream.as_ref(), consumer.as_ref());
let info: super::consumer::Info = match self.request(subject, &json!({})).await? {
Response::Ok(info) => info,
Response::Err { error } => return Err(error.into()),
};
Ok(Consumer::new(
T::try_from_consumer_config(info.config.clone()).map_err(|err| {
ConsumerError::with_source(ConsumerErrorKind::InvalidConsumerType, err)
})?,
info,
self.clone(),
))
}
/// Delete a [crate::jetstream::consumer::Consumer] straight from [Context], without binding to a [Stream] first.
///
/// It has one less interaction with the server when binding to only one
/// [crate::jetstream::consumer::Consumer].
///
/// # Examples:
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer::PullConsumer;
///
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// jetstream
/// .delete_consumer_from_stream("consumer", "stream")
/// .await?;
///
/// # Ok(())
/// # }
/// ```
pub async fn delete_consumer_from_stream<C: AsRef<str>, S: AsRef<str>>(
&self,
consumer: C,
stream: S,
) -> Result<DeleteStatus, ConsumerError> {
if !is_valid_name(consumer.as_ref()) {
return Err(ConsumerError::new(ConsumerErrorKind::InvalidName));
}
if !is_valid_name(stream.as_ref()) {
return Err(ConsumerError::with_source(
ConsumerErrorKind::Other,
"invalid stream name",
));
}
let subject = format!("CONSUMER.DELETE.{}.{}", stream.as_ref(), consumer.as_ref());
match self.request(subject, &json!({})).await? {
Response::Ok(delete_status) => Ok(delete_status),
Response::Err { error } => Err(error.into()),
}
}
/// Create or update a `Durable` or `Ephemeral` Consumer (if `durable_name` was not provided) and
/// returns the info from the server about created [Consumer] without binding to a [Stream] first.
/// If you want a strict update or create, use [Context::create_consumer_strict_on_stream] or [Context::update_consumer_on_stream].
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let consumer: consumer::PullConsumer = jetstream
/// .create_consumer_on_stream(
/// consumer::pull::Config {
/// durable_name: Some("pull".to_string()),
/// ..Default::default()
/// },
/// "stream",
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn create_consumer_on_stream<C: IntoConsumerConfig + FromConsumer, S: AsRef<str>>(
&self,
config: C,
stream: S,
) -> Result<Consumer<C>, ConsumerError> {
self.create_consumer_on_stream_action(config, stream, ConsumerAction::CreateOrUpdate)
.await
}
/// Update an existing consumer.
/// This call will fail if the consumer does not exist.
/// returns the info from the server about updated [Consumer] without binding to a [Stream] first.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let consumer: consumer::PullConsumer = jetstream
/// .update_consumer_on_stream(
/// consumer::pull::Config {
/// durable_name: Some("pull".to_string()),
/// description: Some("updated pull consumer".to_string()),
/// ..Default::default()
/// },
/// "stream",
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "server_2_10")]
pub async fn update_consumer_on_stream<C: IntoConsumerConfig + FromConsumer, S: AsRef<str>>(
&self,
config: C,
stream: S,
) -> Result<Consumer<C>, ConsumerUpdateError> {
self.create_consumer_on_stream_action(config, stream, ConsumerAction::Update)
.await
.map_err(|err| err.into())
}
/// Create consumer on stream, but only if it does not exist or the existing config is exactly
/// the same.
/// This method will fail if consumer is already present with different config.
/// returns the info from the server about created [Consumer] without binding to a [Stream] first.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// use async_nats::jetstream::consumer;
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let consumer: consumer::PullConsumer = jetstream
/// .create_consumer_strict_on_stream(
/// consumer::pull::Config {
/// durable_name: Some("pull".to_string()),
/// ..Default::default()
/// },
/// "stream",
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "server_2_10")]
pub async fn create_consumer_strict_on_stream<
C: IntoConsumerConfig + FromConsumer,
S: AsRef<str>,
>(
&self,
config: C,
stream: S,
) -> Result<Consumer<C>, ConsumerCreateStrictError> {
self.create_consumer_on_stream_action(config, stream, ConsumerAction::Create)
.await
.map_err(|err| err.into())
}
async fn create_consumer_on_stream_action<
C: IntoConsumerConfig + FromConsumer,
S: AsRef<str>,
>(
&self,
config: C,
stream: S,
action: ConsumerAction,
) -> Result<Consumer<C>, ConsumerError> {
let config = config.into_consumer_config();
let subject = {
let filter = if config.filter_subject.is_empty() {
"".to_string()
} else {
format!(".{}", config.filter_subject)
};
config
.name
.as_ref()
.or(config.durable_name.as_ref())
.map(|name| format!("CONSUMER.CREATE.{}.{}{}", stream.as_ref(), name, filter))
.unwrap_or_else(|| format!("CONSUMER.CREATE.{}", stream.as_ref()))
};
match self
.request(
subject,
&json!({"stream_name": stream.as_ref(), "config": config, "action": action}),
)
.await?
{
Response::Err { error } => Err(ConsumerError::new(ConsumerErrorKind::JetStream(error))),
Response::Ok::<consumer::Info>(info) => Ok(Consumer::new(
FromConsumer::try_from_consumer_config(info.clone().config)
.map_err(|err| ConsumerError::with_source(ConsumerErrorKind::Other, err))?,
info,
self.clone(),
)),
}
}
/// Send a request to the jetstream JSON API.
///
/// This is a low level API used mostly internally, that should be used only in
/// specific cases when this crate API on [Consumer] or [Stream] does not provide needed functionality.
///
/// # Examples
///
/// ```no_run
/// # use async_nats::jetstream::stream::Info;
/// # use async_nats::jetstream::response::Response;
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("localhost:4222").await?;
/// let jetstream = async_nats::jetstream::new(client);
///
/// let response: Response<Info> = jetstream.request("STREAM.INFO.events", &()).await?;
/// # Ok(())
/// # }
/// ```
pub async fn request<S, T, V>(&self, subject: S, payload: &T) -> Result<V, RequestError>
where
S: ToSubject,
T: ?Sized + Serialize,
V: DeserializeOwned,
{
let subject = subject.to_subject();
let request = serde_json::to_vec(&payload)
.map(Bytes::from)
.map_err(|err| RequestError::with_source(RequestErrorKind::Other, err))?;
debug!("JetStream request sent: {:?}", request);
let message = self
.client
.request(format!("{}.{}", self.prefix, subject.as_ref()), request)
.await;
let message = message?;
debug!(
"JetStream request response: {:?}",
from_utf8(&message.payload)
);
let response = serde_json::from_slice(message.payload.as_ref())
.map_err(|err| RequestError::with_source(RequestErrorKind::Other, err))?;
Ok(response)
}
/// Creates a new object store bucket.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let bucket = jetstream
/// .create_object_store(async_nats::jetstream::object_store::Config {
/// bucket: "bucket".to_string(),
/// ..Default::default()
/// })
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn create_object_store(
&self,
config: super::object_store::Config,
) -> Result<super::object_store::ObjectStore, CreateObjectStoreError> {
if !super::object_store::is_valid_bucket_name(&config.bucket) {
return Err(CreateObjectStoreError::new(
CreateKeyValueErrorKind::InvalidStoreName,
));
}
let bucket_name = config.bucket.clone();
let stream_name = format!("OBJ_{bucket_name}");
let chunk_subject = format!("$O.{bucket_name}.C.>");
let meta_subject = format!("$O.{bucket_name}.M.>");
let stream = self
.create_stream(super::stream::Config {
name: stream_name,
description: config.description.clone(),
subjects: vec![chunk_subject, meta_subject],
max_age: config.max_age,
max_bytes: config.max_bytes,
storage: config.storage,
num_replicas: config.num_replicas,
discard: DiscardPolicy::New,
allow_rollup: true,
allow_direct: true,
#[cfg(feature = "server_2_10")]
compression: if config.compression {
Some(Compression::S2)
} else {
None
},
placement: config.placement,
..Default::default()
})
.await
.map_err(|err| {
CreateObjectStoreError::with_source(CreateKeyValueErrorKind::BucketCreate, err)
})?;
Ok(ObjectStore {
name: bucket_name,
stream,
})
}
/// Get an existing object store bucket.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let bucket = jetstream.get_object_store("bucket").await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_object_store<T: AsRef<str>>(
&self,
bucket_name: T,
) -> Result<ObjectStore, ObjectStoreError> {
let bucket_name = bucket_name.as_ref();
if !is_valid_bucket_name(bucket_name) {
return Err(ObjectStoreError::new(
ObjectStoreErrorKind::InvalidBucketName,
));
}
let stream_name = format!("OBJ_{bucket_name}");
let stream = self
.get_stream(stream_name)
.await
.map_err(|err| ObjectStoreError::with_source(ObjectStoreErrorKind::GetStore, err))?;
Ok(ObjectStore {
name: bucket_name.to_string(),
stream,
})
}
/// Delete a object store bucket.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), async_nats::Error> {
/// let client = async_nats::connect("demo.nats.io").await?;
/// let jetstream = async_nats::jetstream::new(client);
/// let bucket = jetstream.delete_object_store("bucket").await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete_object_store<T: AsRef<str>>(
&self,
bucket_name: T,
) -> Result<(), DeleteObjectStore> {
let stream_name = format!("OBJ_{}", bucket_name.as_ref());
self.delete_stream(stream_name)
.await
.map_err(|err| ObjectStoreError::with_source(ObjectStoreErrorKind::GetStore, err))?;
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PublishErrorKind {
StreamNotFound,
WrongLastMessageId,
WrongLastSequence,
TimedOut,
BrokenPipe,
Other,
}
impl Display for PublishErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::StreamNotFound => write!(f, "no stream found for given subject"),
Self::TimedOut => write!(f, "timed out: didn't receive ack in time"),
Self::Other => write!(f, "publish failed"),
Self::BrokenPipe => write!(f, "broken pipe"),
Self::WrongLastMessageId => write!(f, "wrong last message id"),
Self::WrongLastSequence => write!(f, "wrong last sequence"),
}
}
}
pub type PublishError = Error<PublishErrorKind>;
#[derive(Debug)]
pub struct PublishAckFuture {
timeout: Duration,
subscription: oneshot::Receiver<Message>,
}
impl PublishAckFuture {
async fn next_with_timeout(self) -> Result<PublishAck, PublishError> {
let next = tokio::time::timeout(self.timeout, self.subscription)
.await
.map_err(|_| PublishError::new(PublishErrorKind::TimedOut))?;
next.map_or_else(
|_| Err(PublishError::new(PublishErrorKind::BrokenPipe)),
|m| {
if m.status == Some(StatusCode::NO_RESPONDERS) {
return Err(PublishError::new(PublishErrorKind::StreamNotFound));
}
let response = serde_json::from_slice(m.payload.as_ref())
.map_err(|err| PublishError::with_source(PublishErrorKind::Other, err))?;
match response {
Response::Err { error } => match error.error_code() {
ErrorCode::STREAM_WRONG_LAST_MESSAGE_ID => Err(PublishError::with_source(
PublishErrorKind::WrongLastMessageId,
error,
)),
ErrorCode::STREAM_WRONG_LAST_SEQUENCE => Err(PublishError::with_source(
PublishErrorKind::WrongLastSequence,
error,
)),
_ => Err(PublishError::with_source(PublishErrorKind::Other, error)),
},
Response::Ok(publish_ack) => Ok(publish_ack),
}
},
)
}
}
impl IntoFuture for PublishAckFuture {
type Output = Result<PublishAck, PublishError>;
type IntoFuture = Pin<Box<dyn Future<Output = Result<PublishAck, PublishError>> + Send>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(std::future::IntoFuture::into_future(
self.next_with_timeout(),
))
}
}
#[derive(Deserialize, Debug)]
struct StreamPage {
total: usize,
streams: Option<Vec<String>>,
}
#[derive(Deserialize, Debug)]
struct StreamInfoPage {
total: usize,
streams: Option<Vec<super::stream::Info>>,
}
type PageRequest = BoxFuture<'static, Result<StreamPage, RequestError>>;
pub struct StreamNames {
context: Context,
offset: usize,
page_request: Option<PageRequest>,
subject: Option<String>,
streams: Vec<String>,
done: bool,
}
impl futures::Stream for StreamNames {
type Item = Result<String, StreamsError>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
match self.page_request.as_mut() {
Some(page) => match page.try_poll_unpin(cx) {
std::task::Poll::Ready(page) => {
self.page_request = None;
let page = page
.map_err(|err| StreamsError::with_source(StreamsErrorKind::Other, err))?;
if let Some(streams) = page.streams {
self.offset += streams.len();
self.streams = streams;
if self.offset >= page.total {
self.done = true;
}
match self.streams.pop() {
Some(stream) => Poll::Ready(Some(Ok(stream))),
None => Poll::Ready(None),
}
} else {
Poll::Ready(None)
}
}
std::task::Poll::Pending => std::task::Poll::Pending,
},
None => {
if let Some(stream) = self.streams.pop() {
Poll::Ready(Some(Ok(stream)))
} else {
if self.done {
return Poll::Ready(None);
}
let context = self.context.clone();
let offset = self.offset;
let subject = self.subject.clone();
self.page_request = Some(Box::pin(async move {
match context
.request(
"STREAM.NAMES",
&json!({
"offset": offset,
"subject": subject
}),
)
.await?
{
Response::Err { error } => {
Err(RequestError::with_source(RequestErrorKind::Other, error))
}
Response::Ok(page) => Ok(page),
}
}));
self.poll_next(cx)
}
}
}
}
}
type PageInfoRequest = BoxFuture<'static, Result<StreamInfoPage, RequestError>>;
pub type StreamsErrorKind = RequestErrorKind;
pub type StreamsError = RequestError;
pub struct Streams {
context: Context,
offset: usize,
page_request: Option<PageInfoRequest>,
streams: Vec<super::stream::Info>,
done: bool,
}
impl futures::Stream for Streams {
type Item = Result<super::stream::Info, StreamsError>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
match self.page_request.as_mut() {
Some(page) => match page.try_poll_unpin(cx) {
std::task::Poll::Ready(page) => {
self.page_request = None;
let page = page
.map_err(|err| StreamsError::with_source(StreamsErrorKind::Other, err))?;
if let Some(streams) = page.streams {
self.offset += streams.len();
self.streams = streams;
if self.offset >= page.total {
self.done = true;
}
match self.streams.pop() {
Some(stream) => Poll::Ready(Some(Ok(stream))),
None => Poll::Ready(None),
}
} else {
Poll::Ready(None)
}
}
std::task::Poll::Pending => std::task::Poll::Pending,
},
None => {
if let Some(stream) = self.streams.pop() {
Poll::Ready(Some(Ok(stream)))
} else {
if self.done {
return Poll::Ready(None);
}
let context = self.context.clone();
let offset = self.offset;
self.page_request = Some(Box::pin(async move {
match context
.request(
"STREAM.LIST",
&json!({
"offset": offset,
}),
)
.await?
{
Response::Err { error } => {
Err(RequestError::with_source(RequestErrorKind::Other, error))
}
Response::Ok(page) => Ok(page),
}
}));
self.poll_next(cx)
}
}
}
}
}
/// Used for building customized `publish` message.
#[derive(Default, Clone, Debug)]
pub struct Publish {
payload: Bytes,
headers: Option<header::HeaderMap>,
}
impl Publish {
/// Creates a new custom Publish struct to be used with.
pub fn build() -> Self {
Default::default()
}
/// Sets the payload for the message.
pub fn payload(mut self, payload: Bytes) -> Self {
self.payload = payload;
self
}
/// Adds headers to the message.
pub fn headers(mut self, headers: HeaderMap) -> Self {
self.headers = Some(headers);
self
}
/// A shorthand to add a single header.
pub fn header<N: IntoHeaderName, V: IntoHeaderValue>(mut self, name: N, value: V) -> Self {
self.headers
.get_or_insert(header::HeaderMap::new())
.insert(name, value);
self
}
/// Sets the `Nats-Msg-Id` header, that is used by stream deduplicate window.
pub fn message_id<T: AsRef<str>>(self, id: T) -> Self {
self.header(header::NATS_MESSAGE_ID, id.as_ref())
}
/// Sets expected last message ID.
/// It sets the `Nats-Expected-Last-Msg-Id` header with provided value.
pub fn expected_last_message_id<T: AsRef<str>>(self, last_message_id: T) -> Self {
self.header(
header::NATS_EXPECTED_LAST_MESSAGE_ID,
last_message_id.as_ref(),
)
}
/// Sets the last expected stream sequence.
/// It sets the `Nats-Expected-Last-Sequence` header with provided value.
pub fn expected_last_sequence(self, last_sequence: u64) -> Self {
self.header(
header::NATS_EXPECTED_LAST_SEQUENCE,
HeaderValue::from(last_sequence),
)
}
/// Sets the last expected stream sequence for a subject this message will be published to.
/// It sets the `Nats-Expected-Last-Subject-Sequence` header with provided value.
pub fn expected_last_subject_sequence(self, subject_sequence: u64) -> Self {
self.header(
header::NATS_EXPECTED_LAST_SUBJECT_SEQUENCE,
HeaderValue::from(subject_sequence),
)
}
/// Sets the expected stream name.
/// It sets the `Nats-Expected-Stream` header with provided value.
pub fn expected_stream<T: AsRef<str>>(self, stream: T) -> Self {
self.header(
header::NATS_EXPECTED_STREAM,
HeaderValue::from(stream.as_ref()),
)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RequestErrorKind {
NoResponders,
TimedOut,
Other,
}
impl Display for RequestErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TimedOut => write!(f, "timed out"),
Self::Other => write!(f, "request failed"),
Self::NoResponders => write!(f, "requested JetStream resource does not exist"),
}
}
}
pub type RequestError = Error<RequestErrorKind>;
impl From<crate::RequestError> for RequestError {
fn from(error: crate::RequestError) -> Self {
match error.kind() {
crate::RequestErrorKind::TimedOut => {
RequestError::with_source(RequestErrorKind::TimedOut, error)
}
crate::RequestErrorKind::NoResponders => {
RequestError::new(RequestErrorKind::NoResponders)
}
crate::RequestErrorKind::Other => {
RequestError::with_source(RequestErrorKind::Other, error)
}
}
}
}
impl From<super::errors::Error> for RequestError {
fn from(err: super::errors::Error) -> Self {
RequestError::with_source(RequestErrorKind::Other, err)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum CreateStreamErrorKind {
EmptyStreamName,
InvalidStreamName,
DomainAndExternalSet,
JetStreamUnavailable,
JetStream(super::errors::Error),
TimedOut,
Response,
ResponseParse,
}
impl Display for CreateStreamErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::EmptyStreamName => write!(f, "stream name cannot be empty"),
Self::InvalidStreamName => write!(f, "stream name cannot contain `.`, `_`"),
Self::DomainAndExternalSet => write!(f, "domain and external are both set"),
Self::JetStream(err) => write!(f, "jetstream error: {}", err),
Self::TimedOut => write!(f, "jetstream request timed out"),
Self::JetStreamUnavailable => write!(f, "jetstream unavailable"),
Self::ResponseParse => write!(f, "failed to parse server response"),
Self::Response => write!(f, "response error"),
}
}
}
pub type CreateStreamError = Error<CreateStreamErrorKind>;
impl From<super::errors::Error> for CreateStreamError {
fn from(error: super::errors::Error) -> Self {
CreateStreamError::new(CreateStreamErrorKind::JetStream(error))
}
}
impl From<RequestError> for CreateStreamError {
fn from(error: RequestError) -> Self {
match error.kind() {
RequestErrorKind::NoResponders => {
CreateStreamError::new(CreateStreamErrorKind::JetStreamUnavailable)
}
RequestErrorKind::TimedOut => CreateStreamError::new(CreateStreamErrorKind::TimedOut),
RequestErrorKind::Other => {
CreateStreamError::with_source(CreateStreamErrorKind::Response, error)
}
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum GetStreamErrorKind {
EmptyName,
Request,
InvalidStreamName,
JetStream(super::errors::Error),
}
impl Display for GetStreamErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::EmptyName => write!(f, "empty name cannot be empty"),
Self::Request => write!(f, "request error"),
Self::InvalidStreamName => write!(f, "invalid stream name"),
Self::JetStream(err) => write!(f, "jetstream error: {}", err),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum GetStreamByNameErrorKind {
Request,
NotFound,
InvalidSubject,
JetStream(super::errors::Error),
}
impl Display for GetStreamByNameErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Request => write!(f, "request error"),
Self::NotFound => write!(f, "stream not found"),
Self::InvalidSubject => write!(f, "invalid subject"),
Self::JetStream(err) => write!(f, "jetstream error: {}", err),
}
}
}
pub type GetStreamError = Error<GetStreamErrorKind>;
pub type GetStreamByNameError = Error<GetStreamByNameErrorKind>;
pub type UpdateStreamError = CreateStreamError;
pub type UpdateStreamErrorKind = CreateStreamErrorKind;
pub type DeleteStreamError = GetStreamError;
pub type DeleteStreamErrorKind = GetStreamErrorKind;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum KeyValueErrorKind {
InvalidStoreName,
GetBucket,
JetStream,
}
impl Display for KeyValueErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidStoreName => write!(f, "invalid Key Value Store name"),
Self::GetBucket => write!(f, "failed to get the bucket"),
Self::JetStream => write!(f, "JetStream error"),
}
}
}
pub type KeyValueError = Error<KeyValueErrorKind>;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CreateKeyValueErrorKind {
InvalidStoreName,
TooLongHistory,
JetStream,
BucketCreate,
TimedOut,
}
impl Display for CreateKeyValueErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidStoreName => write!(f, "invalid Key Value Store name"),
Self::TooLongHistory => write!(f, "too long history"),
Self::JetStream => write!(f, "JetStream error"),
Self::BucketCreate => write!(f, "bucket creation failed"),
Self::TimedOut => write!(f, "timed out"),
}
}
}
pub type CreateKeyValueError = Error<CreateKeyValueErrorKind>;
pub type CreateObjectStoreError = CreateKeyValueError;
pub type CreateObjectStoreErrorKind = CreateKeyValueErrorKind;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ObjectStoreErrorKind {
InvalidBucketName,
GetStore,
}
impl Display for ObjectStoreErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidBucketName => write!(f, "invalid Object Store bucket name"),
Self::GetStore => write!(f, "failed to get Object Store"),
}
}
}
pub type ObjectStoreError = Error<ObjectStoreErrorKind>;
pub type DeleteObjectStore = ObjectStoreError;
pub type DeleteObjectStoreKind = ObjectStoreErrorKind;
#[derive(Clone, Debug, PartialEq)]
pub enum AccountErrorKind {
TimedOut,
JetStream(super::errors::Error),
JetStreamUnavailable,
Other,
}
impl Display for AccountErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TimedOut => write!(f, "timed out"),
Self::JetStream(err) => write!(f, "JetStream error: {}", err),
Self::Other => write!(f, "error"),
Self::JetStreamUnavailable => write!(f, "JetStream unavailable"),
}
}
}
pub type AccountError = Error<AccountErrorKind>;
impl From<RequestError> for AccountError {
fn from(err: RequestError) -> Self {
match err.kind {
RequestErrorKind::NoResponders => {
AccountError::with_source(AccountErrorKind::JetStreamUnavailable, err)
}
RequestErrorKind::TimedOut => AccountError::new(AccountErrorKind::TimedOut),
RequestErrorKind::Other => AccountError::with_source(AccountErrorKind::Other, err),
}
}
}
#[derive(Clone, Debug, Serialize)]
enum ConsumerAction {
#[serde(rename = "")]
CreateOrUpdate,
#[serde(rename = "create")]
#[cfg(feature = "server_2_10")]
Create,
#[serde(rename = "update")]
#[cfg(feature = "server_2_10")]
Update,
}