use dropshot::{ConfigLogging, ConfigLoggingLevel, ServerBuilder};
mod api {
use dropshot::{
HttpError, HttpResponseOk, HttpResponseUpdatedNoContent,
RequestContext, TypedBody,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[dropshot::api_description]
pub(crate) trait CounterApi {
type Context;
#[endpoint { method = GET, path = "/counter" }]
async fn get_counter(
rqctx: RequestContext<Self::Context>,
) -> Result<HttpResponseOk<CounterValue>, HttpError>;
#[endpoint { method = PUT, path = "/counter" }]
async fn put_counter(
rqctx: RequestContext<Self::Context>,
update: TypedBody<CounterValue>,
) -> Result<HttpResponseUpdatedNoContent, HttpError>;
}
#[derive(Deserialize, Serialize, JsonSchema)]
pub(crate) struct CounterValue {
pub(crate) counter: u64,
}
pub(crate) fn generate_openapi_spec() -> String {
let description = counter_api_mod::stub_api_description().unwrap();
let spec = description
.openapi("Counter Server", semver::Version::new(1, 0, 0));
serde_json::to_string_pretty(&spec.json().unwrap()).unwrap()
}
}
mod imp {
use std::sync::atomic::{AtomicU64, Ordering};
use dropshot::{
HttpError, HttpResponseOk, HttpResponseUpdatedNoContent,
RequestContext, TypedBody,
};
use crate::api::{CounterApi, CounterValue};
pub(crate) struct AtomicCounter {
counter: AtomicU64,
}
impl AtomicCounter {
pub(crate) fn new() -> AtomicCounter {
AtomicCounter { counter: AtomicU64::new(0) }
}
}
pub(crate) enum CounterImpl {}
impl CounterApi for CounterImpl {
type Context = AtomicCounter;
async fn get_counter(
rqctx: RequestContext<Self::Context>,
) -> Result<HttpResponseOk<CounterValue>, HttpError> {
let cx = rqctx.context();
Ok(HttpResponseOk(CounterValue {
counter: cx.counter.load(Ordering::Relaxed),
}))
}
async fn put_counter(
rqctx: RequestContext<Self::Context>,
update: TypedBody<CounterValue>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let cx = rqctx.context();
let updated_value = update.into_inner();
if updated_value.counter == 10 {
Err(HttpError::for_bad_request(
Some(String::from("BadInput")),
format!("do not like the number {}", updated_value.counter),
))
} else {
cx.counter.store(updated_value.counter, Ordering::SeqCst);
Ok(HttpResponseUpdatedNoContent())
}
}
}
}
#[tokio::main]
async fn main() -> Result<(), String> {
let config_logging =
ConfigLogging::StderrTerminal { level: ConfigLoggingLevel::Info };
let log = config_logging
.to_logger("example-api-trait")
.map_err(|error| format!("failed to create logger: {}", error))?;
println!("OpenAPI spec:");
println!("{}", api::generate_openapi_spec());
let my_api =
api::counter_api_mod::api_description::<imp::CounterImpl>().unwrap();
let server = ServerBuilder::new(my_api, imp::AtomicCounter::new(), log)
.start()
.map_err(|error| format!("failed to create server: {}", error))?;
server.await
}