Use Actix worker thread for database operations

This commit is contained in:
Cameron Cordes
2021-03-17 22:30:02 -04:00
parent 3c02bcc8fb
commit a2a9c27f12
2 changed files with 16 additions and 8 deletions

View File

@@ -5,16 +5,20 @@ extern crate rayon;
use crate::auth::login;
use database::{SqliteUserDao, UserDao};
use futures::stream::StreamExt;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::{env, fs::File};
use actix::{Actor, Addr};
use actix_files::NamedFile;
use actix_multipart as mp;
use actix_web::{get, post, web, App, HttpServer, Responder};
use actix_web::{
get, post,
web::{self, BufMut, BytesMut},
App, HttpServer, Responder,
};
use actix_web::{
middleware,
web::{HttpRequest, HttpResponse, Json},
@@ -103,7 +107,7 @@ async fn get_image(
#[post("/image")]
async fn upload_image(_: Claims, mut payload: mp::Multipart) -> impl Responder {
let mut file_content: Vec<_> = Vec::new();
let mut file_content: BytesMut = BytesMut::new();
let mut file_name: Option<String> = None;
let mut file_path: Option<String> = None;
@@ -115,7 +119,7 @@ async fn upload_image(_: Claims, mut payload: mp::Multipart) -> impl Responder {
file_name = Some(filename.to_string());
while let Some(Ok(data)) = part.next().await {
file_content.extend_from_slice(data.as_ref());
file_content.put(data);
}
} else if content_type.get_name().map_or(false, |name| name == "path") {
while let Some(Ok(data)) = part.next().await {
@@ -213,7 +217,9 @@ async fn get_video_part(
#[get("image/favorites")]
async fn favorites(claims: Claims) -> impl Responder {
let favorites = get_favorites(claims.sub.parse::<i32>().unwrap())
let favorites = web::block(move || get_favorites(claims.sub.parse::<i32>().unwrap()))
.await
.unwrap()
.into_iter()
.map(|favorite| favorite.path)
.collect::<Vec<String>>();
@@ -227,7 +233,10 @@ async fn favorites(claims: Claims) -> impl Responder {
#[post("image/favorites")]
async fn post_add_favorite(claims: Claims, body: web::Json<AddFavoriteRequest>) -> impl Responder {
if let Ok(user_id) = claims.sub.parse::<i32>() {
add_favorite(user_id, body.path.clone());
let path = body.path.clone();
web::block::<_, _, String>(move || Ok(add_favorite(user_id, path)))
.await
.unwrap();
debug!("Adding favorite \"{}\" for userid: {}", user_id, body.path);
HttpResponse::Ok()
} else {