1use axum::body::Body;
25use axum::extract::{Path, Query, State};
26use axum::http::{header, HeaderMap, StatusCode};
27use axum::response::{IntoResponse, Response};
28use axum::Json;
29use serde::{Deserialize, Serialize};
30
31use super::{require_user, Shared};
32use crate::Error;
33
34#[derive(Debug, Serialize)]
37pub struct IndexEntry {
38 pub key: String,
39 pub part_id: String,
40 pub part_number: String,
41 pub part_name: String,
42 pub document_class: crate::model::DocumentClass,
45 pub revision_id: String,
46 pub revision_label: String,
47 pub lifecycle: &'static str,
48 pub editable: bool,
49 pub content_hash: String,
50 pub size: u64,
51 pub modified: u64,
52 pub locked_by: Option<String>,
53 pub locked_by_me: bool,
54}
55
56#[derive(Debug, Serialize)]
57pub struct Index {
58 pub seq: u64,
59 pub entries: Vec<IndexEntry>,
60}
61
62#[derive(Debug, Default, Deserialize)]
63pub struct IndexQuery {
64 #[serde(default)]
67 pub keys: Option<String>,
68}
69
70pub async fn index(
76 State(db): State<Shared>,
77 headers: HeaderMap,
78 query: Option<Query<IndexQuery>>,
79) -> Result<Json<Index>, Error> {
80 let user = require_user(&db, &headers)?;
81 let wanted: Option<Vec<(String, String)>> = query.and_then(|Query(q)| q.keys).map(|keys| {
82 keys.split(',').filter_map(|key| split_key(key.trim()).ok()).collect()
83 });
84 Ok(Json(db.read(|state| {
85 let row = |part: &crate::model::Part, revision: &crate::model::Revision| IndexEntry {
86 key: revision.document_key(&part.id),
87 part_id: part.id.clone(),
88 part_number: part.number.clone(),
89 part_name: part.name.clone(),
90 document_class: part.document_class,
91 revision_id: revision.id.clone(),
92 revision_label: revision.label.clone(),
93 lifecycle: revision.lifecycle.as_str(),
94 editable: revision.lifecycle.is_editable(),
95 content_hash: revision.content_hash.clone(),
96 size: revision.size,
97 modified: revision.modified_at,
98 locked_by: revision.lock.as_ref().and_then(|l| state.user(&l.user_id).map(|u| u.username.clone())),
99 locked_by_me: revision.lock.as_ref().is_some_and(|l| l.user_id == user.id),
100 };
101 let mut entries = Vec::new();
102 match &wanted {
103 Some(keys) => {
104 for (part_id, revision_id) in keys {
105 if let Some(part) = state.part(part_id) {
106 if let Some(revision) = part.revision(revision_id) {
107 entries.push(row(part, revision));
108 }
109 }
110 }
111 }
112 None => {
113 for part in &state.parts {
114 for revision in &part.revisions {
115 entries.push(row(part, revision));
116 }
117 }
118 }
119 }
120 Index { seq: state.seq, entries }
121 })))
122}
123
124#[derive(Debug, Deserialize)]
125pub struct Since {
126 #[serde(default)]
127 pub since: u64,
128}
129
130#[derive(Debug, Serialize)]
131pub struct Changes {
132 pub seq: u64,
133 pub stale: bool,
136 pub keys: Vec<String>,
137}
138
139pub async fn changes(
140 State(db): State<Shared>,
141 headers: HeaderMap,
142 Query(query): Query<Since>,
143) -> Result<Json<Changes>, Error> {
144 require_user(&db, &headers)?;
145 let (seq, stale, keys) = db.changes_since(query.since);
146 Ok(Json(Changes { seq, stale, keys }))
147}
148
149fn split_key(key: &str) -> Result<(String, String), Error> {
151 crate::identity::split_key(key).ok_or_else(|| Error::bad_request(format!(
152 "'{key}' is not a document key — expected part/<part>/rev/<revision>"
153 )))
154}
155
156pub async fn read_doc(
160 State(db): State<Shared>,
161 headers: HeaderMap,
162 Path(key): Path<String>,
163) -> Result<Response, Error> {
164 require_user(&db, &headers)?;
165 let (part_id, revision_id) = split_key(&key)?;
166 let exists = db.read(|state| {
167 state
168 .part(&part_id)
169 .and_then(|p| p.revision(&revision_id))
170 .is_some()
171 });
172 if !exists {
173 return Err(Error::not_found("revision"));
174 }
175 match db.read_document(&key)? {
176 Some(body) => Ok((
177 StatusCode::OK,
178 [(header::CONTENT_TYPE, "application/json; charset=utf-8")],
179 body,
180 )
181 .into_response()),
182 None => Ok(StatusCode::NO_CONTENT.into_response()),
186 }
187}
188
189pub async fn write_doc(
195 State(db): State<Shared>,
196 headers: HeaderMap,
197 Path(key): Path<String>,
198 body: Body,
199) -> Result<Response, Error> {
200 let user = require_user(&db, &headers)?;
201 let (part_id, revision_id) = split_key(&key)?;
202 guard_writable(&db, &user, &part_id, &revision_id)?;
203 let limit = db.security().config.document_limit();
204 let body = read_bounded(&headers, body, limit, || {
205 format!("the document is over the {} document limit", megabytes(limit))
206 })
207 .await?;
208
209 if serde_json::from_str::<serde_json::Value>(&body).is_err() {
212 return Err(Error::bad_request("a document must be JSON"));
213 }
214
215 let if_match = headers
218 .get(axum::http::header::IF_MATCH)
219 .and_then(|v| v.to_str().ok())
220 .map(|v| v.trim().trim_matches('"').to_string())
221 .filter(|v| !v.is_empty());
222 let (seq, uses_refused) = db.write_document_deriving(&part_id, &revision_id, &body, if_match.as_deref())?;
225 Ok(Json(serde_json::json!({
226 "ok": true,
227 "seq": seq,
228 "uses_refused": uses_refused,
229 "content_hash": db.read(|state|state.part(&part_id).and_then(|p|p.revision(&revision_id)).map(|r|r.content_hash.clone()).unwrap_or_default()),
230 "size": body.len(),
231 }))
232 .into_response())
233}
234
235pub async fn delete_doc(
236 State(db): State<Shared>,
237 headers: HeaderMap,
238 Path(key): Path<String>,
239) -> Result<Response, Error> {
240 let user = require_user(&db, &headers)?;
241 let (part_id, revision_id) = split_key(&key)?;
242 guard_writable(&db, &user, &part_id, &revision_id)?;
243 db.remove_document(&key)?;
244 db.mutate(|state| {
245 if let Some(revision) = state.parts.get_mut(&part_id)
246 .and_then(|p| p.revision_mut(&revision_id))
247 {
248 revision.content_hash.clear();
249 revision.size = 0;
250 revision.modified_at = crate::db::now();
251 }
252 crate::review::document_changed(state, &part_id, &revision_id);
253 Ok(())
254 })?;
255 Ok(super::ok_seq(&db))
256}
257
258fn guard_writable(
262 db: &crate::db::Db,
263 user: &crate::model::User,
264 part_id: &str,
265 revision_id: &str,
266) -> Result<(), Error> {
267 db.read(|state| crate::db::check_writable(state, user, part_id, revision_id))
268}
269
270pub(crate) async fn read_bounded(
276 headers: &HeaderMap,
277 body: Body,
278 limit: u64,
279 refusal: impl Fn() -> String,
280) -> Result<String, Error> {
281 let too_large = || Error { status: StatusCode::PAYLOAD_TOO_LARGE, message: refusal() };
282 let declared = headers
283 .get(header::CONTENT_LENGTH)
284 .and_then(|v| v.to_str().ok())
285 .and_then(|v| v.parse::<u64>().ok());
286 if declared.is_some_and(|length| length > limit) {
287 return Err(too_large());
288 }
289 let mut bytes = Vec::with_capacity(declared.unwrap_or(0) as usize);
290 let mut body = body;
291 while let Some(chunk) = super::body_io::next_chunk(&mut body).await {
292 let chunk = chunk.map_err(|e| Error::bad_request(format!("the request body broke off: {e}")))?;
293 if bytes.len() as u64 + chunk.len() as u64 > limit {
294 return Err(too_large());
295 }
296 bytes.extend_from_slice(&chunk);
297 }
298 String::from_utf8(bytes).map_err(|_| Error::bad_request("the body must be JSON, and it is not UTF-8 text"))
299}
300
301pub(crate) fn megabytes(limit: u64) -> String {
303 const MB: u64 = 1024 * 1024;
304 if limit >= MB && limit % MB == 0 { format!("{} MB", limit / MB) } else { format!("{} KB", limit.div_ceil(1024)) }
305}