1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
|
use axum::extract::Form;
use axum::http::StatusCode;
use axum::response::{Html, IntoResponse};
use axum::Extension;
use info_utils::prelude::*;
use crate::CreateForm;
use crate::ServerState;
use crate::UrlRow;
#[derive(Debug, Clone, sqlx::FromRow, PartialEq, Eq)]
struct NextId {
id: String,
index: Option<i64>,
exists: bool,
}
#[derive(Debug, Clone, sqlx::FromRow, PartialEq, Eq)]
struct NextIndex {
new_index: Option<i64>,
}
pub async fn create_link(
Extension(state): Extension<ServerState>,
Form(form): Form<CreateForm>,
) -> impl IntoResponse {
log!("Request to create '{}' -> {}", form.id, form.url.as_str());
let try_id = generate_id(form.clone(), state.clone()).await;
if let Ok(id) = try_id {
if id.exists {
log!("Serving cached id {} -> {}", id.id, form.url.as_str());
return Html(format!(
r#"<pre>http{}://{}/{} -> <a href="{}"">{}</a></pre>"#,
if state.uses_https { "s" } else { "" },
state.host,
id.id,
form.url.as_str(),
form.url.as_str(),
))
.into_response();
}
let res;
if let Some(index) = id.index {
res = sqlx::query(
"
INSERT INTO chela.urls (index,id,url,custom_id)
VALUES ($1,$2,$3,false)
",
)
.bind(index)
.bind(id.id.clone())
.bind(form.url.as_str())
.execute(&state.db_pool)
.await;
} else {
res = sqlx::query(
"
INSERT INTO chela.urls (id,url,custom_id)
VALUES ($1,$2,true)
",
)
.bind(id.id.clone())
.bind(form.url.as_str())
.execute(&state.db_pool)
.await;
}
match res {
Ok(_) => {
log!("Created new id {} -> {}", id.id, form.url.as_str());
return (
StatusCode::OK,
Html(format!(
r#"<pre>http{}://{}/{} -> <a href="{}"">{}</a></pre>"#,
if state.uses_https { "s" } else { "" },
state.host,
id.id,
form.url.as_str(),
form.url.as_str(),
)),
)
.into_response();
}
Err(err) => {
warn!("{}", err);
return (StatusCode::INTERNAL_SERVER_ERROR, Html("Internal error."))
.into_response();
}
}
} else if let Err(err) = try_id {
warn!("{}", err);
return (
StatusCode::INTERNAL_SERVER_ERROR,
Html(format!("Internal error: {err}")),
)
.into_response();
}
(StatusCode::INTERNAL_SERVER_ERROR, Html("Internal error.")).into_response()
}
async fn generate_id(form: CreateForm, state: ServerState) -> eyre::Result<NextId> {
if form.id.is_empty() {
let existing_row: Result<UrlRow, sqlx::Error> =
sqlx::query_as("SELECT * FROM chela.urls WHERE url = $1 AND custom_id = 'false'")
.bind(form.url.as_str())
.fetch_one(&state.db_pool)
.await;
if let Ok(row) = existing_row {
return Ok(NextId {
id: row.id,
index: None,
exists: true,
});
}
let next_index: NextIndex = sqlx::query_as(
"SELECT nextval(pg_get_serial_sequence('chela.urls', 'index')) as new_index",
)
.fetch_one(&state.db_pool)
.await?;
if let Some(index) = next_index.new_index {
let new_id = state.sqids.encode(&[index.try_into()?])?;
return Ok(NextId {
id: new_id,
index: Some(index),
exists: false,
});
}
} else {
let existing_row: Result<UrlRow, sqlx::Error> =
sqlx::query_as("SELECT * FROM chela.urls WHERE id = $1")
.bind(form.id.clone())
.fetch_one(&state.db_pool)
.await;
if let Ok(row) = existing_row {
if row.url == form.url.as_str() {
return Ok(NextId {
id: row.id,
index: None,
exists: true,
});
}
return Err(eyre::eyre!("id '{}' is already taken", row.id));
}
return Ok(NextId {
id: form.id,
index: None,
exists: false,
});
}
Err(eyre::eyre!("Internal error"))
}
|