This commit is contained in:
StNicolay 2024-07-31 19:17:59 +03:00
parent ea718be066
commit 32d207a991
Signed by: StNicolay
GPG Key ID: 9693D04DCD962B0D
20 changed files with 113 additions and 79 deletions

View File

@ -0,0 +1,23 @@
{
"db_name": "PostgreSQL",
"query": "SELECT\n EXISTS (\n SELECT\n file_name as name\n FROM\n files\n WHERE\n folder_id = $1\n AND file_name = $2\n UNION\n SELECT\n folder_name as name\n FROM\n folders\n WHERE\n parent_folder_id = $1\n AND folder_name = $2\n )",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "exists",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Uuid",
"Text"
]
},
"nullable": [
null
]
},
"hash": "443854b9fb234840588e0100774d3ab51c4532b14d50e5ca3578fe6311e2017a"
}

View File

@ -1,23 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT EXISTS(SELECT folder_id FROM folders WHERE parent_folder_id = $1 AND folder_name = $2)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "exists",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Uuid",
"Text"
]
},
"nullable": [
null
]
},
"hash": "cd3591c61f3cc036158d8d55ec22a04adaf62ec4b05ba73da9253128b7bbb5b1"
}

37
Cargo.lock generated
View File

@ -26,7 +26,7 @@ dependencies = [
"cfg-if", "cfg-if",
"once_cell", "once_cell",
"version_check", "version_check",
"zerocopy", "zerocopy 0.7.35",
] ]
[[package]] [[package]]
@ -321,9 +321,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]] [[package]]
name = "bytes" name = "bytes"
version = "1.6.1" version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" checksum = "fca2be1d5c43812bae364ee3f30b3afcb7877cf59f4aeb94c66f313a41d2fac9"
[[package]] [[package]]
name = "cc" name = "cc"
@ -1482,12 +1482,11 @@ checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]] [[package]]
name = "ppv-lite86" name = "ppv-lite86"
version = "0.2.19" version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2288c0e17cc8d342c712bb43a257a80ebffce59cdb33d5000d8348f3ec02528b" checksum = "dee4364d9f3b902ef14fab8a1ddffb783a1cb6b4bba3bfc1fa3922732c7de97f"
dependencies = [ dependencies = [
"zerocopy", "zerocopy 0.6.6",
"zerocopy-derive",
] ]
[[package]] [[package]]
@ -3115,14 +3114,34 @@ dependencies = [
"windows-sys 0.48.0", "windows-sys 0.48.0",
] ]
[[package]]
name = "zerocopy"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "854e949ac82d619ee9a14c66a1b674ac730422372ccb759ce0c39cabcf2bf8e6"
dependencies = [
"byteorder",
"zerocopy-derive 0.6.6",
]
[[package]] [[package]]
name = "zerocopy" name = "zerocopy"
version = "0.7.35" version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0"
dependencies = [ dependencies = [
"byteorder", "zerocopy-derive 0.7.35",
"zerocopy-derive", ]
[[package]]
name = "zerocopy-derive"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "125139de3f6b9d625c39e2efdd73d41bdac468ccd556556440e322be0e1bbd91"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.72",
] ]
[[package]] [[package]]

View File

@ -57,4 +57,4 @@ tracing-subscriber = { version = "0.3", features = [
] } ] }
utoipa = { version = "4", features = ["axum_extras", "uuid", "chrono"] } utoipa = { version = "4", features = ["axum_extras", "uuid", "chrono"] }
utoipauto = "0.1" utoipauto = "0.1"
uuid = { version = "1", features = ["serde", "v4"] } uuid = { version = "1", features = ["serde", "v7"] }

View File

@ -1,6 +1,6 @@
services: services:
db: db:
image: postgres:alpine image: ghcr.io/fboulnois/pg_uuidv7:1.5.0
environment: environment:
- POSTGRES_USER=tester - POSTGRES_USER=tester
- POSTGRES_PASSWORD=testing123! - POSTGRES_PASSWORD=testing123!

View File

@ -1,3 +1,7 @@
DROP EXTENSION IF EXISTS pg_trgm;
DROP EXTENSION IF EXISTS pg_uuidv7;
DROP TABLE permissions; DROP TABLE permissions;
DROP TABLE files; DROP TABLE files;
@ -7,5 +11,3 @@ DROP TABLE folders;
DROP TABLE users; DROP TABLE users;
DROP TYPE permission; DROP TYPE permission;
DROP EXTENSION pg_trgm;

View File

@ -1,5 +1,7 @@
CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE EXTENSION IF NOT EXISTS pg_uuidv7;
CREATE TABLE CREATE TABLE
users ( users (
user_id SERIAL PRIMARY KEY, user_id SERIAL PRIMARY KEY,
@ -9,7 +11,7 @@ CREATE TABLE
CREATE TABLE CREATE TABLE
folders ( folders (
folder_id UUID PRIMARY KEY DEFAULT gen_random_uuid (), folder_id UUID PRIMARY KEY DEFAULT uuid_generate_v7 (),
parent_folder_id UUID REFERENCES folders (folder_id) ON DELETE CASCADE DEFAULT null, parent_folder_id UUID REFERENCES folders (folder_id) ON DELETE CASCADE DEFAULT null,
owner_id INT REFERENCES users (user_id) ON DELETE CASCADE NOT NULL, owner_id INT REFERENCES users (user_id) ON DELETE CASCADE NOT NULL,
folder_name VARCHAR(255) NOT NULL, folder_name VARCHAR(255) NOT NULL,
@ -18,7 +20,7 @@ CREATE TABLE
CREATE TABLE CREATE TABLE
files ( files (
file_id UUID PRIMARY KEY DEFAULT gen_random_uuid (), file_id UUID PRIMARY KEY DEFAULT uuid_generate_v7 (),
folder_id UUID REFERENCES folders (folder_id) ON DELETE CASCADE NOT NULL, folder_id UUID REFERENCES folders (folder_id) ON DELETE CASCADE NOT NULL,
file_name VARCHAR(255) NOT NULL, file_name VARCHAR(255) NOT NULL,
file_size BIGINT NOT NULL, file_size BIGINT NOT NULL,

View File

@ -7,16 +7,16 @@ pub struct Params {
} }
pub async fn create( pub async fn create(
State(state): State<AppState>, State(pool): State<Pool>,
claims: Claims, claims: Claims,
Json(params): Json<Params>, Json(params): Json<Params>,
) -> Result<Json<Uuid>, StatusCode> { ) -> Result<Json<Uuid>, StatusCode> {
db::folder::get_permissions(params.parent_folder_id, claims.user_id, &state.pool) db::folder::get_permissions(params.parent_folder_id, claims.user_id, &pool)
.await .await
.handle_internal()? .handle_internal()?
.can_write_guard()?; .can_write_guard()?;
let exists = db::folder::name_exists(params.parent_folder_id, &params.folder_name, &state.pool) let exists = db::folder::name_exists(params.parent_folder_id, &params.folder_name, &pool)
.await .await
.handle_internal()?; .handle_internal()?;
if exists { if exists {
@ -27,7 +27,7 @@ pub async fn create(
params.parent_folder_id, params.parent_folder_id,
claims.user_id, claims.user_id,
&params.folder_name, &params.folder_name,
&state.pool, &pool,
) )
.await .await
.handle_internal()?; .handle_internal()?;

View File

@ -16,17 +16,17 @@ pub struct Response {
pub async fn list( pub async fn list(
Query(params): Query<Params>, Query(params): Query<Params>,
State(state): State<AppState>, State(pool): State<Pool>,
claims: Claims, claims: Claims,
) -> Result<Json<Response>, StatusCode> { ) -> Result<Json<Response>, StatusCode> {
let folder_id = db::folder::get_by_id(params.folder_id, claims.user_id, &state.pool) let folder_id = db::folder::get_by_id(params.folder_id, claims.user_id, &pool)
.await .await
.handle_internal()? .handle_internal()?
.ok_or(StatusCode::NOT_FOUND)?; .ok_or(StatusCode::NOT_FOUND)?;
let (files, folders) = try_join!( let (files, folders) = try_join!(
db::file::get_files(folder_id, &state.pool), db::file::get_files(folder_id, &pool),
db::folder::get_folders(folder_id, &state.pool) db::folder::get_folders(folder_id, &pool)
) )
.handle_internal()?; .handle_internal()?;

View File

@ -7,18 +7,18 @@ pub struct Params {
} }
pub async fn delete( pub async fn delete(
State(pool): State<Pool>,
claims: Claims, claims: Claims,
State(state): State<AppState>,
Json(params): Json<Params>, Json(params): Json<Params>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
if params.user_id != claims.user_id { if params.user_id != claims.user_id {
db::folder::get_permissions(params.folder_id, claims.user_id, &state.pool) db::folder::get_permissions(params.folder_id, claims.user_id, &pool)
.await .await
.handle_internal()? .handle_internal()?
.can_manage_guard()?; .can_manage_guard()?;
} }
db::permissions::delete_for_folder(params.folder_id, params.user_id, &state.pool) db::permissions::delete_for_folder(params.folder_id, params.user_id, &pool)
.await .await
.handle_internal()?; .handle_internal()?;

View File

@ -10,16 +10,16 @@ pub struct Params {
} }
pub async fn get( pub async fn get(
State(pool): State<Pool>,
Query(params): Query<Params>, Query(params): Query<Params>,
claims: Claims, claims: Claims,
State(state): State<AppState>,
) -> Result<Json<HashMap<String, PermissionRaw>>, StatusCode> { ) -> Result<Json<HashMap<String, PermissionRaw>>, StatusCode> {
db::folder::get_permissions(params.folder_id, claims.user_id, &state.pool) db::folder::get_permissions(params.folder_id, claims.user_id, &pool)
.await .await
.handle_internal()? .handle_internal()?
.can_manage_guard()?; .can_manage_guard()?;
let permissions = db::permissions::get_all_for_folder(params.folder_id, &state.pool) let permissions = db::permissions::get_all_for_folder(params.folder_id, &pool)
.await .await
.handle_internal()?; .handle_internal()?;
Ok(Json(permissions)) Ok(Json(permissions))

View File

@ -1,10 +1,10 @@
use crate::prelude::*; use crate::prelude::*;
pub async fn get_top_level( pub async fn get_top_level(
State(state): State<AppState>, State(pool): State<Pool>,
claims: Claims, claims: Claims,
) -> Result<Json<Vec<Uuid>>, StatusCode> { ) -> Result<Json<Vec<Uuid>>, StatusCode> {
let folders = db::permissions::get_top_level_permitted_folders(claims.user_id, &state.pool) let folders = db::permissions::get_top_level_permitted_folders(claims.user_id, &pool)
.await .await
.handle_internal()?; .handle_internal()?;
Ok(Json(folders)) Ok(Json(folders))

View File

@ -11,17 +11,17 @@ pub struct Params {
pub async fn set( pub async fn set(
claims: Claims, claims: Claims,
State(state): State<AppState>, State(pool): State<Pool>,
Json(params): Json<Params>, Json(params): Json<Params>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let root = db::folder::get_root(claims.user_id, &state.pool) let root = db::folder::get_root(claims.user_id, &pool)
.await .await
.handle_internal()?; .handle_internal()?;
if params.folder_id == root { if params.folder_id == root {
return Err(StatusCode::BAD_REQUEST); return Err(StatusCode::BAD_REQUEST);
} }
db::folder::get_permissions(params.folder_id, claims.user_id, &state.pool) db::folder::get_permissions(params.folder_id, claims.user_id, &pool)
.await .await
.handle_internal()? .handle_internal()?
.can_manage_guard()?; .can_manage_guard()?;
@ -30,7 +30,7 @@ pub async fn set(
params.user_id, params.user_id,
params.folder_id, params.folder_id,
params.permission_type, params.permission_type,
&state.pool, &pool,
) )
.await .await
.handle_internal()?; .handle_internal()?;

View File

@ -7,10 +7,10 @@ pub struct Params {
} }
pub async fn create( pub async fn create(
State(state): State<AppState>, State(pool): State<Pool>,
Json(params): Json<Params>, Json(params): Json<Params>,
) -> Result<Json<i32>, StatusCode> { ) -> Result<Json<i32>, StatusCode> {
let id = db::users::create_user(&params.username, &params.email, &state.pool) let id = db::users::create_user(&params.username, &params.email, &pool)
.await .await
.handle_internal()?; .handle_internal()?;
Ok(Json(id)) Ok(Json(id))

View File

@ -2,9 +2,11 @@ use futures::TryStreamExt;
use crate::prelude::*; use crate::prelude::*;
pub async fn delete(State(state): State<AppState>, claims: Claims) -> Result<(), StatusCode> { pub async fn delete(
let storage = &state.storage; State(AppState { pool, ref storage }): State<AppState>,
db::users::delete_user(claims.user_id, &state.pool) claims: Claims,
) -> Result<(), StatusCode> {
db::users::delete_user(claims.user_id, &pool)
.try_for_each_concurrent(5, |file_id| async move { .try_for_each_concurrent(5, |file_id| async move {
let _ = storage.delete(file_id).await; let _ = storage.delete(file_id).await;
Ok(()) Ok(())

View File

@ -6,10 +6,10 @@ pub struct Params {
} }
pub async fn get( pub async fn get(
State(state): State<AppState>, State(pool): State<Pool>,
Query(params): Query<Params>, Query(params): Query<Params>,
) -> Result<Json<db::users::UserInfo>, StatusCode> { ) -> Result<Json<db::users::UserInfo>, StatusCode> {
let info = db::users::get(params.user_id, &state.pool) let info = db::users::get(params.user_id, &pool)
.await .await
.handle_internal()?; .handle_internal()?;
Ok(Json(info)) Ok(Json(info))

View File

@ -7,11 +7,11 @@ pub struct Params {
} }
pub async fn put( pub async fn put(
State(state): State<AppState>, State(pool): State<Pool>,
claims: Claims, claims: Claims,
Json(params): Json<Params>, Json(params): Json<Params>,
) -> Result<Json<db::users::UserInfo>, StatusCode> { ) -> Result<Json<db::users::UserInfo>, StatusCode> {
let info = db::users::update(claims.user_id, &params.username, &params.email, &state.pool) let info = db::users::update(claims.user_id, &params.username, &params.email, &pool)
.await .await
.handle_internal()?; .handle_internal()?;
Ok(Json(info)) Ok(Json(info))

View File

@ -8,11 +8,11 @@ pub struct Params {
} }
pub async fn search( pub async fn search(
State(state): State<AppState>, State(pool): State<Pool>,
Query(params): Query<Params>, Query(params): Query<Params>,
) -> sqlx::Result<Json<Vec<db::users::UserInfo>>, StatusCode> { ) -> sqlx::Result<Json<Vec<db::users::UserInfo>>, StatusCode> {
let users = db::users::search_for_user(&params.search_string, &state.pool) let users = db::users::search_for_user(&params.search_string, &pool)
.take(5) .take(20)
.try_collect() .try_collect()
.await .await
.handle_internal()?; .handle_internal()?;

View File

@ -21,7 +21,7 @@ impl FileStorage {
pub fn new() -> anyhow::Result<Self> { pub fn new() -> anyhow::Result<Self> {
let var = env::var("DRIVE_STORAGE_PATH"); let var = env::var("DRIVE_STORAGE_PATH");
let path_str = match var { let path_str = match var {
Ok(ref string) => string, Ok(ref string) => string.trim(),
Err(err) => { Err(err) => {
tracing::info!( tracing::info!(
%err, %err,
@ -55,7 +55,7 @@ impl FileStorage {
pub async fn create(&self) -> anyhow::Result<(Uuid, impl tokio::io::AsyncWrite)> { pub async fn create(&self) -> anyhow::Result<(Uuid, impl tokio::io::AsyncWrite)> {
let mut error = anyhow::anyhow!("Error creating a file"); let mut error = anyhow::anyhow!("Error creating a file");
for _ in 0..3 { for _ in 0..3 {
let file_id = Uuid::new_v4(); let file_id = Uuid::now_v7();
match self.create_inner(file_id).await { match self.create_inner(file_id).await {
Ok(file) => return Ok((file_id, file)), Ok(file) => return Ok((file_id, file)),
Err(err) => error = error.context(err), Err(err) => error = error.context(err),

View File

@ -7,7 +7,7 @@ mod prelude;
use std::{env, net::Ipv4Addr}; use std::{env, net::Ipv4Addr};
use axum::Router; use axum::{extract::FromRef, Router};
use file_storage::FileStorage; use file_storage::FileStorage;
use tokio::net::TcpListener; use tokio::net::TcpListener;
@ -19,7 +19,13 @@ struct AppState {
storage: FileStorage, storage: FileStorage,
} }
async fn create_debug_users(pool: &Pool) -> anyhow::Result<()> { impl FromRef<AppState> for Pool {
fn from_ref(input: &AppState) -> Self {
input.pool.clone()
}
}
async fn create_test_users(pool: &Pool) -> anyhow::Result<()> {
let count = sqlx::query!("SELECT count(user_id) FROM users") let count = sqlx::query!("SELECT count(user_id) FROM users")
.fetch_one(pool) .fetch_one(pool)
.await? .await?
@ -49,11 +55,14 @@ async fn main() -> anyhow::Result<()> {
Err(err) => anyhow::bail!("Error getting database url: {err}"), Err(err) => anyhow::bail!("Error getting database url: {err}"),
}; };
sqlx::migrate!().run(&pool).await?; sqlx::migrate!().run(&pool).await?;
create_debug_users(&pool).await?; if let Ok("1") = env::var("DEVELOPMENT").as_deref().map(str::trim_ascii) {
create_test_users(&pool).await?;
}
let storage = file_storage::FileStorage::new()?; let state = AppState {
pool,
let state = AppState { pool, storage }; storage: FileStorage::new()?,
};
let router = app(state); let router = app(state);
let addr = (Ipv4Addr::UNSPECIFIED, 3000); let addr = (Ipv4Addr::UNSPECIFIED, 3000);