Skip to content

Commit

Permalink
add admin db remove
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelvlach committed Dec 12, 2023
1 parent 1532f07 commit d24b5fd
Show file tree
Hide file tree
Showing 12 changed files with 167 additions and 29 deletions.
47 changes: 35 additions & 12 deletions agdb_server/openapi/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,40 @@
]
}
},
"/api/v1/admin/db/remove": {
"post": {
"tags": [
"crate::routes::admin::db"
],
"operationId": "remove",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ServerDatabaseName"
}
}
},
"required": true
},
"responses": {
"204": {
"description": "db removed"
},
"401": {
"description": "unauthorized"
},
"466": {
"description": "db not found"
}
},
"security": [
{
"Token": []
}
]
}
},
"/api/v1/admin/shutdown": {
"get": {
"tags": [
Expand Down Expand Up @@ -359,7 +393,7 @@
"operationId": "list",
"parameters": [
{
"name": "db",
"name": "name",
"in": "path",
"required": true,
"schema": {
Expand Down Expand Up @@ -533,17 +567,6 @@
}
}
},
"DbName": {
"type": "object",
"required": [
"db"
],
"properties": {
"db": {
"type": "string"
}
}
},
"DbType": {
"type": "string",
"enum": [
Expand Down
2 changes: 1 addition & 1 deletion agdb_server/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use utoipa::OpenApi;
paths(
crate::routes::status,
crate::routes::admin::db::list,
crate::routes::admin::db::remove,
crate::routes::admin::user::change_password,
crate::routes::admin::user::create,
crate::routes::admin::user::list,
Expand All @@ -29,7 +30,6 @@ use utoipa::OpenApi;
crate::routes::db::ServerDatabase,
crate::routes::db::ServerDatabaseName,
crate::routes::db::user::DbUser,
crate::routes::db::user::DbName,
crate::routes::db::user::RemoveDbUser,
crate::routes::db::user::DbUserRole,
crate::routes::user::ChangePassword,
Expand Down
4 changes: 3 additions & 1 deletion agdb_server/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ pub(crate) fn app(config: Config, shutdown_sender: Sender<()>, db_pool: DbPool)
shutdown_sender,
};

let admin_db_router_v1 = Router::new().route("/list", routing::get(routes::admin::db::list));
let admin_db_router_v1 = Router::new()
.route("/list", routing::get(routes::admin::db::list))
.route("/remove", routing::post(routes::admin::db::remove));

let admin_user_router_v1 = Router::new()
.route(
Expand Down
29 changes: 29 additions & 0 deletions agdb_server/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,35 @@ impl DbPool {
.try_into()?)
}

pub(crate) fn find_db(&self, db: &str) -> ServerResult<Database> {
Ok(self
.0
.server_db
.get()?
.exec(
&QueryBuilder::select()
.ids(
QueryBuilder::search()
.from("dbs")
.limit(1)
.where_()
.distance(CountComparison::Equal(2))
.and()
.key("name")
.value(Comparison::Equal(db.into()))
.query(),
)
.query(),
)?
.elements
.get(0)
.ok_or(ServerError::new(
ErrorCode::DbNotFound.into(),
&format!("{}: {db}", ErrorCode::DbNotFound.as_str()),
))?
.try_into()?)
}

pub(crate) fn find_db_id(&self, name: &str) -> ServerResult<DbId> {
Ok(self
.db()?
Expand Down
22 changes: 22 additions & 0 deletions agdb_server/src/routes/admin/db.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::db::DbPool;
use crate::routes::db::ServerDatabase;
use crate::routes::db::ServerDatabaseName;
use crate::server_error::ServerResponse;
use crate::user_id::AdminId;
use axum::extract::State;
Expand All @@ -25,3 +26,24 @@ pub(crate) async fn list(
.collect();
Ok((StatusCode::OK, Json(dbs)))
}

#[utoipa::path(post,
path = "/api/v1/admin/db/remove",
request_body = ServerDatabaseName,
security(("Token" = [])),
responses(
(status = 204, description = "db removed"),
(status = 401, description = "unauthorized"),
(status = 466, description = "db not found"),
)
)]
pub(crate) async fn remove(
_admin: AdminId,
State(db_pool): State<DbPool>,
Json(request): Json<ServerDatabaseName>,
) -> ServerResponse {
let db = db_pool.find_db(&request.name)?;
db_pool.remove_db(db)?;

Ok(StatusCode::NO_CONTENT)
}
3 changes: 2 additions & 1 deletion agdb_server/src/routes/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use axum::Json;
use serde::Deserialize;
use serde::Serialize;
use std::fmt::Display;
use utoipa::IntoParams;
use utoipa::ToSchema;

#[derive(Serialize, Deserialize, ToSchema)]
Expand All @@ -27,7 +28,7 @@ pub(crate) struct ServerDatabase {
pub(crate) db_type: DbType,
}

#[derive(Deserialize, ToSchema)]
#[derive(Deserialize, ToSchema, IntoParams)]
pub(crate) struct ServerDatabaseName {
pub(crate) name: String,
}
Expand Down
15 changes: 5 additions & 10 deletions agdb_server/src/routes/db/user.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::db::DbPool;
use crate::routes::db::ServerDatabaseName;
use crate::server_error::ServerResponse;
use crate::user_id::UserId;
use axum::extract::Query;
Expand All @@ -8,7 +9,6 @@ use axum::Json;
use serde::Deserialize;
use serde::Serialize;
use std::fmt::Display;
use utoipa::IntoParams;
use utoipa::ToSchema;

#[derive(Serialize, Deserialize, ToSchema)]
Expand All @@ -26,11 +26,6 @@ pub(crate) struct DbUser {
pub(crate) role: DbUserRole,
}

#[derive(Deserialize, IntoParams, ToSchema)]
pub(crate) struct DbName {
pub(crate) db: String,
}

#[derive(Deserialize, ToSchema)]
pub(crate) struct RemoveDbUser {
pub(crate) database: String,
Expand Down Expand Up @@ -90,7 +85,7 @@ pub(crate) async fn add(
path = "/api/v1/db/user/list",
security(("Token" = [])),
params(
DbName,
ServerDatabaseName,
),
responses(
(status = 200, description = "ok"),
Expand All @@ -101,14 +96,14 @@ pub(crate) async fn add(
pub(crate) async fn list(
user: UserId,
State(db_pool): State<DbPool>,
request: Query<DbName>,
request: Query<ServerDatabaseName>,
) -> ServerResponse<(StatusCode, Json<Vec<DbUser>>)> {
let db = db_pool.find_user_db(user.0, &request.db)?;
let db = db_pool.find_user_db(user.0, &request.name)?;
let users = db_pool
.db_users(db.db_id.unwrap())?
.into_iter()
.map(|(name, role)| DbUser {
database: request.db.clone(),
database: request.name.clone(),
user: name,
role: role.into(),
})
Expand Down
1 change: 1 addition & 0 deletions agdb_server/tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub const DB_USER_REMOVE_URI: &str = "/db/user/remove";
pub const DB_DELETE_URI: &str = "/db/delete";
pub const DB_LIST_URI: &str = "/db/list";
pub const ADMIN_DB_LIST_URI: &str = "/admin/db/list";
pub const ADMIN_DB_REMOVE_URI: &str = "/admin/db/remove";
pub const ADMIN_USER_LIST_URI: &str = "/admin/user/list";
pub const ADMIN_CHANGE_PASSWORD_URI: &str = "/admin/user/change_password";
pub const DB_REMOVE_URI: &str = "/db/remove";
Expand Down
64 changes: 64 additions & 0 deletions agdb_server/tests/routes/admin_db_remove_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use std::path::Path;

use crate::Db;
use crate::TestServer;
use crate::ADMIN_DB_REMOVE_URI;
use crate::DB_LIST_URI;
use crate::NO_TOKEN;
use serde::Serialize;

#[derive(Serialize)]
struct DbName<'a> {
name: &'a str,
}

#[tokio::test]
async fn remove() -> anyhow::Result<()> {
let server = TestServer::new().await?;
let (_, token) = server.init_user().await?;
let db = server.init_db("mapped", &token).await?;
let (status, list) = server.get::<Vec<Db>>(DB_LIST_URI, &token).await?;
assert_eq!(status, 200);
assert!(list?.contains(&Db {
name: db.clone(),
db_type: "mapped".to_string(),
}));
let rem = DbName { name: &db };
assert_eq!(
server
.post(ADMIN_DB_REMOVE_URI, &rem, &server.admin_token)
.await?
.0,
204
);
let (status, list) = server.get::<Vec<Db>>(DB_LIST_URI, &token).await?;
assert_eq!(status, 200);
assert!(list?.is_empty());
assert!(Path::new(&server.dir).join(db).exists());
Ok(())
}

#[tokio::test]
async fn db_not_found() -> anyhow::Result<()> {
let server = TestServer::new().await?;
let db = DbName { name: "some_db" };
assert_eq!(
server
.post(ADMIN_DB_REMOVE_URI, &db, &server.admin_token)
.await?
.0,
466
);
Ok(())
}

#[tokio::test]
async fn no_admin_token() -> anyhow::Result<()> {
let server = TestServer::new().await?;
let db = DbName { name: "some_db" };
assert_eq!(
server.post(ADMIN_DB_REMOVE_URI, &db, NO_TOKEN).await?.0,
401
);
Ok(())
}
2 changes: 1 addition & 1 deletion agdb_server/tests/routes/db_remove_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ struct RemoveDb<'a> {
}

#[tokio::test]
async fn delete() -> anyhow::Result<()> {
async fn remove() -> anyhow::Result<()> {
let server = TestServer::new().await?;
let (_, token) = server.init_user().await?;
let db = server.init_db("mapped", &token).await?;
Expand Down
6 changes: 3 additions & 3 deletions agdb_server/tests/routes/db_user_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async fn list_user() -> anyhow::Result<()> {
let (name, token) = server.init_user().await?;
let db = server.init_db("memory", &token).await?;
let (_, list) = server
.get::<Vec<DbUser>>(&format!("{DB_USER_LIST_URI}?db={}", &db), &token)
.get::<Vec<DbUser>>(&format!("{DB_USER_LIST_URI}?name={}", &db), &token)
.await?;
let expected = vec![DbUser {
database: db,
Expand All @@ -42,7 +42,7 @@ async fn list_users() -> anyhow::Result<()> {
};
assert_eq!(server.post(DB_USER_ADD_URI, &role, &token).await?.0, 201);
let (_, list) = server
.get::<Vec<DbUser>>(&format!("{DB_USER_LIST_URI}?db={}", &db), &other)
.get::<Vec<DbUser>>(&format!("{DB_USER_LIST_URI}?name={}", &db), &other)
.await?;
let mut list = list?;
list.sort();
Expand All @@ -67,7 +67,7 @@ async fn no_token() -> anyhow::Result<()> {
let server = TestServer::new().await?;
assert_eq!(
server
.get::<Vec<DbUser>>(&format!("{DB_USER_LIST_URI}?db=some_db"), NO_TOKEN)
.get::<Vec<DbUser>>(&format!("{DB_USER_LIST_URI}?name=some_db"), NO_TOKEN)
.await?
.0,
401
Expand Down
1 change: 1 addition & 0 deletions agdb_server/tests/routes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod admin_db_list_test;
mod admin_db_remove_test;
mod admin_user_change_password_test;
mod admin_user_create_test;
mod admin_user_list_test;
Expand Down

0 comments on commit d24b5fd

Please sign in to comment.