coap_handler_implementations/typed_resource.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
//! Module containing the [TypeHandler] handler and the [TypeRenderable]
//! trait, along with the [TypeSerializer] helper trait and its corresponding implementations
//! for various serde(ish) (de)serializers.
use crate::helpers::block2_write_with_cf;
use crate::Error;
use coap_handler::Handler;
use coap_message::{
Code as _, MessageOption, MinimalWritableMessage, MutableWritableMessage, ReadableMessage,
};
use coap_message_utils::{option_value::Block2RequestData, OptionsExt};
use coap_numbers::{code, option};
use core::marker::PhantomData;
use serde::Serialize;
/// A type that (for minicbor typed handlers) represents an empty payload.
///
/// This is particularly practical for resources that have a GET and PUT handler that act on
/// serialized data, but where the POST handler just takes an empty resource.
pub struct Empty;
/// A simple Handler trait that supports GET, POST and/or PUT on a data structure that supports
/// serde.
///
/// A TypeRenderable implementation can be turned into a [Handler] by wrapping it in
/// [TypeHandler::new].
pub trait TypeRenderable {
/// Output type of the [get()] method, serialized into the response payload.
type Get;
/// Input type of the [post()] method, deserialized from the request payload.
///
/// Note that with TypedRenderable in this version, the response is always empty.
type Post;
/// Input type of the [put()] method, deserialized from the request payload.
type Put;
fn get(&mut self) -> Result<Self::Get, u8> {
Err(code::METHOD_NOT_ALLOWED)
}
fn post(&mut self, _representation: &Self::Post) -> u8 {
code::METHOD_NOT_ALLOWED
}
fn put(&mut self, _representation: &Self::Put) -> u8 {
code::METHOD_NOT_ALLOWED
}
fn delete(&mut self) -> u8 {
code::METHOD_NOT_ALLOWED
}
}
/// Keeping them hidden to stay flexible; they don't need to be named for their'e either default or
/// their users have aliases.
mod sealed {
pub trait TypeSerializer {
const CF: Option<u16>;
}
pub struct SerdeCBORSerialization;
pub struct MiniCBORSerialization0_19;
pub struct MiniCBORSerialization0_24;
}
use sealed::*;
impl TypeSerializer for SerdeCBORSerialization {
const CF: Option<u16> = coap_numbers::content_format::from_str("application/cbor");
}
/// Wrapper for resource handlers that are implemented in terms of GETting, POSTing or PUTting
/// objects in CBOR format.
///
/// The wrapper handles all encoding and decoding, options processing (ignoring the critical
/// Uri-Path option under the assumption that that has been already processed by an underlying
/// request router), the corresponding errors and block-wise GETs.
///
/// More complex handlers (eg. implementing additional representations, or processing query
/// aprameters into additional data available to the [TypeRenderable]) can be built by
/// forwarding to this (where any critical but already processed options would need to be masked
/// from the message's option) or taking inspiration from it.
pub struct TypeHandler<H, S: TypeSerializer = SerdeCBORSerialization>
where
H: TypeRenderable,
{
handler: H,
_phantom: PhantomData<S>,
}
impl<H, S> TypeHandler<H, S>
where
H: TypeRenderable,
S: TypeSerializer,
{
fn check_get_options(request: &impl ReadableMessage) -> Result<Block2RequestData, Error> {
let mut block2 = None;
request
.options()
.take_block2(&mut block2)
.filter(|o| {
if o.number() == option::ACCEPT {
if let Some(cf) = S::CF {
// If they differ, we'll keep the option for later failing
o.value_uint() != Some(cf)
} else {
// We don't know any content format, so we keep the option in the iterator
// to fail later
true
}
} else {
true
}
})
.ignore_elective_others()?;
Ok(block2.unwrap_or_default())
}
fn check_delete_options(request: &impl ReadableMessage) -> Result<(), Error> {
request.options().ignore_elective_others()
}
fn check_postput_options(request: &impl ReadableMessage) -> Result<(), Error> {
let mut cf = Ok(());
request
.options()
.filter(|o| {
if o.number() == option::CONTENT_FORMAT
&& (S::CF.is_none() || o.value_uint() != S::CF)
{
cf = Err(Error::bad_option(option::CONTENT_FORMAT));
}
// It's not a critical option so we don't really have to filter it out
true
})
.ignore_elective_others()?;
cf
}
}
impl<H> TypeHandler<H, SerdeCBORSerialization>
where
H: TypeRenderable,
H::Get: for<'de> serde::Serialize,
H::Post: for<'de> serde::Deserialize<'de>,
H::Put: for<'de> serde::Deserialize<'de>,
{
/// Wrap a handler that uses [serde::Serialize] / [serde::Deserialize] through [serde_cbor]
pub fn new(handler: H) -> Self {
TypeHandler {
handler,
_phantom: PhantomData,
}
}
}
/// Data carried around between a request and its response for [TypeHandler]s
pub struct TypeRequestData(TypeRequestDataE);
enum TypeRequestDataE {
Get(Block2RequestData), // GET to be processed later, but all request opions were in order
Done(u8), // All done, just a response to emit -- if POST/PUT has been processed, or GET had a bad accept/option
}
use self::TypeRequestDataE::{Done, Get};
// FIXME for all the below: deduplicate (but not sure how, without HKTs) -- and some alterations
// have accumulated
impl<H> Handler for TypeHandler<H, SerdeCBORSerialization>
where
H: TypeRenderable,
H::Get: for<'de> serde::Serialize,
H::Post: for<'de> serde::Deserialize<'de>,
H::Put: for<'de> serde::Deserialize<'de>,
{
type RequestData = TypeRequestData;
type ExtractRequestError = Error;
type BuildResponseError<M: MinimalWritableMessage> = M::UnionError;
fn extract_request_data<M: ReadableMessage>(
&mut self,
request: &M,
) -> Result<Self::RequestData, Error> {
Ok(TypeRequestData(match request.code().into() {
code::DELETE => {
Self::check_delete_options(request)?;
Done(self.handler.delete())
}
code::GET => Get(Self::check_get_options(request)?),
code::POST => {
Self::check_postput_options(request)?;
// FIXME: allow getting a mutable payload here, which may be hard for general
// Message but usually cheap for GNRC-based.
let parsed: H::Post =
serde_cbor::de::from_slice_with_scratch(request.payload(), &mut [])
.map_err(|_| Error::bad_request())?;
Done(self.handler.post(&parsed))
}
code::PUT => {
Self::check_postput_options(request)?;
let parsed: H::Put =
serde_cbor::de::from_slice_with_scratch(request.payload(), &mut [])
.map_err(|_| Error::bad_request())?;
Done(self.handler.put(&parsed))
}
_ => Done(code::METHOD_NOT_ALLOWED),
}))
}
fn estimate_length(&mut self, request: &Self::RequestData) -> usize {
match &request.0 {
Done(_) => 4,
Get(block) => (block.size() + 25).into(), // FIXME: hard-coded copied over from block2_write_with_cf's estimated overhead
}
}
fn build_response<M: MutableWritableMessage>(
&mut self,
response: &mut M,
request: Self::RequestData,
) -> Result<(), Self::BuildResponseError<M>> {
match request.0 {
Done(r) => response.set_code(M::Code::new(r)?),
Get(block2) => {
let repr = self.handler.get();
match repr {
Err(e) => response.set_code(M::Code::new(e)?),
Ok(repr) => {
response.set_code(M::Code::new(code::CONTENT)?);
match block2_write_with_cf(
block2,
response,
|win| repr.serialize(&mut serde_cbor::ser::Serializer::new(win)),
SerdeCBORSerialization::CF,
) {
Ok(()) => (),
Err(_) => {
// FIXME: Rewind all the written options
response.set_code(M::Code::new(code::INTERNAL_SERVER_ERROR)?);
}
}
}
}
}
};
Ok(())
}
}
trait ToTypedResourceError {
fn into_general_error(self, total_len: usize) -> Error;
}
macro_rules! for_each_minicbor {
($minicbor:ident, $mcstype:ident) => {
impl<'b, C> $minicbor::decode::Decode<'b, C> for Empty {
fn decode(
_d: &mut $minicbor::decode::Decoder<'b>,
_ctx: &mut C,
) -> Result<Self, $minicbor::decode::Error> {
Err($minicbor::decode::Error::message("No element expected").at(0))
}
fn nil() -> Option<Self> {
Some(Empty)
}
}
impl<H> Handler for TypeHandler<H, $mcstype>
where
H: TypeRenderable,
H::Get: for<'de> $minicbor::Encode<()>,
H::Post: for<'de> $minicbor::Decode<'de, ()>,
H::Put: for<'de> $minicbor::Decode<'de, ()>,
{
type RequestData = TypeRequestData;
type ExtractRequestError = Error;
type BuildResponseError<M: MinimalWritableMessage> = M::UnionError;
fn extract_request_data<M: ReadableMessage>(
&mut self,
request: &M,
) -> Result<Self::RequestData, Error> {
Ok(TypeRequestData(match request.code().into() {
code::DELETE => {
Self::check_delete_options(request)?;
Done(self.handler.delete())
}
code::GET => Get(Self::check_get_options(request)?),
code::POST => {
use $minicbor::decode::Decode;
Self::check_postput_options(request)?;
let payload = request.payload();
match (payload, H::Post::nil()) {
(b"", Some(nil)) => Done(self.handler.post(&nil)),
(payload, _) => {
let parsed: H::Post =
$minicbor::decode(payload).map_err(|deserialize_error| {
deserialize_error.into_general_error(payload.len())
})?;
Done(self.handler.post(&parsed))
}
}
}
code::PUT => {
Self::check_postput_options(request)?;
let payload = request.payload();
let parsed: H::Put =
$minicbor::decode(payload).map_err(|deserialize_error| {
deserialize_error.into_general_error(payload.len())
})?;
Done(self.handler.put(&parsed))
}
_ => Done(code::METHOD_NOT_ALLOWED),
}))
}
fn estimate_length(&mut self, request: &Self::RequestData) -> usize {
match &request.0 {
Done(_) => 4,
Get(block) => (block.size() + 25).into(), // FIXME: hard-coded copied over from block2_write_with_cf's estimated overhead
}
}
fn build_response<M: MutableWritableMessage>(
&mut self,
response: &mut M,
request: Self::RequestData,
) -> Result<(), Self::BuildResponseError<M>> {
match request.0 {
Done(r) => response.set_code(M::Code::new(r)?),
Get(block2) => {
let repr = self.handler.get();
match repr {
Err(e) => response.set_code(M::Code::new(e)?),
Ok(repr) => {
response.set_code(M::Code::new(code::CONTENT)?);
match block2_write_with_cf(
block2,
response,
|win| $minicbor::encode(&repr, win),
$mcstype::CF,
) {
Ok(()) => (),
Err(_) => {
// FIXME: Rewind all the written options
response
.set_code(M::Code::new(code::INTERNAL_SERVER_ERROR)?);
}
}
}
}
}
};
Ok(())
}
}
impl TypeSerializer for $mcstype {
const CF: Option<u16> = coap_numbers::content_format::from_str("application/cbor");
}
};
}
for_each_minicbor!(minicbor_0_19, MiniCBORSerialization0_19);
for_each_minicbor!(minicbor_0_24, MiniCBORSerialization0_24);
impl<H> TypeHandler<H, MiniCBORSerialization0_19>
where
H: TypeRenderable,
H::Get: for<'de> minicbor_0_19::Encode<()>,
H::Post: for<'de> minicbor_0_19::Decode<'de, ()>,
H::Put: for<'de> minicbor_0_19::Decode<'de, ()>,
{
/// Wrap a handler through minicbor 0.19
pub fn new_minicbor(handler: H) -> Self {
TypeHandler {
handler,
_phantom: PhantomData,
}
}
}
impl<H> TypeHandler<H, MiniCBORSerialization0_24>
where
H: TypeRenderable,
H::Get: for<'de> minicbor_0_24::Encode<()>,
H::Post: for<'de> minicbor_0_24::Decode<'de, ()>,
H::Put: for<'de> minicbor_0_24::Decode<'de, ()>,
{
/// Wrap a handler through minicbor 0.24
pub fn new_minicbor_0_24(handler: H) -> Self {
TypeHandler {
handler,
_phantom: PhantomData,
}
}
}
impl ToTypedResourceError for minicbor_0_19::decode::Error {
fn into_general_error(self, total_len: usize) -> Error {
let mut error = Error::bad_request();
// This version predates https://gitlab.com/twittner/minicbor/-/merge_requests/47
if self.is_end_of_input() {
error = Error::bad_request_with_rbep(total_len);
};
if self.is_type_mismatch() {
error = error.with_title("Type mismatch")
}
error
}
}
impl ToTypedResourceError for minicbor_0_24::decode::Error {
fn into_general_error(self, total_len: usize) -> Error {
let mut error = Error::bad_request();
if let Some(position) = self.position() {
error = Error::bad_request_with_rbep(position);
}
if self.is_end_of_input() {
// Data is not set, but it's convenient to point that out in the error response just in
// case something goes wrong with block-wise transfers
error = Error::bad_request_with_rbep(total_len);
};
if self.is_type_mismatch() {
error = error.with_title("Type mismatch")
}
error
}
}