Skip to content

Commit

Permalink
move fully to chrono
Browse files Browse the repository at this point in the history
  • Loading branch information
sdankel committed Jan 11, 2025
1 parent 7c3c0a7 commit 5ad28ca
Show file tree
Hide file tree
Showing 12 changed files with 99 additions and 55 deletions.
23 changes: 23 additions & 0 deletions migrations/2025-01-11-051241_alter_timestamp_to_tstz/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
ALTER TABLE api_tokens
ALTER COLUMN created_at TYPE timestamp
USING created_at AT TIME ZONE 'UTC';

ALTER TABLE api_tokens
ALTER COLUMN expires_at TYPE timestamp
USING expires_at AT TIME ZONE 'UTC';

ALTER TABLE sessions
ALTER COLUMN expires_at TYPE timestamp
USING expires_at AT TIME ZONE 'UTC';

ALTER TABLE sessions
ALTER COLUMN created_at TYPE timestamp
USING created_at AT TIME ZONE 'UTC';

ALTER TABLE uploads
ALTER COLUMN created_at TYPE timestamp
USING created_at AT TIME ZONE 'UTC';

ALTER TABLE users
ALTER COLUMN created_at TYPE timestamp
USING created_at AT TIME ZONE 'UTC';
23 changes: 23 additions & 0 deletions migrations/2025-01-11-051241_alter_timestamp_to_tstz/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
ALTER TABLE api_tokens
ALTER COLUMN created_at TYPE timestamptz
USING created_at AT TIME ZONE 'UTC';

ALTER TABLE api_tokens
ALTER COLUMN expires_at TYPE timestamptz
USING expires_at AT TIME ZONE 'UTC';

ALTER TABLE sessions
ALTER COLUMN expires_at TYPE timestamptz
USING expires_at AT TIME ZONE 'UTC';

ALTER TABLE sessions
ALTER COLUMN created_at TYPE timestamptz
USING created_at AT TIME ZONE 'UTC';

ALTER TABLE uploads
ALTER COLUMN created_at TYPE timestamptz
USING created_at AT TIME ZONE 'UTC';

ALTER TABLE users
ALTER COLUMN created_at TYPE timestamptz
USING created_at AT TIME ZONE 'UTC';
7 changes: 4 additions & 3 deletions src/api/api_token.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use crate::{models, util::sys_time_to_epoch};
use crate::models;
use chrono::{DateTime, Utc};
use rocket::serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Token {
pub id: String,
pub name: String,
pub created_at: u64,
pub created_at: DateTime<Utc>,
pub token: Option<String>,
}

Expand All @@ -15,7 +16,7 @@ impl From<models::ApiToken> for Token {
Token {
id: token.id.to_string(),
name: token.friendly_name,
created_at: sys_time_to_epoch(token.created_at),
created_at: token.created_at,
// We don't return the hashed token, as it's a secret.
token: None,
}
Expand Down
6 changes: 3 additions & 3 deletions src/api/search.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::models::RecentPackage;
use crate::models::PackagePreview;
use serde::Serialize;

#[derive(Serialize, Debug)]
pub struct RecentPackagesResponse {
pub recently_created: Vec<RecentPackage>,
pub recently_updated: Vec<RecentPackage>,
pub recently_created: Vec<PackagePreview>,
pub recently_updated: Vec<PackagePreview>,
}
10 changes: 5 additions & 5 deletions src/db/package_version.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::error::DatabaseError;
use super::{models, schema, DbConn};
use crate::api::publish::PublishRequest;
use crate::models::{ApiToken, RecentPackage};
use crate::models::{ApiToken, PackagePreview};
use diesel::prelude::*;
use uuid::Uuid;

Expand Down Expand Up @@ -101,7 +101,7 @@ impl DbConn {
}

/// Fetch the most recently updated packages.
pub fn get_recently_updated(&mut self) -> Result<Vec<RecentPackage>, DatabaseError> {
pub fn get_recently_updated(&mut self) -> Result<Vec<PackagePreview>, DatabaseError> {
let packages = diesel::sql_query(
r#"WITH ranked_versions AS (
SELECT
Expand All @@ -127,14 +127,14 @@ impl DbConn {
LIMIT 10;
"#,
)
.load::<RecentPackage>(self.inner())
.load::<PackagePreview>(self.inner())
.map_err(|err| DatabaseError::QueryFailed("recently updated".to_string(), err))?;

Ok(packages)
}

/// Fetch the most recently created packages.
pub fn get_recently_created(&mut self) -> Result<Vec<RecentPackage>, DatabaseError> {
pub fn get_recently_created(&mut self) -> Result<Vec<PackagePreview>, DatabaseError> {
let packages = diesel::sql_query(
r#"WITH ranked_versions AS (
SELECT
Expand All @@ -160,7 +160,7 @@ impl DbConn {
LIMIT 10;
"#,
)
.load::<RecentPackage>(self.inner())
.load::<PackagePreview>(self.inner())
.map_err(|err| DatabaseError::QueryFailed("recently created".to_string(), err))?;

Ok(packages)
Expand Down
5 changes: 4 additions & 1 deletion src/db/user_session.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use super::error::DatabaseError;
use super::{api, models, schema, DbConn};
use chrono::{DateTime, Utc};
use diesel::prelude::*;
use diesel::upsert::excluded;
use std::time::{Duration, SystemTime};
Expand Down Expand Up @@ -38,7 +39,9 @@ impl DbConn {

let new_session = models::NewSession {
user_id: saved_user.id,
expires_at: SystemTime::now() + Duration::from_secs(u64::from(expires_in)),
expires_at: DateTime::<Utc>::from(
SystemTime::now() + Duration::from_secs(u64::from(expires_in)),
),
};

// Insert new session
Expand Down
3 changes: 2 additions & 1 deletion src/middleware/session_auth.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::db::Database;
use crate::models;
use chrono::{DateTime, Utc};
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome};
use rocket::Request;
Expand Down Expand Up @@ -44,7 +45,7 @@ impl<'r> FromRequest<'r> for SessionAuth {
{
if let Ok(session) = db.get_session(session_id) {
if let Ok(user) = db.get_user_for_session(session_id) {
if session.expires_at > SystemTime::now() {
if session.expires_at > DateTime::<Utc>::from(SystemTime::now()) {
return Outcome::Success(SessionAuth { user, session_id });
}
}
Expand Down
11 changes: 5 additions & 6 deletions src/middleware/token_auth.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::time::SystemTime;

use crate::db::api_token::PlainToken;
use crate::db::Database;
use crate::models;
use chrono::{DateTime, Utc};
use rocket::http::hyper::header;
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome};
use rocket::Request;
use std::time::SystemTime;

pub struct TokenAuth {
pub token: models::ApiToken,
Expand Down Expand Up @@ -42,10 +42,9 @@ impl<'r> FromRequest<'r> for TokenAuth {
if auth_header.starts_with("Bearer ") {
let token = auth_header.trim_start_matches("Bearer ");
if let Ok(token) = db.get_token(PlainToken::from(token.to_string())) {
if token
.expires_at
.map_or(true, |expires_at| expires_at > SystemTime::now())
{
if token.expires_at.map_or(true, |expires_at| {
expires_at > DateTime::<Utc>::from(SystemTime::now())
}) {
return Outcome::Success(TokenAuth { token });
}
return Outcome::Error((Status::Unauthorized, TokenAuthError::Expired));
Expand Down
39 changes: 19 additions & 20 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use diesel::prelude::*;
use diesel::sql_types::{Nullable, Text, Timestamptz};
use diesel::QueryableByName;
use serde::Serialize;
use std::time::SystemTime;
use uuid::Uuid;

#[derive(Queryable, Selectable, Debug, Clone)]
Expand All @@ -17,7 +16,7 @@ pub struct User {
pub avatar_url: Option<String>,
pub email: Option<String>,
pub is_admin: bool,
pub created_at: SystemTime,
pub created_at: DateTime<Utc>,
}

#[derive(Insertable)]
Expand All @@ -37,15 +36,15 @@ pub struct NewUser {
pub struct Session {
pub id: Uuid,
pub user_id: Uuid,
pub expires_at: SystemTime,
pub created_at: SystemTime,
pub expires_at: DateTime<Utc>,
pub created_at: DateTime<Utc>,
}

#[derive(Insertable)]
#[diesel(table_name = crate::schema::sessions)]
pub struct NewSession {
pub user_id: Uuid,
pub expires_at: SystemTime,
pub expires_at: DateTime<Utc>,
}

#[derive(Queryable, Selectable, Debug, PartialEq, Eq)]
Expand All @@ -55,8 +54,8 @@ pub struct ApiToken {
pub id: Uuid,
pub user_id: Uuid,
pub friendly_name: String,
pub expires_at: Option<SystemTime>,
pub created_at: SystemTime,
pub expires_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
}

#[derive(Insertable)]
Expand All @@ -65,7 +64,7 @@ pub struct NewApiToken {
pub user_id: Uuid,
pub friendly_name: String,
pub token: Vec<u8>,
pub expires_at: Option<SystemTime>,
pub expires_at: Option<DateTime<Utc>>,
}

#[derive(Queryable, Selectable, Debug, Clone)]
Expand All @@ -77,7 +76,7 @@ pub struct Upload {
pub forc_version: String,
pub abi_ipfs_hash: Option<String>,
pub bytecode_identifier: Option<String>,
pub created_at: SystemTime,
pub created_at: DateTime<Utc>,
}

#[derive(Insertable, Debug)]
Expand Down Expand Up @@ -146,15 +145,15 @@ pub struct NewPackageVersion {

#[derive(QueryableByName, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct RecentPackage {
#[sql_type = "Text"]
pub name: String, // Corresponds to `p.package_name as name`
#[sql_type = "Text"]
pub version: String, // Corresponds to `pv.num as version`
#[sql_type = "Nullable<Text>"]
pub description: Option<String>, // Corresponds to `pv.package_description as description`, which might be nullable
#[sql_type = "Timestamptz"]
pub created_at: DateTime<Utc>, // Corresponds to `p.created_at as created_at`
#[sql_type = "Timestamptz"]
pub updated_at: DateTime<Utc>, // Corresponds to `pv.created_at as updated_at`
pub struct PackagePreview {
#[diesel(sql_type = Text)]
pub name: String,
#[diesel(sql_type = Text)]
pub version: String,
#[diesel(sql_type = Nullable<Text>)]
pub description: Option<String>,
#[diesel(sql_type = Timestamptz)]
pub created_at: DateTime<Utc>,
#[diesel(sql_type = Timestamptz)]
pub updated_at: DateTime<Utc>,
}
12 changes: 6 additions & 6 deletions src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ diesel::table! {
user_id -> Uuid,
friendly_name -> Varchar,
token -> Bytea,
expires_at -> Nullable<Timestamp>,
created_at -> Timestamp,
expires_at -> Nullable<Timestamptz>,
created_at -> Timestamptz,
}
}

Expand Down Expand Up @@ -44,8 +44,8 @@ diesel::table! {
sessions (id) {
id -> Uuid,
user_id -> Uuid,
expires_at -> Timestamp,
created_at -> Timestamp,
expires_at -> Timestamptz,
created_at -> Timestamptz,
}
}

Expand All @@ -56,7 +56,7 @@ diesel::table! {
forc_version -> Varchar,
abi_ipfs_hash -> Nullable<Varchar>,
bytecode_identifier -> Nullable<Varchar>,
created_at -> Timestamp,
created_at -> Timestamptz,
}
}

Expand All @@ -69,7 +69,7 @@ diesel::table! {
avatar_url -> Nullable<Varchar>,
email -> Nullable<Varchar>,
is_admin -> Bool,
created_at -> Timestamp,
created_at -> Timestamptz,
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,12 @@ pub fn install_forc_at_path(forc_version: &str, forc_path: &Path) -> Result<(),

#[cfg(test)]
mod tests {
use serial_test::serial;
use crate::pinata::MockPinataClient;

use super::*;

#[tokio::test]
#[serial]
async fn handle_project_upload_success() {
let upload_id = Uuid::new_v4();
let upload_dir = PathBuf::from("tmp/uploads/").join(upload_id.to_string());
Expand Down
12 changes: 3 additions & 9 deletions src/util.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
use semver::Version;
use std::{path::Path, time::SystemTime};

pub fn sys_time_to_epoch(sys_time: SystemTime) -> u64 {
sys_time
.duration_since(SystemTime::UNIX_EPOCH)
.expect("convert time to epoch")
.as_secs()
* 1000
}
use std::path::Path;

pub fn validate_or_format_semver(version: &str) -> Option<String> {
// Remove the leading 'v' if it exists
Expand Down Expand Up @@ -40,6 +32,7 @@ mod tests {
use super::*;
use std::env;
use std::fs;
use serial_test::serial;
use tempfile::tempdir;

#[test]
Expand Down Expand Up @@ -69,6 +62,7 @@ mod tests {
}

#[test]
#[serial]
fn test_load_env() {
// Save the current directory
let original_dir = env::current_dir().unwrap();
Expand Down

0 comments on commit 5ad28ca

Please sign in to comment.