Skip to content
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

Improve library listing performance #196

Merged
merged 1 commit into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/api-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ pub enum PublishState {
Public,
}

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone)]
pub struct LibraryMetadata {
pub owner: String,
pub name: String,
Expand Down
15 changes: 15 additions & 0 deletions crates/cloud/src/auth/libraries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,18 @@ pub(crate) async fn try_moderate_libraries(
Err(UserError::PermissionsError)
}
}

#[cfg(test)]
mod test_utils {
use super::*;

impl ListLibraries {
pub(crate) fn test(username: String, visibility: PublishState) -> Self {
Self {
username,
visibility,
_private: (),
}
}
}
}
131 changes: 112 additions & 19 deletions crates/cloud/src/libraries/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,24 +53,26 @@ impl<'a> LibraryActions<'a> {
&self,
ll: &auth::ListLibraries,
) -> Result<Vec<api::LibraryMetadata>, UserError> {
let query = doc! {"owner": &ll.username};
let query = match ll.visibility {
PublishState::Private => doc! {"owner": &ll.username},
_ => doc! {
"owner": &ll.username,
"state": PublishState::Public,
},
};

let options = FindOptions::builder().sort(doc! {"name": 1}).build();
let mut cursor = self
let libraries: Vec<_> = self
.libraries
.find(query, options)
.await
.map_err(InternalError::DatabaseConnectionError)?;

let mut libraries = Vec::new();
while let Some(library) = cursor
.try_next()
.map_err(InternalError::DatabaseConnectionError)?
.try_collect::<Vec<_>>()
.await
.map_err(InternalError::DatabaseConnectionError)?
{
if can_view_library(&ll, &library) {
libraries.push(library.into());
}
}
.into_iter()
.map(|lib| lib.into())
.collect();

Ok(libraries)
}
Expand Down Expand Up @@ -264,17 +266,13 @@ fn is_valid_name(name: &str) -> bool {
LIBRARY_NAME.is_match(name) && !name.is_inappropriate()
}

fn can_view_library(ll: &auth::ListLibraries, library: &Library) -> bool {
match ll.visibility {
PublishState::Private => true,
_ => matches!(library.state, PublishState::Public),
}
}

#[cfg(test)]
mod tests {
use crate::test_utils;

use super::*;
use actix_web::test;
use netsblox_cloud_common::User;

#[test]
async fn test_is_valid_name() {
Expand Down Expand Up @@ -305,4 +303,99 @@ mod tests {
async fn test_ensure_valid_name_weird_symbol() {
assert!(ensure_valid_name("<hola libré>").is_err());
}

#[actix_web::test]
async fn test_list_user_libs_public() {
let user: User = api::NewUser {
username: "user".into(),
email: "user@netsblox.org".into(),
password: None,
group_id: None,
role: None,
}
.into();
let pub1 = Library {
owner: user.username.clone(),
name: "pub1".into(),
notes: "".into(),
blocks: "<blocks/>".into(),
state: api::PublishState::Public,
};
let pub2 = Library {
owner: user.username.clone(),
name: "pub2".into(),
notes: "".into(),
blocks: "<blocks/>".into(),
state: api::PublishState::Public,
};
let private = Library {
owner: user.username.clone(),
name: "priv".into(),
notes: "".into(),
blocks: "<blocks/>".into(),
state: api::PublishState::Private,
};

test_utils::setup()
.with_users(&[user.clone()])
.with_libraries(&[pub1.clone(), pub2.clone(), private])
.run(|app_data| async move {
let actions = app_data.as_library_actions();
let auth_ll =
auth::ListLibraries::test(user.username.clone(), PublishState::Public);

let libraries = actions.list_user_libraries(&auth_ll).await.unwrap();
assert_eq!(libraries.len(), 2);
assert!(libraries.iter().find(|lib| lib.name == pub1.name).is_some());
assert!(libraries.iter().find(|lib| lib.name == pub2.name).is_some());
})
.await;
}

#[actix_web::test]
async fn test_list_user_libs_private() {
let user: User = api::NewUser {
username: "user".into(),
email: "user@netsblox.org".into(),
password: None,
group_id: None,
role: None,
}
.into();
let pub1 = Library {
owner: user.username.clone(),
name: "pub1".into(),
notes: "".into(),
blocks: "<blocks/>".into(),
state: api::PublishState::Public,
};
let pub2 = Library {
owner: user.username.clone(),
name: "pub2".into(),
notes: "".into(),
blocks: "<blocks/>".into(),
state: api::PublishState::Public,
};
let private = Library {
owner: user.username.clone(),
name: "priv".into(),
notes: "".into(),
blocks: "<blocks/>".into(),
state: api::PublishState::Private,
};

test_utils::setup()
.with_users(&[user.clone()])
.with_libraries(&[pub1, pub2, private])
.run(|app_data| async move {
let actions = app_data.as_library_actions();
let auth_ll =
auth::ListLibraries::test(user.username.clone(), PublishState::Private);

let libraries = actions.list_user_libraries(&auth_ll).await.unwrap();
// Should get all the libraries since it has permissions to view private libraries
assert_eq!(libraries.len(), 3);
})
.await;
}
}
17 changes: 16 additions & 1 deletion crates/cloud/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use futures::{future::join_all, Future};
use lazy_static::lazy_static;
use mongodb::{bson::doc, Client};
use netsblox_cloud_common::{
api, AuthorizedServiceHost, BannedAccount, CollaborationInvite, FriendLink, Group, User,
api, AuthorizedServiceHost, BannedAccount, CollaborationInvite, FriendLink, Group, Library,
User,
};

use crate::{
Expand All @@ -27,6 +28,7 @@ pub(crate) fn setup() -> TestSetupBuilder {
users: Vec::new(),
banned_users: Vec::new(),
projects: Vec::new(),
libraries: Vec::new(),
groups: Vec::new(),
clients: Vec::new(),
friends: Vec::new(),
Expand All @@ -40,6 +42,7 @@ pub(crate) struct TestSetupBuilder {
prefix: String,
users: Vec<User>,
projects: Vec<project::ProjectFixture>,
libraries: Vec<Library>,
groups: Vec<Group>,
clients: Vec<network::Client>,
friends: Vec<FriendLink>,
Expand Down Expand Up @@ -70,6 +73,11 @@ impl TestSetupBuilder {
self
}

pub(crate) fn with_libraries(mut self, libraries: &[Library]) -> Self {
self.libraries.extend_from_slice(libraries);
self
}

pub(crate) fn with_collab_invites(mut self, invites: &[CollaborationInvite]) -> Self {
self.collab_invites.extend_from_slice(invites);
self
Expand Down Expand Up @@ -177,6 +185,13 @@ impl TestSetupBuilder {
.await
.unwrap();
}
if !self.libraries.is_empty() {
app_data
.libraries
.insert_many(self.libraries, None)
.await
.unwrap();
}
if !self.users.is_empty() {
app_data.users.insert_many(self.users, None).await.unwrap();
}
Expand Down
Loading