1use std::time::Duration;
2
3use http::StatusCode;
4use serde::{de::DeserializeOwned, Serialize};
5use serde_json::Value;
6use tracing_error::SpanTrace;
7
8use crate::error::ApiError;
9
10#[derive(Debug, Serialize)]
12#[serde(untagged)]
13pub enum Response {
14 Raw(Value),
16 Auth(AuthResponse),
19 Lease(LeaseResponse),
22}
23
24#[derive(Debug, Serialize)]
26pub struct LeaseResponse {
27 pub revoke: LeaseRenewRevokeEndpoint,
28 pub renew: LeaseRenewRevokeEndpoint,
29 pub data: Value,
30 #[serde(with = "humantime_serde")]
31 pub ttl: Option<Duration>,
32}
33
34#[derive(Debug, Serialize)]
35pub struct LeaseRenewRevokeEndpoint {
36 pub path: String,
37 pub data: Value,
38}
39
40#[derive(Debug, Serialize)]
41pub struct AuthResponse {
42 pub alias: String,
43 #[serde(with = "humantime_serde")]
44 pub ttl: Option<Duration>,
45}
46
47impl Response {
48 #[must_use]
49 pub fn ok() -> Self {
50 Self::Raw(Value::default())
51 }
52
53 pub fn raw<T: Serialize>(data: T) -> Result<Self, serde_json::Error> {
59 serde_json::to_value(data).map(Self::Raw)
60 }
61
62 pub fn data<T: DeserializeOwned>(self) -> Result<T, ApiError> {
69 match self {
70 Response::Raw(data) => serde_json::from_value(data).map_err(|err| ApiError {
71 error: err.into(),
72 status_code: StatusCode::BAD_REQUEST,
73 span_trace: Some(SpanTrace::capture()),
74 }),
75 Response::Auth(_data) => Err(ApiError {
76 error: anyhow::Error::msg("expected raw data, found auth data"),
77 status_code: StatusCode::BAD_REQUEST,
78 span_trace: Some(SpanTrace::capture()),
79 }),
80 Response::Lease(_data) => Err(ApiError {
81 error: anyhow::Error::msg("expected raw data, found lease data"),
82 status_code: StatusCode::BAD_REQUEST,
83 span_trace: Some(SpanTrace::capture()),
84 }),
85 }
86 }
87}