use dropshot::{ConfigLogging, ConfigLoggingLevel, ServerBuilder};
mod api {
use dropshot::{
HttpError, HttpResponseOk, HttpResponseUpdatedNoContent,
RequestContext, TypedBody,
};
use futures::Future;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
pub(crate) trait CounterBase {
fn get_counter_impl(&self) -> impl Future<Output = u64> + Send;
fn set_counter_impl(
&self,
value: u64,
) -> impl Future<Output = Result<(), String>> + Send;
}
#[dropshot::api_description]
pub(crate) trait CounterApi {
type Context: CounterBase;
#[endpoint { method = GET, path = "/counter" }]
async fn get_counter(
rqctx: RequestContext<Self::Context>,
) -> Result<HttpResponseOk<CounterValue>, HttpError> {
let cx = rqctx.context();
Ok(HttpResponseOk(CounterValue {
counter: cx.get_counter_impl().await,
}))
}
#[endpoint { method = PUT, path = "/counter" }]
async fn put_counter(
rqctx: RequestContext<Self::Context>,
update: TypedBody<CounterValue>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let cx = rqctx.context();
cx.set_counter_impl(update.into_inner().counter).await.map_err(
|error| {
HttpError::for_bad_request(
Some(String::from("BadInput")),
error,
)
},
)?;
Ok(HttpResponseUpdatedNoContent())
}
}
#[derive(Deserialize, Serialize, JsonSchema)]
pub(crate) struct CounterValue {
pub(crate) counter: u64,
}
pub(crate) fn generate_openapi_spec() -> String {
let api = counter_api_mod::stub_api_description().unwrap();
let spec = api.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 crate::api::{CounterApi, CounterBase};
pub(crate) struct AtomicCounter {
counter: AtomicU64,
}
impl AtomicCounter {
pub(crate) fn new() -> AtomicCounter {
AtomicCounter { counter: AtomicU64::new(0) }
}
}
impl CounterBase for AtomicCounter {
async fn get_counter_impl(&self) -> u64 {
self.counter.load(Ordering::Relaxed)
}
async fn set_counter_impl(&self, value: u64) -> Result<(), String> {
if value == 10 {
Err(format!("do not like the number {}", value))
} else {
self.counter.store(value, Ordering::SeqCst);
Ok(())
}
}
}
pub(crate) enum CounterImpl {}
impl CounterApi for CounterImpl {
type Context = AtomicCounter;
}
}
#[tokio::main]
async fn main() -> Result<(), String> {
let config_logging =
ConfigLogging::StderrTerminal { level: ConfigLoggingLevel::Info };
let log = config_logging
.to_logger("example-api-trait-default")
.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
}