Skip to main content

kcode_k1_http_kmap_representation/
lib.rs

1use axum::{
2    Json,
3    http::{HeaderMap, HeaderValue, StatusCode, header},
4    response::{IntoResponse, Response},
5};
6use kcode_k1_access_types::{AccessId, ProfileId, TxId};
7use serde::{Deserialize, Serialize};
8
9const PROFILE_UNAVAILABLE: &str = "profile is unavailable";
10const NODE_UNAVAILABLE: &str = "node unavailable";
11
12#[derive(Debug)]
13pub struct ApiError(ErrorKind);
14
15#[derive(Debug)]
16enum ErrorKind {
17    Fixed {
18        status: StatusCode,
19        code: &'static str,
20        message: &'static str,
21    },
22    Unavailable(String),
23}
24
25impl ApiError {
26    pub fn status(&self) -> StatusCode {
27        match self.0 {
28            ErrorKind::Fixed { status, .. } => status,
29            ErrorKind::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
30        }
31    }
32
33    pub fn code(&self) -> &'static str {
34        match self.0 {
35            ErrorKind::Fixed { code, .. } => code,
36            ErrorKind::Unavailable(_) => "kmap_creation_unavailable",
37        }
38    }
39
40    pub fn message(&self) -> &str {
41        match &self.0 {
42            ErrorKind::Fixed { message, .. } => message,
43            ErrorKind::Unavailable(message) => message,
44        }
45    }
46}
47
48impl IntoResponse for ApiError {
49    fn into_response(self) -> Response {
50        let status = self.status();
51        let code = self.code();
52        let message = self.message().to_owned();
53        json_response(
54            status,
55            ErrorBody {
56                error: code,
57                message,
58            },
59        )
60    }
61}
62
63fn fixed(status: StatusCode, code: &'static str, message: &'static str) -> ApiError {
64    ApiError(ErrorKind::Fixed {
65        status,
66        code,
67        message,
68    })
69}
70
71fn unavailable(operation: &str, safe_child: impl AsRef<str>) -> ApiError {
72    ApiError(ErrorKind::Unavailable(format!(
73        "{operation}: {}",
74        safe_child.as_ref()
75    )))
76}
77
78pub fn malformed_input() -> ApiError {
79    fixed(
80        StatusCode::BAD_REQUEST,
81        "invalid_json",
82        "request JSON is invalid",
83    )
84}
85
86pub fn unsupported_media_type() -> ApiError {
87    fixed(
88        StatusCode::UNSUPPORTED_MEDIA_TYPE,
89        "unsupported_media_type",
90        "content type must be application/json",
91    )
92}
93
94pub fn invalid_authority_filter() -> ApiError {
95    fixed(
96        StatusCode::BAD_REQUEST,
97        "invalid_authority_filter_id",
98        "authority filter ID is invalid",
99    )
100}
101
102pub fn authority_filter_not_found() -> ApiError {
103    fixed(
104        StatusCode::NOT_FOUND,
105        "authority_filter_not_found",
106        "authority filter is not available",
107    )
108}
109
110pub fn access_context_dependency_error(safe_child: impl AsRef<str>) -> ApiError {
111    unavailable("access context resolution failed", safe_child)
112}
113
114pub fn blocking_task_failure() -> ApiError {
115    ApiError(ErrorKind::Unavailable(
116        "Kmap node creation blocking task failed".to_owned(),
117    ))
118}
119
120pub fn profile_resolution_error(safe_child: impl AsRef<str>) -> ApiError {
121    if safe_child.as_ref() == PROFILE_UNAVAILABLE {
122        fixed(
123            StatusCode::NOT_FOUND,
124            "profile_not_found",
125            "profile is not available",
126        )
127    } else {
128        unavailable("Kmap profile resolution failed", safe_child)
129    }
130}
131
132pub fn creation_error(safe_child: impl AsRef<str>) -> ApiError {
133    match safe_child.as_ref() {
134        PROFILE_UNAVAILABLE => fixed(
135            StatusCode::NOT_FOUND,
136            "profile_not_found",
137            "profile is not available",
138        ),
139        NODE_UNAVAILABLE => fixed(
140            StatusCode::NOT_FOUND,
141            "node_not_found",
142            "node is not available",
143        ),
144        _ => unavailable("Kmap node creation failed", safe_child),
145    }
146}
147
148#[derive(Clone, Debug, Eq, PartialEq)]
149pub struct CreateNode {
150    title: String,
151    navigation_hint: String,
152    narrative: String,
153    connections: Vec<AccessId>,
154}
155
156impl CreateNode {
157    pub fn title(&self) -> &str {
158        &self.title
159    }
160
161    pub fn navigation_hint(&self) -> &str {
162        &self.navigation_hint
163    }
164
165    pub fn narrative(&self) -> &str {
166        &self.narrative
167    }
168
169    pub fn connections(&self) -> &[AccessId] {
170        &self.connections
171    }
172
173    pub fn into_parts(self) -> (String, String, String, Vec<AccessId>) {
174        (
175            self.title,
176            self.navigation_hint,
177            self.narrative,
178            self.connections,
179        )
180    }
181}
182
183#[derive(Deserialize)]
184#[serde(deny_unknown_fields)]
185struct CreateWire {
186    title: String,
187    navigation_hint: String,
188    narrative: String,
189    connections: Vec<String>,
190}
191
192#[derive(Serialize)]
193struct CreatedBody {
194    node_id: String,
195}
196
197#[derive(Serialize)]
198struct ErrorBody {
199    error: &'static str,
200    message: String,
201}
202
203pub fn parse_profile_id(value: &str) -> Result<ProfileId, ApiError> {
204    parse_tx(value).map(ProfileId::new).ok_or_else(|| {
205        fixed(
206            StatusCode::BAD_REQUEST,
207            "invalid_profile_id",
208            "profile ID must be lowercase hexadecimal",
209        )
210    })
211}
212
213pub fn decode_create(headers: &HeaderMap, body: &[u8]) -> Result<CreateNode, ApiError> {
214    require_json(headers)?;
215    let wire: CreateWire = serde_json::from_slice(body).map_err(|_| malformed_input())?;
216    let connections = wire
217        .connections
218        .into_iter()
219        .map(|value| {
220            parse_tx(&value)
221                .map(AccessId::new)
222                .ok_or_else(malformed_input)
223        })
224        .collect::<Result<Vec<_>, _>>()?;
225    Ok(CreateNode {
226        title: wire.title,
227        navigation_hint: wire.navigation_hint,
228        narrative: wire.narrative,
229        connections,
230    })
231}
232
233pub fn created_response(node: AccessId) -> Response {
234    json_response(
235        StatusCode::CREATED,
236        CreatedBody {
237            node_id: node.txid().to_string(),
238        },
239    )
240}
241
242fn require_json(headers: &HeaderMap) -> Result<(), ApiError> {
243    let mut values = headers.get_all(header::CONTENT_TYPE).iter();
244    let Some(value) = values.next() else {
245        return Err(unsupported_media_type());
246    };
247    let valid = values.next().is_none()
248        && value
249            .to_str()
250            .ok()
251            .and_then(|raw| raw.split(';').next())
252            .is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"));
253    if valid {
254        Ok(())
255    } else {
256        Err(unsupported_media_type())
257    }
258}
259
260fn parse_tx(value: &str) -> Option<TxId> {
261    if value.len() != 24
262        || !value
263            .bytes()
264            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
265    {
266        return None;
267    }
268    let mut bytes = [0; 12];
269    for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
270        bytes[index] = nibble(pair[0])? << 4 | nibble(pair[1])?;
271    }
272    Some(TxId::from_bytes(bytes))
273}
274
275fn nibble(byte: u8) -> Option<u8> {
276    match byte {
277        b'0'..=b'9' => Some(byte - b'0'),
278        b'a'..=b'f' => Some(byte - b'a' + 10),
279        _ => None,
280    }
281}
282
283fn json_response<T: Serialize>(status: StatusCode, value: T) -> Response {
284    let mut response = (status, Json(value)).into_response();
285    response
286        .headers_mut()
287        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
288    response
289}
290
291#[cfg(test)]
292mod tests;