Compare commits
5
Commits
433d224f6f
...
2f3212527e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f3212527e | ||
|
|
f6dd3d9ca1 | ||
|
|
a430e7f895 | ||
|
|
f510b73d05 | ||
|
|
a269a4bff9 |
+10
@@ -0,0 +1,10 @@
|
|||||||
|
FROM rust:latest as build
|
||||||
|
WORKDIR /usr/src/app
|
||||||
|
COPY Cargo.toml Cargo.lock secret.txt postgres_password.txt .
|
||||||
|
COPY src src
|
||||||
|
RUN rustup target add x86_64-unknown-linux-musl
|
||||||
|
RUN cargo build --target=x86_64-unknown-linux-musl --release
|
||||||
|
|
||||||
|
FROM scratch
|
||||||
|
COPY --from=build /usr/src/app/target/x86_64-unknown-linux-musl/release/shortener /
|
||||||
|
CMD ["/shortener"]
|
||||||
@@ -13,33 +13,55 @@ pub const N_STATEMENTS: usize = 4;
|
|||||||
|
|
||||||
pub async fn get_link(state: &Mutex<GlobalState>, link: &str) -> Result<Option<String>, Error> {
|
pub async fn get_link(state: &Mutex<GlobalState>, link: &str) -> Result<Option<String>, Error> {
|
||||||
let lock = state.lock().await;
|
let lock = state.lock().await;
|
||||||
Ok(lock.db_client.query_opt(&lock.statements[STATEMENT_GET_LINK], &[&link]).await?.map(|row| row.get(0)))
|
Ok(lock
|
||||||
|
.db_client
|
||||||
|
.query_opt(&lock.statements[STATEMENT_GET_LINK], &[&link])
|
||||||
|
.await?
|
||||||
|
.map(|row| row.get(0)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn add_link(state: &Mutex<GlobalState>, link: &str, url: &str) -> Result<(), Error> {
|
pub async fn add_link(state: &Mutex<GlobalState>, link: &str, url: &str) -> Result<(), Error> {
|
||||||
let lock = state.lock().await;
|
let lock = state.lock().await;
|
||||||
lock.db_client.execute(&lock.statements[STATEMENT_ADD_LINK], &[&link, &url]).await?;
|
lock.db_client
|
||||||
|
.execute(&lock.statements[STATEMENT_ADD_LINK], &[&link, &url])
|
||||||
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn add_temporary_link(state: &Mutex<GlobalState>, link: &str, url: &str, ttl: u64) -> Result<(), Error> {
|
pub async fn add_temporary_link(
|
||||||
|
state: &Mutex<GlobalState>,
|
||||||
|
link: &str,
|
||||||
|
url: &str,
|
||||||
|
ttl: u64,
|
||||||
|
) -> Result<(), Error> {
|
||||||
let time = SystemTime::now() + Duration::from_secs(ttl);
|
let time = SystemTime::now() + Duration::from_secs(ttl);
|
||||||
let lock = state.lock().await;
|
let lock = state.lock().await;
|
||||||
lock.db_client.execute(&lock.statements[STATEMENT_ADD_TEMP_LINK], &[&link, &url, &time]).await?;
|
lock.db_client
|
||||||
|
.execute(
|
||||||
|
&lock.statements[STATEMENT_ADD_TEMP_LINK],
|
||||||
|
&[&link, &url, &time],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete_expired_links(state: &Mutex<GlobalState>) -> Result<(), Error> {
|
pub async fn delete_expired_links(state: &Mutex<GlobalState>) -> Result<(), Error> {
|
||||||
let lock = state.lock().await;
|
let lock = state.lock().await;
|
||||||
lock.db_client.execute(&lock.statements[STATEMENT_DELETE_EXPIRED], &[]).await?;
|
lock.db_client
|
||||||
|
.execute(&lock.statements[STATEMENT_DELETE_EXPIRED], &[])
|
||||||
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn prepare_statements(db: &Client) -> Result<[Statement; N_STATEMENTS], Error> {
|
pub async fn prepare_statements(db: &Client) -> Result<[Statement; N_STATEMENTS], Error> {
|
||||||
Ok([db.prepare("SELECT url FROM links WHERE id = $1").await?,
|
Ok([
|
||||||
db.prepare("INSERT INTO links (id, url) VALUES ($1, $2)").await?,
|
db.prepare("SELECT url FROM links WHERE id = $1").await?,
|
||||||
db.prepare("INSERT INTO links (id, url, valid_until) VALUES ($1, $2, $3)").await?,
|
db.prepare("INSERT INTO links (id, url) VALUES ($1, $2)")
|
||||||
db.prepare("DELETE FROM links WHERE valid_until < NOW()").await?
|
.await?,
|
||||||
|
db.prepare("INSERT INTO links (id, url, valid_until) VALUES ($1, $2, $3)")
|
||||||
|
.await?,
|
||||||
|
db.prepare("DELETE FROM links WHERE valid_until < NOW()")
|
||||||
|
.await?,
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
-1
@@ -5,7 +5,12 @@ pub fn generate_link_id(length: u32) -> String {
|
|||||||
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
|
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
|
||||||
let mut link = String::with_capacity(length as usize);
|
let mut link = String::with_capacity(length as usize);
|
||||||
for _ in 0..length {
|
for _ in 0..length {
|
||||||
link.push(alphabet.chars().nth(rng.sample(Uniform::new(0u8, 64u8)) as usize).unwrap());
|
link.push(
|
||||||
|
alphabet
|
||||||
|
.chars()
|
||||||
|
.nth(rng.sample(Uniform::new(0u8, 64u8)) as usize)
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if link == "create" || link == "p" {
|
if link == "create" || link == "p" {
|
||||||
return generate_link_id(length);
|
return generate_link_id(length);
|
||||||
|
|||||||
+51
-12
@@ -1,13 +1,23 @@
|
|||||||
use db::N_STATEMENTS;
|
use db::N_STATEMENTS;
|
||||||
use rocket::{futures::lock::Mutex, get, fs::FileServer, http::Status, response::Redirect, response::content::RawHtml, routes, State};
|
use rocket::{
|
||||||
|
fs::FileServer, futures::lock::Mutex, get, http::Status, response::content::RawHtml,
|
||||||
|
response::Redirect, routes, State,
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
env,
|
||||||
|
fs::File,
|
||||||
|
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||||
|
str::FromStr,
|
||||||
|
sync::Arc,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
use tokio_postgres::{Client, NoTls, Statement};
|
use tokio_postgres::{Client, NoTls, Statement};
|
||||||
use std::{fs::File, sync::Arc, time::Duration};
|
|
||||||
|
|
||||||
mod db;
|
mod db;
|
||||||
mod linkgen;
|
mod linkgen;
|
||||||
|
|
||||||
const DEFAULT_LINK_LENGTH: u32 = 6;
|
const DEFAULT_LINK_LENGTH: u32 = 6;
|
||||||
const LINK_PREFIX: &str = "https://slavasil.ru/";
|
const LINK_PREFIX: &str = "https://xurl.pw/";
|
||||||
|
|
||||||
pub struct GlobalState {
|
pub struct GlobalState {
|
||||||
db_client: Client,
|
db_client: Client,
|
||||||
@@ -16,7 +26,8 @@ pub struct GlobalState {
|
|||||||
}
|
}
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
let postgres_config = "host=localhost user=shortener password=".to_owned() + include_str!("../postgres_password.txt").trim();
|
let postgres_config = "host=localhost user=shortener password=".to_owned()
|
||||||
|
+ include_str!("../postgres_password.txt").trim();
|
||||||
let (client, conn) = match tokio_postgres::connect(&postgres_config, NoTls).await {
|
let (client, conn) = match tokio_postgres::connect(&postgres_config, NoTls).await {
|
||||||
Ok((client, conn)) => (client, conn),
|
Ok((client, conn)) => (client, conn),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -31,9 +42,21 @@ async fn main() {
|
|||||||
});
|
});
|
||||||
db::prepare_tables(&client).await.unwrap();
|
db::prepare_tables(&client).await.unwrap();
|
||||||
let statements = db::prepare_statements(&client).await.unwrap();
|
let statements = db::prepare_statements(&client).await.unwrap();
|
||||||
|
|
||||||
|
let default_listen_addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 3020).into();
|
||||||
|
let listen_addr = env::var("SERVER_ADDR")
|
||||||
|
.ok()
|
||||||
|
.map(|v| SocketAddr::from_str(&v).ok())
|
||||||
|
.flatten()
|
||||||
|
.unwrap_or(default_listen_addr);
|
||||||
let mut config = rocket::Config::default();
|
let mut config = rocket::Config::default();
|
||||||
config.port = 3020;
|
config.address = listen_addr.ip();
|
||||||
let state = GlobalState { db_client: client, statements };
|
config.port = listen_addr.port();
|
||||||
|
|
||||||
|
let state = GlobalState {
|
||||||
|
db_client: client,
|
||||||
|
statements,
|
||||||
|
};
|
||||||
let state_mutex = Arc::new(Mutex::new(state));
|
let state_mutex = Arc::new(Mutex::new(state));
|
||||||
{
|
{
|
||||||
let state_mutex = state_mutex.clone();
|
let state_mutex = state_mutex.clone();
|
||||||
@@ -44,16 +67,25 @@ async fn main() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
rocket::build()
|
rocket::build()
|
||||||
.mount("/", routes![create, go_to_link])
|
.mount("/", routes![create, go_to_link])
|
||||||
.manage(state_mutex.clone())
|
.manage(state_mutex.clone())
|
||||||
.configure(config)
|
.configure(config)
|
||||||
.launch()
|
.launch()
|
||||||
.await.unwrap();
|
.await
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/create?<url>&<secret>&<length>&<link>&<ttl>")]
|
#[get("/create?<url>&<secret>&<length>&<link>&<ttl>")]
|
||||||
async fn create(state: &State<Mutex<GlobalState>>, url: &str, secret: Option<&str>, length: Option<u32>, link: Option<&str>, ttl: Option<u64>) -> (Status, String) {
|
async fn create(
|
||||||
|
state: &State<Arc<Mutex<GlobalState>>>,
|
||||||
|
url: &str,
|
||||||
|
secret: Option<&str>,
|
||||||
|
length: Option<u32>,
|
||||||
|
link: Option<&str>,
|
||||||
|
ttl: Option<u64>,
|
||||||
|
) -> (Status, String) {
|
||||||
let mut allow_secret_options = false;
|
let mut allow_secret_options = false;
|
||||||
if let Some(secret) = secret {
|
if let Some(secret) = secret {
|
||||||
if secret == include_str!("../secret.txt").trim() {
|
if secret == include_str!("../secret.txt").trim() {
|
||||||
@@ -68,7 +100,11 @@ async fn create(state: &State<Mutex<GlobalState>>, url: &str, secret: Option<&st
|
|||||||
custom_link = true;
|
custom_link = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let actual_len = if allow_secret_options && length.is_some() { length.unwrap() } else { DEFAULT_LINK_LENGTH };
|
let actual_len = if allow_secret_options && length.is_some() {
|
||||||
|
length.unwrap()
|
||||||
|
} else {
|
||||||
|
DEFAULT_LINK_LENGTH
|
||||||
|
};
|
||||||
if actual_len < 1 || actual_len > 64 {
|
if actual_len < 1 || actual_len > 64 {
|
||||||
return (Status::BadRequest, "invalid length".to_owned());
|
return (Status::BadRequest, "invalid length".to_owned());
|
||||||
}
|
}
|
||||||
@@ -86,7 +122,7 @@ async fn create(state: &State<Mutex<GlobalState>>, url: &str, secret: Option<&st
|
|||||||
if custom_link {
|
if custom_link {
|
||||||
return (Status::BadRequest, "link already exists".to_owned());
|
return (Status::BadRequest, "link already exists".to_owned());
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
None => {
|
None => {
|
||||||
actual_link = Some(link_id.clone());
|
actual_link = Some(link_id.clone());
|
||||||
break;
|
break;
|
||||||
@@ -101,7 +137,7 @@ async fn create(state: &State<Mutex<GlobalState>>, url: &str, secret: Option<&st
|
|||||||
|
|
||||||
let res = match ttl {
|
let res = match ttl {
|
||||||
Some(ttl) => db::add_temporary_link(&state, actual_link.as_ref().unwrap(), url, ttl).await,
|
Some(ttl) => db::add_temporary_link(&state, actual_link.as_ref().unwrap(), url, ttl).await,
|
||||||
None => db::add_link(&state, actual_link.as_ref().unwrap(), url).await
|
None => db::add_link(&state, actual_link.as_ref().unwrap(), url).await,
|
||||||
};
|
};
|
||||||
match res {
|
match res {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
@@ -116,7 +152,10 @@ async fn create(state: &State<Mutex<GlobalState>>, url: &str, secret: Option<&st
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[get("/<link>")]
|
#[get("/<link>")]
|
||||||
pub async fn go_to_link(state: &State<Mutex<GlobalState>>, link: &str) -> Result<Option<Redirect>, Status> {
|
pub async fn go_to_link(
|
||||||
|
state: &State<Arc<Mutex<GlobalState>>>,
|
||||||
|
link: &str,
|
||||||
|
) -> Result<Option<Redirect>, Status> {
|
||||||
match db::get_link(&state, link).await {
|
match db::get_link(&state, link).await {
|
||||||
Ok(url) => match url {
|
Ok(url) => match url {
|
||||||
Some(url) => Ok(Some(Redirect::to(url))),
|
Some(url) => Ok(Some(Redirect::to(url))),
|
||||||
|
|||||||
Reference in New Issue
Block a user