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
use std::{borrow::Cow, fmt::Debug, marker::PhantomData, task::Poll};
use async_trait::async_trait;
use futures::{future::BoxFuture, ready, Future, FutureExt};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use transmog::{Format, OwnedDeserializer};
use transmog_pot::Pot;
use crate::{
connection::{self, Connection, Range},
document::{BorrowedDocument, CollectionDocument, KeyId, OwnedDocument, OwnedDocuments},
schema::{CollectionName, Schematic},
Error,
};
/// A namespaced collection of `Document<Self>` items and views.
///
/// ## Deriving this trait
///
/// This trait can be derived instead of manually implemented:
///
/// ```rust
/// use bonsaidb_core::schema::Collection;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize, Default, Collection)]
/// #[collection(name = "MyCollection")]
/// # #[collection(core = bonsaidb_core)]
/// pub struct MyCollection;
/// ```
///
/// If you're publishing a collection for use in multiple projects, consider
/// giving the collection an `authority`, which gives your collection a
/// namespace:
///
/// ```rust
/// use bonsaidb_core::schema::Collection;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize, Default, Collection)]
/// #[collection(name = "MyCollection", authority = "khonsulabs")]
/// # #[collection(core = bonsaidb_core)]
/// pub struct MyCollection;
/// ```
///
/// The list of views can be specified using the `views` parameter:
///
/// ```rust
/// use bonsaidb_core::schema::{Collection, View};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize, Default, Collection)]
/// #[collection(name = "MyCollection", views = [ScoresByRank])]
/// # #[collection(core = bonsaidb_core)]
/// pub struct MyCollection;
///
/// #[derive(Debug, Clone, View)]
/// #[view(collection = MyCollection, key = u32, value = f32, name = "scores-by-rank")]
/// # #[view(core = bonsaidb_core)]
/// pub struct ScoresByRank;
/// #
/// # use bonsaidb_core::{
/// # document::CollectionDocument,
/// # schema::{
/// # CollectionViewSchema, ReduceResult,
/// # ViewMapResult, ViewMappedValue,
/// # },
/// # };
/// # impl CollectionViewSchema for ScoresByRank {
/// # type View = Self;
/// # fn map(
/// # &self,
/// # _document: CollectionDocument<<Self::View as View>::Collection>,
/// # ) -> ViewMapResult<Self::View> {
/// # todo!()
/// # }
/// #
/// # fn reduce(
/// # &self,
/// # _mappings: &[ViewMappedValue<Self::View>],
/// # _rereduce: bool,
/// # ) -> ReduceResult<Self::View> {
/// # todo!()
/// # }
/// # }
/// ```
///
/// ### Specifying a Collection Encryption Key
///
/// By default, encryption will be required if an `encryption_key` is provided:
///
/// ```rust
/// use bonsaidb_core::{document::KeyId, schema::Collection};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize, Default, Collection)]
/// #[collection(name = "MyCollection", encryption_key = Some(KeyId::Master))]
/// # #[collection(core = bonsaidb_core)]
/// pub struct MyCollection;
/// ```
///
/// The `encryption_required` parameter can be provided if you wish to be
/// explicit:
///
/// ```rust
/// use bonsaidb_core::{document::KeyId, schema::Collection};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize, Default, Collection)]
/// #[collection(name = "MyCollection")]
/// #[collection(encryption_key = Some(KeyId::Master), encryption_required)]
/// # #[collection(core = bonsaidb_core)]
/// pub struct MyCollection;
/// ```
///
/// Or, if you wish your collection to be encrypted if its available, but not
/// cause errors when being stored without encryption, you can provide the
/// `encryption_optional` parameter:
///
/// ```rust
/// use bonsaidb_core::{document::KeyId, schema::Collection};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize, Default, Collection)]
/// #[collection(name = "MyCollection")]
/// #[collection(encryption_key = Some(KeyId::Master), encryption_optional)]
/// # #[collection(core = bonsaidb_core)]
/// pub struct MyCollection;
/// ```
///
/// ### Changing the serialization strategy
///
/// BonsaiDb uses [`transmog`](::transmog) to allow customizing serialization
/// formats. To use one of the formats Transmog already supports, add its crate
/// to your Cargo.toml and use it like this example using `transmog_bincode`:
///
/// ```rust
/// use bonsaidb_core::schema::Collection;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize, Default, Collection)]
/// #[collection(name = "MyCollection")]
/// #[collection(serialization = transmog_bincode::Bincode)]
/// # #[collection(core = bonsaidb_core)]
/// pub struct MyCollection;
/// ```
///
/// To manually implement `SerializedCollection` you can pass `None` to
/// `serialization`:
///
/// ```rust
/// use bonsaidb_core::schema::Collection;
///
/// #[derive(Debug, Default, Collection)]
/// #[collection(name = "MyCollection")]
/// #[collection(serialization = None)]
/// # #[collection(core = bonsaidb_core)]
/// pub struct MyCollection;
/// ```
pub trait Collection: Debug + Send + Sync {
/// The `Id` of this collection.
fn collection_name() -> CollectionName;
/// Defines all `View`s in this collection in `schema`.
fn define_views(schema: &mut Schematic) -> Result<(), Error>;
/// If a [`KeyId`] is returned, this collection will be stored encrypted
/// at-rest using the key specified.
#[must_use]
fn encryption_key() -> Option<KeyId> {
None
}
}
/// A collection that knows how to serialize and deserialize documents to an associated type.
///
/// These examples for this type use this basic collection definition:
///
/// ```rust
/// use bonsaidb_core::{
/// schema::{Collection, CollectionName, DefaultSerialization, Schematic},
/// Error,
/// };
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize, Default, Collection)]
/// #[collection(name = "MyCollection")]
/// # #[collection(core = bonsaidb_core)]
/// pub struct MyCollection {
/// pub rank: u32,
/// pub score: f32,
/// }
/// ```
#[async_trait]
pub trait SerializedCollection: Collection {
/// The type of the contents stored in documents in this collection.
type Contents: Send + Sync;
/// The serialization format for this collection.
type Format: OwnedDeserializer<Self::Contents>;
/// Returns the configured instance of [`Self::Format`].
// TODO allow configuration to be passed here, such as max allocation bytes.
fn format() -> Self::Format;
/// Deserialize `data` as `Self::Contents` using this collection's format.
fn deserialize(data: &[u8]) -> Result<Self::Contents, Error> {
Self::format()
.deserialize_owned(data)
.map_err(|err| crate::Error::Serialization(err.to_string()))
}
/// Serialize `item` using this collection's format.
fn serialize(item: &Self::Contents) -> Result<Vec<u8>, Error> {
Self::format()
.serialize(item)
.map_err(|err| crate::Error::Serialization(err.to_string()))
}
/// Gets a [`CollectionDocument`] with `id` from `connection`.
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// if let Some(doc) = MyCollection::get(42, &db).await? {
/// println!(
/// "Retrieved revision {} with deserialized contents: {:?}",
/// doc.header.revision, doc.contents
/// );
/// }
/// # Ok(())
/// # })
/// # }
/// ```
async fn get<C: Connection>(
id: u64,
connection: &C,
) -> Result<Option<CollectionDocument<Self>>, Error>
where
Self: Sized,
{
let possible_doc = connection.get::<Self>(id).await?;
Ok(possible_doc.as_ref().map(TryInto::try_into).transpose()?)
}
/// Retrieves all documents matching `ids`. Documents that are not found
/// are not returned, but no error will be generated.
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// for doc in MyCollection::get_multiple(&[42, 43], &db).await? {
/// println!(
/// "Retrieved #{} with deserialized contents: {:?}",
/// doc.header.id, doc.contents
/// );
/// }
/// # Ok(())
/// # })
/// # }
/// ```
async fn get_multiple<C: Connection>(
ids: &[u64],
connection: &C,
) -> Result<Vec<CollectionDocument<Self>>, Error>
where
Self: Sized,
{
connection
.collection::<Self>()
.get_multiple(ids)
.await
.and_then(|docs| docs.collection_documents())
}
/// Retrieves all documents matching the range of `ids`.
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// for doc in MyCollection::list(42.., &db).descending().limit(20).await? {
/// println!(
/// "Retrieved #{} with deserialized contents: {:?}",
/// doc.header.id, doc.contents
/// );
/// }
/// # Ok(())
/// # })
/// # }
/// ```
fn list<R: Into<Range<u64>>, C: Connection>(ids: R, connection: &'_ C) -> List<'_, C, Self>
where
Self: Sized,
{
List(connection::List::new(
connection::PossiblyOwned::Owned(connection.collection::<Self>()),
ids.into(),
))
}
/// Retrieves all documents.
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// for doc in MyCollection::all(&db).await? {
/// println!(
/// "Retrieved #{} with deserialized contents: {:?}",
/// doc.header.id, doc.contents
/// );
/// }
/// # Ok(())
/// # })
/// # }
/// ```
fn all<C: Connection>(connection: &C) -> List<'_, C, Self>
where
Self: Sized,
{
List(connection::List::new(
connection::PossiblyOwned::Owned(connection.collection::<Self>()),
Range::from(..),
))
}
/// Pushes this value into the collection, returning the created document.
/// This function is useful when `Self != Self::Contents`.
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let document = MyCollection::push(MyCollection::default(), &db).await?;
/// println!(
/// "Inserted {:?} with id {} with revision {}",
/// document.contents, document.header.id, document.header.revision
/// );
/// # Ok(())
/// # })
/// # }
/// ```
async fn push<Cn: Connection>(
contents: Self::Contents,
connection: &Cn,
) -> Result<CollectionDocument<Self>, InsertError<Self::Contents>>
where
Self: Sized + 'static,
Self::Contents: 'async_trait,
{
let header = match connection.collection::<Self>().push(&contents).await {
Ok(header) => header,
Err(error) => return Err(InsertError { contents, error }),
};
Ok(CollectionDocument { header, contents })
}
/// Pushes this value into the collection, returning the created document.
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let document = MyCollection::default().push_into(&db).await?;
/// println!(
/// "Inserted {:?} with id {} with revision {}",
/// document.contents, document.header.id, document.header.revision
/// );
/// # Ok(())
/// # })
/// # }
/// ```
async fn push_into<Cn: Connection>(
self,
connection: &Cn,
) -> Result<CollectionDocument<Self>, InsertError<Self>>
where
Self: SerializedCollection<Contents = Self> + Sized + 'static,
{
Self::push(self, connection).await
}
/// Inserts this value into the collection with the specified id, returning
/// the created document.
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let document = MyCollection::insert(42, MyCollection::default(), &db).await?;
/// assert_eq!(document.header.id, 42);
/// println!(
/// "Inserted {:?} with revision {}",
/// document.contents, document.header.revision
/// );
/// # Ok(())
/// # })
/// # }
/// ```
async fn insert<Cn: Connection>(
id: u64,
contents: Self::Contents,
connection: &Cn,
) -> Result<CollectionDocument<Self>, InsertError<Self::Contents>>
where
Self: Sized + 'static,
Self::Contents: 'async_trait,
{
let header = match connection.collection::<Self>().insert(id, &contents).await {
Ok(header) => header,
Err(error) => return Err(InsertError { contents, error }),
};
Ok(CollectionDocument { header, contents })
}
/// Inserts this value into the collection with the given `id`, returning
/// the created document.
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let document = MyCollection::default().insert_into(42, &db).await?;
/// assert_eq!(document.header.id, 42);
/// println!(
/// "Inserted {:?} with revision {}",
/// document.contents, document.header.revision
/// );
/// # Ok(())
/// # })
/// # }
/// ```
async fn insert_into<Cn: Connection>(
self,
id: u64,
connection: &Cn,
) -> Result<CollectionDocument<Self>, InsertError<Self>>
where
Self: SerializedCollection<Contents = Self> + Sized + 'static,
{
Self::insert(id, self, connection).await
}
}
/// A convenience trait for easily storing Serde-compatible types in documents.
pub trait DefaultSerialization: Collection {}
impl<T> SerializedCollection for T
where
T: DefaultSerialization + Serialize + DeserializeOwned,
{
type Contents = Self;
type Format = Pot;
fn format() -> Self::Format {
Pot::default()
}
}
/// An error from inserting a [`CollectionDocument`].
#[derive(thiserror::Error, Debug)]
#[error("{error}")]
pub struct InsertError<T> {
/// The original value being inserted.
pub contents: T,
/// The error that occurred while inserting.
pub error: Error,
}
/// A collection with a unique name column.
///
/// ## Finding a document by unique name
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// if let Some(doc) = MyCollection::load("unique name", &db).await? {
/// println!(
/// "Retrieved revision {} with deserialized contents: {:?}",
/// doc.header.revision, doc.contents
/// );
/// }
/// # Ok(())
/// # })
/// # }
/// ```
///
/// Load accepts either a string or a u64. This enables building methods that
/// accept either the unique ID or the unique name:
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// if let Some(doc) = MyCollection::load(42, &db).await? {
/// println!(
/// "Retrieved revision {} with deserialized contents: {:?}",
/// doc.header.revision, doc.contents
/// );
/// }
/// # Ok(())
/// # })
/// # }
/// ```
///
/// ## Executing an insert or update
///
/// ```rust
/// # bonsaidb_core::__doctest_prelude!();
/// # fn test_fn<C: Connection>(db: C) -> Result<(), Error> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let upserted = MyCollection::entry("unique name", &db)
/// .update_with(|existing: &mut MyCollection| {
/// existing.rank += 1;
/// })
/// .or_insert_with(MyCollection::default)
/// .await?
/// .unwrap();
/// println!("Rank: {:?}", upserted.contents.rank);
///
/// # Ok(())
/// # })
/// # }
/// ```
#[async_trait]
pub trait NamedCollection: Collection + Unpin {
/// The name view defined for the collection.
type ByNameView: crate::schema::SerializedView<Key = String>;
/// Gets a [`CollectionDocument`] with `id` from `connection`.
async fn load<'name, N: Into<NamedReference<'name>> + Send + Sync, C: Connection>(
id: N,
connection: &C,
) -> Result<Option<CollectionDocument<Self>>, Error>
where
Self: SerializedCollection + Sized + 'static,
{
let possible_doc = Self::load_document(id, connection).await?;
Ok(possible_doc
.as_ref()
.map(CollectionDocument::try_from)
.transpose()?)
}
/// Gets a [`CollectionDocument`] with `id` from `connection`.
fn entry<'connection, 'name, N: Into<NamedReference<'name>> + Send + Sync, C: Connection>(
id: N,
connection: &'connection C,
) -> Entry<'connection, 'name, C, Self, (), ()>
where
Self: SerializedCollection + Sized,
{
let name = id.into();
Entry {
state: EntryState::Pending(Some(EntryBuilder {
name,
connection,
insert: None,
update: None,
retry_limit: 0,
_collection: PhantomData,
})),
}
}
/// Loads a document from this collection by name, if applicable. Return
/// `Ok(None)` if unsupported.
#[allow(unused_variables)]
async fn load_document<'name, N: Into<NamedReference<'name>> + Send + Sync, C: Connection>(
name: N,
connection: &C,
) -> Result<Option<OwnedDocument>, Error>
where
Self: SerializedCollection + Sized,
{
match name.into() {
NamedReference::Id(id) => connection.get::<Self>(id).await,
NamedReference::Name(name) => Ok(connection
.view::<Self::ByNameView>()
.with_key(name.as_ref().to_owned())
.query_with_docs()
.await?
.documents
.into_iter()
.next()
.map(|(_, document)| document)),
}
}
}
/// A reference to a collection that has a unique name view.
#[derive(Clone, PartialEq, Deserialize, Serialize, Debug)]
#[must_use]
pub enum NamedReference<'a> {
/// An entity's name.
Name(Cow<'a, str>),
/// A document id.
Id(u64),
}
impl<'a> From<&'a str> for NamedReference<'a> {
fn from(name: &'a str) -> Self {
Self::Name(Cow::Borrowed(name))
}
}
impl<'a> From<&'a String> for NamedReference<'a> {
fn from(name: &'a String) -> Self {
Self::Name(Cow::Borrowed(name.as_str()))
}
}
impl<'a, 'b, 'c> From<&'b BorrowedDocument<'b>> for NamedReference<'a> {
fn from(doc: &'b BorrowedDocument<'b>) -> Self {
Self::Id(doc.header.id)
}
}
impl<'a, 'c, C> From<&'c CollectionDocument<C>> for NamedReference<'a>
where
C: SerializedCollection,
{
fn from(doc: &'c CollectionDocument<C>) -> Self {
Self::Id(doc.header.id)
}
}
impl<'a> From<String> for NamedReference<'a> {
fn from(name: String) -> Self {
Self::Name(Cow::Owned(name))
}
}
impl<'a> From<u64> for NamedReference<'a> {
fn from(id: u64) -> Self {
Self::Id(id)
}
}
impl<'a> NamedReference<'a> {
/// Converts this reference to an owned reference with a `'static` lifetime.
pub fn into_owned(self) -> NamedReference<'static> {
match self {
Self::Name(name) => NamedReference::Name(match name {
Cow::Owned(string) => Cow::Owned(string),
Cow::Borrowed(borrowed) => Cow::Owned(borrowed.to_owned()),
}),
Self::Id(id) => NamedReference::Id(id),
}
}
/// Returns this reference's id. If the reference is a name, the
/// [`NamedCollection::ByNameView`] is queried for the id.
pub async fn id<Col: NamedCollection, Cn: Connection>(
&self,
connection: &Cn,
) -> Result<Option<u64>, Error> {
match self {
Self::Name(name) => Ok(connection
.view::<Col::ByNameView>()
.with_key(name.as_ref().to_owned())
.query()
.await?
.into_iter()
.next()
.map(|e| e.source.id)),
Self::Id(id) => Ok(Some(*id)),
}
}
}
/// A future that resolves to an entry in a [`NamedCollection`].
#[must_use]
pub struct Entry<'a, 'name, Connection, Col, EI, EU>
where
Col: NamedCollection + SerializedCollection,
EI: EntryInsert<Col>,
EU: EntryUpdate<Col>,
{
state: EntryState<'a, 'name, Connection, Col, EI, EU>,
}
struct EntryBuilder<
'a,
'name,
Connection,
Col,
EI: EntryInsert<Col> + 'a,
EU: EntryUpdate<Col> + 'a,
> where
Col: SerializedCollection,
{
name: NamedReference<'name>,
connection: &'a Connection,
insert: Option<EI>,
update: Option<EU>,
retry_limit: usize,
_collection: PhantomData<Col>,
}
impl<'a, 'name, Connection, Col, EI, EU> Entry<'a, 'name, Connection, Col, EI, EU>
where
Col: NamedCollection + SerializedCollection + 'static + Unpin,
Connection: crate::connection::Connection,
EI: EntryInsert<Col> + 'a + Unpin,
EU: EntryUpdate<Col> + 'a + Unpin,
'name: 'a,
{
async fn execute(
name: NamedReference<'name>,
connection: &'a Connection,
insert: Option<EI>,
update: Option<EU>,
mut retry_limit: usize,
) -> Result<Option<CollectionDocument<Col>>, Error> {
if let Some(mut existing) = Col::load(name, connection).await? {
if let Some(update) = update {
loop {
update.call(&mut existing.contents);
match existing.update(connection).await {
Ok(()) => return Ok(Some(existing)),
Err(Error::DocumentConflict(collection, id)) => {
// Another client has updated the document underneath us.
if retry_limit > 0 {
retry_limit -= 1;
existing = match Col::load(id, connection).await? {
Some(doc) => doc,
// Another client deleted the document before we could reload it.
None => break Ok(None),
}
} else {
break Err(Error::DocumentConflict(collection, id));
}
}
Err(other) => break Err(other),
}
}
} else {
Ok(Some(existing))
}
} else if let Some(insert) = insert {
let new_document = insert.call();
Ok(Some(Col::push(new_document, connection).await?))
} else {
Ok(None)
}
}
fn pending(&mut self) -> &mut EntryBuilder<'a, 'name, Connection, Col, EI, EU> {
match &mut self.state {
EntryState::Pending(pending) => pending.as_mut().unwrap(),
EntryState::Executing(_) => unreachable!(),
}
}
/// If an entry with the key doesn't exist, `cb` will be executed to provide
/// an initial document. This document will be saved before being returned.
pub fn or_insert_with<F: EntryInsert<Col> + 'a + Unpin>(
self,
cb: F,
) -> Entry<'a, 'name, Connection, Col, F, EU> {
Entry {
state: match self.state {
EntryState::Pending(Some(EntryBuilder {
name,
connection,
update,
retry_limit,
..
})) => EntryState::Pending(Some(EntryBuilder {
name,
connection,
insert: Some(cb),
update,
retry_limit,
_collection: PhantomData,
})),
_ => {
unreachable!("attempting to modify an already executing future")
}
},
}
}
/// If an entry with the keys exists, `cb` will be executed with the stored
/// value, allowing an opportunity to update the value. This new value will
/// be saved to the database before returning. If an error occurs during
/// update, `cb` may be invoked multiple times, up to the
/// [`retry_limit`](Self::retry_limit()).
pub fn update_with<F: EntryUpdate<Col> + 'a + Unpin>(
self,
cb: F,
) -> Entry<'a, 'name, Connection, Col, EI, F> {
Entry {
state: match self.state {
EntryState::Pending(Some(EntryBuilder {
name,
connection,
insert,
retry_limit,
..
})) => EntryState::Pending(Some(EntryBuilder {
name,
connection,
insert,
update: Some(cb),
retry_limit,
_collection: PhantomData,
})),
_ => {
unreachable!("attempting to modify an already executing future")
}
},
}
}
/// The number of attempts to attempt updating the document using
/// `update_with` before returning an error.
pub fn retry_limit(mut self, attempts: usize) -> Self {
self.pending().retry_limit = attempts;
self
}
}
pub trait EntryInsert<Col: SerializedCollection>: Send + Unpin {
fn call(self) -> Col::Contents;
}
impl<F, Col> EntryInsert<Col> for F
where
F: FnOnce() -> Col::Contents + Send + Unpin,
Col: SerializedCollection,
{
fn call(self) -> Col::Contents {
self()
}
}
impl<Col> EntryInsert<Col> for ()
where
Col: SerializedCollection,
{
fn call(self) -> Col::Contents {
unreachable!()
}
}
pub trait EntryUpdate<Col>: Send + Unpin
where
Col: SerializedCollection,
{
fn call(&self, doc: &mut Col::Contents);
}
impl<F, Col> EntryUpdate<Col> for F
where
F: Fn(&mut Col::Contents) + Send + Unpin,
Col: NamedCollection + SerializedCollection,
{
fn call(&self, doc: &mut Col::Contents) {
self(doc);
}
}
impl<Col> EntryUpdate<Col> for ()
where
Col: SerializedCollection,
{
fn call(&self, _doc: &mut Col::Contents) {
unreachable!();
}
}
impl<'a, 'name, Conn, Col, EI, EU> Future for Entry<'a, 'name, Conn, Col, EI, EU>
where
Col: NamedCollection + SerializedCollection + 'static,
Conn: Connection,
EI: EntryInsert<Col> + 'a,
EU: EntryUpdate<Col> + 'a,
'name: 'a,
{
type Output = Result<Option<CollectionDocument<Col>>, Error>;
fn poll(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<Self::Output> {
if let Some(EntryBuilder {
name,
connection,
insert,
update,
retry_limit,
..
}) = match &mut self.state {
EntryState::Executing(_) => None,
EntryState::Pending(builder) => builder.take(),
} {
let future = Self::execute(name, connection, insert, update, retry_limit).boxed();
self.state = EntryState::Executing(future);
}
if let EntryState::Executing(future) = &mut self.state {
future.as_mut().poll(cx)
} else {
unreachable!()
}
}
}
enum EntryState<'a, 'name, Connection, Col, EI, EU>
where
Col: NamedCollection + SerializedCollection,
EI: EntryInsert<Col>,
EU: EntryUpdate<Col>,
{
Pending(Option<EntryBuilder<'a, 'name, Connection, Col, EI, EU>>),
Executing(BoxFuture<'a, Result<Option<CollectionDocument<Col>>, Error>>),
}
/// Executes [`Connection::list()`] when awaited. Also offers methods to
/// customize the options for the operation.
#[must_use]
pub struct List<'a, Cn, Cl>(connection::List<'a, Cn, Cl>);
impl<'a, Cn, Cl> List<'a, Cn, Cl> {
/// Lists documents by id in ascending order.
pub fn ascending(mut self) -> Self {
self.0 = self.0.ascending();
self
}
/// Lists documents by id in descending order.
pub fn descending(mut self) -> Self {
self.0 = self.0.descending();
self
}
/// Sets the maximum number of results to return.
pub fn limit(mut self, maximum_results: usize) -> Self {
self.0 = self.0.limit(maximum_results);
self
}
}
impl<'a, Cn, Cl> Future for List<'a, Cn, Cl>
where
Cl: SerializedCollection + Unpin,
Cn: Connection,
{
type Output = Result<Vec<CollectionDocument<Cl>>, Error>;
fn poll(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<Self::Output> {
let result = ready!(self.0.poll_unpin(cx));
Poll::Ready(result.and_then(|docs| docs.collection_documents()))
}
}