use axum::{
Json,
http::{HeaderMap, HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
};
use kcode_k1_access_types::{AccessId, ProfileId, TxId};
use serde::{Deserialize, Serialize};
const PROFILE_UNAVAILABLE: &str = "profile is unavailable";
const NODE_UNAVAILABLE: &str = "node unavailable";
#[derive(Debug)]
pub struct ApiError(ErrorKind);
#[derive(Debug)]
enum ErrorKind {
Fixed {
status: StatusCode,
code: &'static str,
message: &'static str,
},
Unavailable(String),
}
impl ApiError {
pub fn status(&self) -> StatusCode {
match self.0 {
ErrorKind::Fixed { status, .. } => status,
ErrorKind::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
}
}
pub fn code(&self) -> &'static str {
match self.0 {
ErrorKind::Fixed { code, .. } => code,
ErrorKind::Unavailable(_) => "kmap_creation_unavailable",
}
}
pub fn message(&self) -> &str {
match &self.0 {
ErrorKind::Fixed { message, .. } => message,
ErrorKind::Unavailable(message) => message,
}
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let status = self.status();
let code = self.code();
let message = self.message().to_owned();
json_response(
status,
ErrorBody {
error: code,
message,
},
)
}
}
fn fixed(status: StatusCode, code: &'static str, message: &'static str) -> ApiError {
ApiError(ErrorKind::Fixed {
status,
code,
message,
})
}
fn unavailable(operation: &str, safe_child: impl AsRef<str>) -> ApiError {
ApiError(ErrorKind::Unavailable(format!(
"{operation}: {}",
safe_child.as_ref()
)))
}
pub fn malformed_input() -> ApiError {
fixed(
StatusCode::BAD_REQUEST,
"invalid_json",
"request JSON is invalid",
)
}
pub fn unsupported_media_type() -> ApiError {
fixed(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"unsupported_media_type",
"content type must be application/json",
)
}
pub fn invalid_authority_filter() -> ApiError {
fixed(
StatusCode::BAD_REQUEST,
"invalid_authority_filter_id",
"authority filter ID is invalid",
)
}
pub fn authority_filter_not_found() -> ApiError {
fixed(
StatusCode::NOT_FOUND,
"authority_filter_not_found",
"authority filter is not available",
)
}
pub fn access_context_dependency_error(safe_child: impl AsRef<str>) -> ApiError {
unavailable("access context resolution failed", safe_child)
}
pub fn blocking_task_failure() -> ApiError {
ApiError(ErrorKind::Unavailable(
"Kmap node creation blocking task failed".to_owned(),
))
}
pub fn profile_resolution_error(safe_child: impl AsRef<str>) -> ApiError {
if safe_child.as_ref() == PROFILE_UNAVAILABLE {
fixed(
StatusCode::NOT_FOUND,
"profile_not_found",
"profile is not available",
)
} else {
unavailable("Kmap profile resolution failed", safe_child)
}
}
pub fn creation_error(safe_child: impl AsRef<str>) -> ApiError {
match safe_child.as_ref() {
PROFILE_UNAVAILABLE => fixed(
StatusCode::NOT_FOUND,
"profile_not_found",
"profile is not available",
),
NODE_UNAVAILABLE => fixed(
StatusCode::NOT_FOUND,
"node_not_found",
"node is not available",
),
_ => unavailable("Kmap node creation failed", safe_child),
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CreateNode {
title: String,
navigation_hint: String,
narrative: String,
connections: Vec<AccessId>,
}
impl CreateNode {
pub fn title(&self) -> &str {
&self.title
}
pub fn navigation_hint(&self) -> &str {
&self.navigation_hint
}
pub fn narrative(&self) -> &str {
&self.narrative
}
pub fn connections(&self) -> &[AccessId] {
&self.connections
}
pub fn into_parts(self) -> (String, String, String, Vec<AccessId>) {
(
self.title,
self.navigation_hint,
self.narrative,
self.connections,
)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CreateWire {
title: String,
navigation_hint: String,
narrative: String,
connections: Vec<String>,
}
#[derive(Serialize)]
struct CreatedBody {
node_id: String,
}
#[derive(Serialize)]
struct ErrorBody {
error: &'static str,
message: String,
}
pub fn parse_profile_id(value: &str) -> Result<ProfileId, ApiError> {
parse_tx(value).map(ProfileId::new).ok_or_else(|| {
fixed(
StatusCode::BAD_REQUEST,
"invalid_profile_id",
"profile ID must be lowercase hexadecimal",
)
})
}
pub fn decode_create(headers: &HeaderMap, body: &[u8]) -> Result<CreateNode, ApiError> {
require_json(headers)?;
let wire: CreateWire = serde_json::from_slice(body).map_err(|_| malformed_input())?;
let connections = wire
.connections
.into_iter()
.map(|value| {
parse_tx(&value)
.map(AccessId::new)
.ok_or_else(malformed_input)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(CreateNode {
title: wire.title,
navigation_hint: wire.navigation_hint,
narrative: wire.narrative,
connections,
})
}
pub fn created_response(node: AccessId) -> Response {
json_response(
StatusCode::CREATED,
CreatedBody {
node_id: node.txid().to_string(),
},
)
}
fn require_json(headers: &HeaderMap) -> Result<(), ApiError> {
let mut values = headers.get_all(header::CONTENT_TYPE).iter();
let Some(value) = values.next() else {
return Err(unsupported_media_type());
};
let valid = values.next().is_none()
&& value
.to_str()
.ok()
.and_then(|raw| raw.split(';').next())
.is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"));
if valid {
Ok(())
} else {
Err(unsupported_media_type())
}
}
fn parse_tx(value: &str) -> Option<TxId> {
if value.len() != 24
|| !value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return None;
}
let mut bytes = [0; 12];
for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
bytes[index] = nibble(pair[0])? << 4 | nibble(pair[1])?;
}
Some(TxId::from_bytes(bytes))
}
fn nibble(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
_ => None,
}
}
fn json_response<T: Serialize>(status: StatusCode, value: T) -> Response {
let mut response = (status, Json(value)).into_response();
response
.headers_mut()
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
response
}
#[cfg(test)]
mod tests;