use axum::{
extract::{Path, Query, State},
Json,
};
use serde::Deserialize;
use crate::db::models::{
KeychainDeleteResponse, KeychainGetResponse, KeychainListResponse, KeychainSetRequest,
KeychainSetResponse,
};
use crate::error::AppResult;
use crate::services::KeychainService;
#[derive(Debug, Deserialize, Default)]
pub struct KeychainQuery {
pub execution_id: Option<i64>,
#[serde(default = "default_scope")]
pub scope_type: String,
}
fn default_scope() -> String {
"global".to_string()
}
pub async fn get(
State(service): State<KeychainService>,
Path((catalog_id, keychain_name)): Path<(i64, String)>,
Query(query): Query<KeychainQuery>,
) -> AppResult<Json<KeychainGetResponse>> {
let response = service
.get(
catalog_id,
&keychain_name,
query.execution_id,
&query.scope_type,
)
.await?;
Ok(Json(response))
}
pub async fn set(
service: State<KeychainService>,
path: Path<(i64, String)>,
request: Json<KeychainSetRequest>,
) -> AppResult<Json<KeychainSetResponse>> {
let started_at = std::time::Instant::now();
let result = set_inner(service, path, request).await;
let status_label = if result.is_ok() { "ok" } else { "error" };
crate::metrics::record_write_request(
crate::metrics::endpoint::KEYCHAIN_SET,
status_label,
started_at.elapsed().as_secs_f64(),
);
result
}
async fn set_inner(
State(service): State<KeychainService>,
Path((catalog_id, keychain_name)): Path<(i64, String)>,
Json(request): Json<KeychainSetRequest>,
) -> AppResult<Json<KeychainSetResponse>> {
let response = service.set(catalog_id, &keychain_name, request).await?;
Ok(Json(response))
}
pub async fn delete(
State(service): State<KeychainService>,
Path((catalog_id, keychain_name)): Path<(i64, String)>,
Query(query): Query<KeychainQuery>,
) -> AppResult<Json<KeychainDeleteResponse>> {
let response = service
.delete(
catalog_id,
&keychain_name,
query.execution_id,
&query.scope_type,
)
.await?;
Ok(Json(response))
}
pub async fn list_by_catalog(
State(service): State<KeychainService>,
Path(catalog_id): Path<i64>,
) -> AppResult<Json<KeychainListResponse>> {
let response = service.list_by_catalog(catalog_id).await?;
Ok(Json(response))
}