tirbofish/kitgit
feat/better-search / src / git / lfs.rs · 6945 bytes
src/git/lfs.rs
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
//! Minimal Git LFS batch + basic transfer API.
use crate::db::queries;
use crate::state::AppState;
use crate::web::routes::{load_repo_context, AppError, AppResult};
use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::path::PathBuf;
use tokio::fs;
use tokio::io::AsyncWriteExt;
fn lfs_root(state: &AppState) -> PathBuf {
state.config.data_dir.join("lfs")
}
fn oid_path(state: &AppState, oid: &str) -> PathBuf {
let prefix = if oid.len() >= 2 { &oid[..2] } else { "xx" };
lfs_root(state).join(prefix).join(oid)
}
#[derive(Deserialize)]
pub struct LfsBatchRequest {
pub operation: String,
#[serde(default)]
pub transfers: Vec<String>,
pub objects: Vec<LfsObjectSpec>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct LfsObjectSpec {
pub oid: String,
pub size: i64,
}
#[derive(Serialize)]
pub struct LfsBatchResponse {
pub transfer: String,
pub objects: Vec<LfsObjectResult>,
}
#[derive(Serialize)]
pub struct LfsObjectResult {
pub oid: String,
pub size: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub actions: Option<LfsActions>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<LfsError>,
}
#[derive(Serialize)]
pub struct LfsActions {
#[serde(skip_serializing_if = "Option::is_none")]
pub download: Option<LfsAction>,
#[serde(skip_serializing_if = "Option::is_none")]
pub upload: Option<LfsAction>,
}
#[derive(Serialize)]
pub struct LfsAction {
pub href: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub header: Option<std::collections::HashMap<String, String>>,
pub expires_in: u64,
}
#[derive(Serialize)]
pub struct LfsError {
pub code: u16,
pub message: String,
}
pub async fn lfs_batch(
State(state): State<AppState>,
headers: HeaderMap,
Path((owner, repo)): Path<(String, String)>,
Json(req): Json<LfsBatchRequest>,
) -> AppResult<impl IntoResponse> {
let (repository, _o, _viewer, access) =
load_repo_context(&state, &owner, &repo, &headers).await?;
let need_write = req.operation == "upload";
if need_write && !access.can_write() {
return Err(AppError::forbidden());
}
if !access.can_read() {
return Err(AppError::forbidden());
}
let base = state.config.public_url.trim_end_matches('/');
let mut objects = Vec::new();
for obj in req.objects {
if !obj.oid.chars().all(|c| c.is_ascii_hexdigit()) || obj.oid.len() != 64 {
objects.push(LfsObjectResult {
oid: obj.oid,
size: obj.size,
actions: None,
error: Some(LfsError {
code: 422,
message: "invalid oid".into(),
}),
});
continue;
}
let path = oid_path(&state, &obj.oid);
let exists = path.exists();
let href = format!("{base}/{owner}/{repo}/info/lfs/objects/{}/{}", obj.oid, obj.size);
let mut actions = LfsActions {
download: None,
upload: None,
};
if req.operation == "download" {
if exists {
actions.download = Some(LfsAction {
href: href.clone(),
header: None,
expires_in: 3600,
});
} else {
objects.push(LfsObjectResult {
oid: obj.oid,
size: obj.size,
actions: None,
error: Some(LfsError {
code: 404,
message: "object not found".into(),
}),
});
continue;
}
} else if req.operation == "upload" {
if !exists {
actions.upload = Some(LfsAction {
href: href.clone(),
header: None,
expires_in: 3600,
});
}
// verify/download optional after upload
actions.download = Some(LfsAction {
href,
header: None,
expires_in: 3600,
});
let _ = queries::register_lfs_object(&state.pool, repository.id, &obj.oid, obj.size).await;
}
objects.push(LfsObjectResult {
oid: obj.oid,
size: obj.size,
actions: Some(actions),
error: None,
});
}
Ok((
[(header::CONTENT_TYPE, "application/vnd.git-lfs+json")],
Json(LfsBatchResponse {
transfer: "basic".into(),
objects,
}),
))
}
pub async fn lfs_upload(
State(state): State<AppState>,
headers: HeaderMap,
Path((owner, repo, oid, size)): Path<(String, String, String, i64)>,
body: Body,
) -> AppResult<Response> {
let (repository, _o, _viewer, access) =
load_repo_context(&state, &owner, &repo, &headers).await?;
if !access.can_write() {
return Err(AppError::forbidden());
}
if oid.len() != 64 || !oid.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(AppError::bad("invalid oid"));
}
let path = oid_path(&state, &oid);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).await?;
}
let bytes = axum::body::to_bytes(body, 1024 * 1024 * 1024)
.await
.map_err(|e| AppError::bad(e.to_string()))?;
if size >= 0 && bytes.len() as i64 != size {
return Err(AppError::bad("size mismatch"));
}
let mut hasher = Sha256::new();
hasher.update(&bytes);
let dig = hex::encode(hasher.finalize());
if dig != oid {
return Err(AppError::bad("oid mismatch"));
}
let mut file = fs::File::create(&path).await?;
file.write_all(&bytes).await?;
file.flush().await?;
queries::register_lfs_object(&state.pool, repository.id, &oid, bytes.len() as i64).await?;
Ok(StatusCode::OK.into_response())
}
pub async fn lfs_download(
State(state): State<AppState>,
headers: HeaderMap,
Path((owner, repo, oid, _size)): Path<(String, String, String, i64)>,
) -> AppResult<Response> {
let (_repository, _o, _viewer, access) =
load_repo_context(&state, &owner, &repo, &headers).await?;
if !access.can_read() {
return Err(AppError::forbidden());
}
let path = oid_path(&state, &oid);
if !path.exists() {
return Err(AppError::not_found());
}
let data = fs::read(&path).await?;
let len = data.len().to_string();
Ok((
[
(header::CONTENT_TYPE, "application/octet-stream"),
(header::CONTENT_LENGTH, len.as_str()),
],
data,
)
.into_response())
}