Thanks to visit codestin.com
Credit goes to github.com

Skip to content
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
356 changes: 108 additions & 248 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions atuin-client/src/api_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub async fn register(
username: &str,
email: &str,
password: &str,
) -> Result<RegisterResponse<'static>> {
) -> Result<RegisterResponse> {
let mut map = HashMap::new();
map.insert("username", username);
map.insert("email", email);
Expand Down Expand Up @@ -61,7 +61,7 @@ pub async fn register(
Ok(session)
}

pub async fn login(address: &str, req: LoginRequest<'_>) -> Result<LoginResponse<'static>> {
pub async fn login(address: &str, req: LoginRequest) -> Result<LoginResponse> {
let url = format!("{}/login", address);
let client = reqwest::Client::new();

Expand Down Expand Up @@ -142,7 +142,7 @@ impl<'a> Client<'a> {
Ok(history)
}

pub async fn post_history(&self, history: &[AddHistoryRequest<'_, String>]) -> Result<()> {
pub async fn post_history(&self, history: &[AddHistoryRequest]) -> Result<()> {
let url = format!("{}/history", self.sync_addr);
let url = Url::parse(url.as_str())?;

Expand Down
4 changes: 2 additions & 2 deletions atuin-client/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,10 @@ async fn sync_upload(
let data = serde_json::to_string(&data)?;

let add_hist = AddHistoryRequest {
id: i.id.into(),
id: i.id,
timestamp: i.timestamp,
data,
hostname: hash_str(&i.hostname).into(),
hostname: hash_str(&i.hostname),
};

buffer.push(add_hist);
Expand Down
3 changes: 2 additions & 1 deletion atuin-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ chrono = { version = "0.4", features = ["serde"] }
serde_derive = "1.0.125"
serde = "1.0.126"
serde_json = "1.0.75"
warp = "0.3"
uuid = { version = "0.8", features = ["v4"] }
axum = "0.5"
http = "0.2"
86 changes: 26 additions & 60 deletions atuin-common/src/api.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@
use std::{borrow::Cow, convert::Infallible};
use std::borrow::Cow;

use axum::{response::IntoResponse, Json};
use chrono::Utc;
use serde::Serialize;
use warp::{reply::Response, Reply};

#[derive(Debug, Serialize, Deserialize)]
pub struct UserResponse<'a> {
pub username: Cow<'a, str>,
pub struct UserResponse {
pub username: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RegisterRequest<'a> {
pub email: Cow<'a, str>,
pub username: Cow<'a, str>,
pub password: Cow<'a, str>,
pub struct RegisterRequest {
pub email: String,
pub username: String,
pub password: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RegisterResponse<'a> {
pub session: Cow<'a, str>,
pub struct RegisterResponse {
pub session: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LoginRequest<'a> {
pub username: Cow<'a, str>,
pub password: Cow<'a, str>,
pub struct LoginRequest {
pub username: String,
pub password: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LoginResponse<'a> {
pub session: Cow<'a, str>,
pub struct LoginResponse {
pub session: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AddHistoryRequest<'a, D> {
pub id: Cow<'a, str>,
pub struct AddHistoryRequest {
pub id: String,
pub timestamp: chrono::DateTime<Utc>,
pub data: D,
pub hostname: Cow<'a, str>,
pub data: String,
pub hostname: String,
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -46,10 +46,10 @@ pub struct CountResponse {
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SyncHistoryRequest<'a> {
pub struct SyncHistoryRequest {
pub sync_ts: chrono::DateTime<chrono::FixedOffset>,
pub history_ts: chrono::DateTime<chrono::FixedOffset>,
pub host: Cow<'a, str>,
pub host: String,
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -62,25 +62,19 @@ pub struct ErrorResponse<'a> {
pub reason: Cow<'a, str>,
}

impl Reply for ErrorResponse<'_> {
fn into_response(self) -> Response {
warp::reply::json(&self).into_response()
impl<'a> IntoResponse for ErrorResponseStatus<'a> {
fn into_response(self) -> axum::response::Response {
(self.status, Json(self.error)).into_response()
}
}

pub struct ErrorResponseStatus<'a> {
pub error: ErrorResponse<'a>,
pub status: warp::http::StatusCode,
}

impl Reply for ErrorResponseStatus<'_> {
fn into_response(self) -> Response {
warp::reply::with_status(self.error, self.status).into_response()
}
pub status: http::StatusCode,
}

impl<'a> ErrorResponse<'a> {
pub fn with_status(self, status: warp::http::StatusCode) -> ErrorResponseStatus<'a> {
pub fn with_status(self, status: http::StatusCode) -> ErrorResponseStatus<'a> {
ErrorResponseStatus {
error: self,
status,
Expand All @@ -93,31 +87,3 @@ impl<'a> ErrorResponse<'a> {
}
}
}

pub enum ReplyEither<T, E> {
Ok(T),
Err(E),
}

impl<T: Reply, E: Reply> Reply for ReplyEither<T, E> {
fn into_response(self) -> Response {
match self {
ReplyEither::Ok(t) => t.into_response(),
ReplyEither::Err(e) => e.into_response(),
}
}
}

pub type ReplyResult<T, E> = Result<ReplyEither<T, E>, Infallible>;
pub fn reply_error<T, E>(e: E) -> ReplyResult<T, E> {
Ok(ReplyEither::Err(e))
}

pub type JSONResult<E> = Result<ReplyEither<warp::reply::Json, E>, Infallible>;
pub fn reply_json<E>(t: impl Serialize) -> JSONResult<E> {
reply(warp::reply::json(&t))
}

pub fn reply<T, E>(t: T) -> ReplyResult<T, E> {
Ok(ReplyEither::Ok(t))
}
3 changes: 2 additions & 1 deletion atuin-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ base64 = "0.13.0"
rand = "0.8.4"
rust-crypto = "^0.2"
tokio = { version = "1", features = ["full"] }
warp = "0.3"
sqlx = { version = "0.5", features = [ "runtime-tokio-rustls", "uuid", "chrono", "postgres" ] }
async-trait = "0.1.49"
axum = "0.5"
http = "0.2"
53 changes: 25 additions & 28 deletions atuin-server/src/handlers/history.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
use warp::{http::StatusCode, Reply};
use axum::extract::Query;
use axum::{Extension, Json};
use http::StatusCode;

use crate::database::Database;
use crate::database::{Database, Postgres};
use crate::models::{NewHistory, User};
use atuin_common::api::*;

pub async fn count(
user: User,
db: impl Database + Clone + Send + Sync,
) -> JSONResult<ErrorResponseStatus<'static>> {
db.count_history(&user).await.map_or(
reply_error(
ErrorResponse::reply("failed to query history count")
.with_status(StatusCode::INTERNAL_SERVER_ERROR),
),
|count| reply_json(CountResponse { count }),
)
db: Extension<Postgres>,
) -> Result<Json<CountResponse>, ErrorResponseStatus<'static>> {
match db.count_history(&user).await {
Ok(count) => Ok(Json(CountResponse { count })),
Err(_) => Err(ErrorResponse::reply("failed to query history count")
.with_status(StatusCode::INTERNAL_SERVER_ERROR)),
}
}

pub async fn list(
req: SyncHistoryRequest<'_>,
req: Query<SyncHistoryRequest>,
user: User,
db: impl Database + Clone + Send + Sync,
) -> JSONResult<ErrorResponseStatus<'static>> {
db: Extension<Postgres>,
) -> Result<Json<SyncHistoryResponse>, ErrorResponseStatus<'static>> {
let history = db
.list_history(
&user,
Expand All @@ -32,10 +33,8 @@ pub async fn list(

if let Err(e) = history {
error!("failed to load history: {}", e);
return reply_error(
ErrorResponse::reply("failed to load history")
.with_status(StatusCode::INTERNAL_SERVER_ERROR),
);
return Err(ErrorResponse::reply("failed to load history")
.with_status(StatusCode::INTERNAL_SERVER_ERROR));
}

let history: Vec<String> = history
Expand All @@ -50,14 +49,14 @@ pub async fn list(
user.id
);

reply_json(SyncHistoryResponse { history })
Ok(Json(SyncHistoryResponse { history }))
}

pub async fn add(
req: Vec<AddHistoryRequest<'_, String>>,
Json(req): Json<Vec<AddHistoryRequest>>,
user: User,
db: impl Database + Clone + Send + Sync,
) -> ReplyResult<impl Reply, ErrorResponseStatus<'_>> {
db: Extension<Postgres>,
) -> Result<(), ErrorResponseStatus<'static>> {
debug!("request to add {} history items", req.len());

let history: Vec<NewHistory> = req
Expand All @@ -67,18 +66,16 @@ pub async fn add(
user_id: user.id,
hostname: h.hostname,
timestamp: h.timestamp.naive_utc(),
data: h.data.into(),
data: h.data,
})
.collect();

if let Err(e) = db.add_history(&history).await {
error!("failed to add history: {}", e);

return reply_error(
ErrorResponse::reply("failed to add history")
.with_status(StatusCode::INTERNAL_SERVER_ERROR),
);
return Err(ErrorResponse::reply("failed to add history")
.with_status(StatusCode::INTERNAL_SERVER_ERROR));
};

reply(warp::reply())
Ok(())
}
2 changes: 1 addition & 1 deletion atuin-server/src/handlers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod history;
pub mod user;

pub const fn index() -> &'static str {
pub async fn index() -> &'static str {
"\"Through the fathomless deeps of space swims the star turtle Great A\u{2019}Tuin, bearing on its back the four giant elephants who carry on their shoulders the mass of the Discworld.\"\n\t-- Sir Terry Pratchett"
}
Loading