-
Notifications
You must be signed in to change notification settings - Fork 180
RUST-1478 GridFS upload methods #751
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
use std::{marker::Unpin, sync::atomic::Ordering}; | ||
|
||
use futures_util::{ | ||
io::{AsyncRead, AsyncReadExt}, | ||
stream::TryStreamExt, | ||
}; | ||
|
||
use super::{options::GridFsUploadOptions, Chunk, FilesCollectionDocument, GridFsBucket}; | ||
use crate::{ | ||
bson::{doc, oid::ObjectId, spec::BinarySubtype, Bson, DateTime, Document, RawBinaryRef}, | ||
bson_util::get_int, | ||
error::{ErrorKind, Result}, | ||
index::IndexModel, | ||
options::{FindOneOptions, ReadPreference, SelectionCriteria}, | ||
Collection, | ||
}; | ||
|
||
impl GridFsBucket { | ||
/// Uploads a user file to a GridFS bucket. Bytes are read from `source` and stored in chunks in | ||
/// the bucket's chunks collection. After all the chunks have been uploaded, a corresponding | ||
/// [`FilesCollectionDocument`] is stored in the bucket's files collection. | ||
/// | ||
/// This method generates an [`ObjectId`] for the `files_id` field of the | ||
/// [`FilesCollectionDocument`] and returns it. | ||
pub async fn upload_from_futures_0_3_reader<T>( | ||
&self, | ||
filename: impl AsRef<str>, | ||
source: T, | ||
options: impl Into<Option<GridFsUploadOptions>>, | ||
) -> Result<ObjectId> | ||
where | ||
T: AsyncRead + Unpin, | ||
{ | ||
let id = ObjectId::new(); | ||
self.upload_from_futures_0_3_reader_with_id(id.into(), filename, source, options) | ||
.await?; | ||
Ok(id) | ||
} | ||
|
||
/// Uploads a user file to a GridFS bucket with the given `files_id`. Bytes are read from | ||
/// `source` and stored in chunks in the bucket's chunks collection. After all the chunks have | ||
/// been uploaded, a corresponding [`FilesCollectionDocument`] is stored in the bucket's files | ||
/// collection. | ||
pub async fn upload_from_futures_0_3_reader_with_id<T>( | ||
&self, | ||
files_id: Bson, | ||
filename: impl AsRef<str>, | ||
mut source: T, | ||
options: impl Into<Option<GridFsUploadOptions>>, | ||
) -> Result<()> | ||
where | ||
T: AsyncRead + Unpin, | ||
{ | ||
let options = options.into(); | ||
|
||
self.create_indexes().await?; | ||
|
||
let chunk_size = options | ||
.as_ref() | ||
.and_then(|opts| opts.chunk_size_bytes) | ||
.unwrap_or_else(|| self.chunk_size_bytes()); | ||
let mut length = 0u64; | ||
let mut n = 0; | ||
|
||
let mut buf = vec![0u8; chunk_size as usize]; | ||
loop { | ||
let bytes_read = match source.read(&mut buf).await { | ||
Ok(0) => break, | ||
Ok(n) => n, | ||
Err(error) => { | ||
kmahar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.chunks() | ||
.delete_many(doc! { "files_id": &files_id }, None) | ||
.await?; | ||
return Err(ErrorKind::Io(error.into()).into()); | ||
} | ||
}; | ||
|
||
let chunk = Chunk { | ||
id: ObjectId::new(), | ||
files_id: files_id.clone(), | ||
n, | ||
data: RawBinaryRef { | ||
subtype: BinarySubtype::Generic, | ||
bytes: &buf[..bytes_read], | ||
}, | ||
}; | ||
self.chunks().insert_one(chunk, None).await?; | ||
|
||
length += bytes_read as u64; | ||
n += 1; | ||
} | ||
|
||
let file = FilesCollectionDocument { | ||
id: files_id, | ||
length, | ||
chunk_size, | ||
upload_date: DateTime::now(), | ||
filename: Some(filename.as_ref().to_string()), | ||
metadata: options.and_then(|opts| opts.metadata), | ||
}; | ||
self.files().insert_one(file, None).await?; | ||
|
||
Ok(()) | ||
} | ||
|
||
async fn create_indexes(&self) -> Result<()> { | ||
if !self.inner.created_indexes.load(Ordering::SeqCst) { | ||
let find_options = FindOneOptions::builder() | ||
.selection_criteria(SelectionCriteria::ReadPreference(ReadPreference::Primary)) | ||
.projection(doc! { "_id": 1 }) | ||
.build(); | ||
if self | ||
.files() | ||
.clone_with_type::<Document>() | ||
.find_one(None, find_options) | ||
.await? | ||
.is_none() | ||
{ | ||
Self::create_index(self.files(), doc! { "filename": 1, "uploadDate": 1 }).await?; | ||
Self::create_index(self.chunks(), doc! { "files_id": 1, "n": 1 }).await?; | ||
} | ||
self.inner.created_indexes.store(true, Ordering::SeqCst); | ||
} | ||
|
||
Ok(()) | ||
} | ||
|
||
async fn create_index<T>(coll: &Collection<T>, keys: Document) -> Result<()> { | ||
// From the spec: Drivers MUST check whether the indexes already exist before attempting to | ||
// create them. | ||
let mut indexes = coll.list_indexes(None).await?; | ||
'outer: while let Some(index_model) = indexes.try_next().await? { | ||
if index_model.keys.len() != keys.len() { | ||
continue; | ||
} | ||
// Indexes should be considered equivalent regardless of numeric value type. | ||
// e.g. { "filename": 1, "uploadDate": 1 } is equivalent to | ||
// { "filename": 1.0, "uploadDate": 1.0 } | ||
let number_matches = |key: &str, value: &Bson| { | ||
if let Some(model_value) = index_model.keys.get(key) { | ||
match get_int(value) { | ||
Some(num) => get_int(model_value) == Some(num), | ||
None => model_value == value, | ||
} | ||
} else { | ||
false | ||
} | ||
}; | ||
for (key, value) in keys.iter() { | ||
if !number_matches(key, value) { | ||
continue 'outer; | ||
} | ||
} | ||
return Ok(()); | ||
} | ||
|
||
let index_model = IndexModel::builder().keys(keys).build(); | ||
coll.create_index(index_model, None).await?; | ||
|
||
Ok(()) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same as last PR, docs will be updated/examples will be added when I mark everything public.