tii 0.0.6

A Low-Latency Web Server.
Documentation
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Contains the builder for a router

use crate::default_functions::{
  default_error_handler, default_method_not_allowed_handler, default_not_acceptable_handler,
  default_not_found_handler, default_pre_routing_filter, default_unsupported_media_type_handler,
};
use crate::functional_traits::{
  HttpEndpoint, RequestFilter, ResponseFilter, RouterFilter, StatefulEntityHttpEndpoint,
  WebsocketEndpoint,
};
use crate::tii_builder::EntityHttpEndpoint;
use crate::{AcceptMimeType, RequestBody};
use crate::{AcceptMimeTypeWithCharset, MimeCharset, MimeTypeWithCharset, TiiResult};
use crate::{AsRequestState, RequestContext};
use crate::{DefaultRouter, Response, Router};
use crate::{EntityDeserializer, HttpMethod};
use crate::{ErrorHandler, NotRouteableHandler};
use crate::{HttpRoute, WebSocketRoute};
use crate::{WebsocketReceiver, WebsocketSender};
use std::any::Any;
use std::collections::HashSet;
use std::sync::Arc;

/// Represents a sub-app to run for a specific host.
pub struct RouterBuilder {
  /// This filter/predicate will decide if the router should even serve the request at all
  router_filter: Box<dyn RouterFilter>,

  /// Filters that run before the route is matched.
  /// These filters may modify the path of the request to affect routing decision.
  pre_routing_filters: Vec<Box<dyn RequestFilter>>,
  /// Filters that run once the routing decision has been made.
  /// These filters only run if there is an actual endpoint.
  routing_filters: Vec<Box<dyn RequestFilter>>,

  /// These filters run on the response after the actual endpoint (or the error handler) has been called.
  response_filters: Vec<Box<dyn ResponseFilter>>,

  /// The routes to process requests for and their handlers.
  routes: Vec<HttpRoute>,

  /// The routes to process WebSocket requests for and their handlers.
  websocket_routes: Vec<WebSocketRoute>,

  /// Called when no route has been found in the router.
  not_found_handler: NotRouteableHandler,

  not_acceptable_handler: NotRouteableHandler,
  method_not_allowed_handler: NotRouteableHandler,
  unsupported_media_type_handler: NotRouteableHandler,

  /// Called when an error in any of the above occurs.
  error_handler: ErrorHandler,
}

/// For multi method routes!
#[derive(Debug)]
struct RouteWrapper<T: HttpEndpoint + 'static>(Arc<T>);
impl<T: HttpEndpoint + 'static> HttpEndpoint for RouteWrapper<T> {
  fn serve(&self, request: &RequestContext) -> TiiResult<Response> {
    self.0.serve(request)
  }

  fn parse_entity(
    &self,
    mime: &MimeTypeWithCharset,
    request: &RequestBody,
  ) -> TiiResult<Option<Box<dyn Any + Send + Sync>>> {
    self.0.parse_entity(mime, request)
  }
}

impl<T: HttpEndpoint + 'static> Clone for RouteWrapper<T> {
  fn clone(&self) -> Self {
    Self(Arc::clone(&self.0))
  }
}

/// For multi method routes!
#[derive(Debug)]
struct WSRouteWrapper<T: WebsocketEndpoint + 'static>(Arc<T>);
impl<T: WebsocketEndpoint + 'static> WebsocketEndpoint for WSRouteWrapper<T> {
  fn serve(
    &self,
    request: &RequestContext,
    receiver: WebsocketReceiver,
    sender: WebsocketSender,
  ) -> TiiResult<()> {
    self.0.serve(request, receiver, sender)
  }
}

impl<T: WebsocketEndpoint + 'static> Clone for WSRouteWrapper<T> {
  fn clone(&self) -> Self {
    Self(Arc::clone(&self.0))
  }
}

/// Builder for a route/endpoint.
pub struct RouteBuilder {
  inner: RouterBuilder,
  route: String,
  method: HttpMethod,
  consumes: HashSet<AcceptMimeTypeWithCharset>,
  produces: HashSet<AcceptMimeTypeWithCharset>,
}

impl RouteBuilder {
  pub(crate) fn new(
    router_builder: RouterBuilder,
    method: HttpMethod,
    route: String,
  ) -> RouteBuilder {
    RouteBuilder {
      inner: router_builder,
      route,
      method,
      consumes: Default::default(),
      produces: Default::default(),
    }
  }

  /// Add a mime type which the endpoint can consume.
  pub fn consumes(mut self, mime: impl Into<AcceptMimeTypeWithCharset>) -> Self {
    self.consumes.insert(mime.into());
    self
  }

  /// Add a mime type which the endpoint may produce.
  pub fn produces(mut self, mime: impl Into<AcceptMimeTypeWithCharset>) -> Self {
    self.produces.insert(mime.into());
    self
  }

  /// Finish building the route by proving the endpoint to call.
  pub fn endpoint<T: HttpEndpoint + 'static>(mut self, handler: T) -> TiiResult<RouterBuilder> {
    self.inner.routes.push(HttpRoute::new(
      self.route,
      self.method,
      self.consumes,
      self.produces,
      handler,
    )?);
    Ok(self.inner)
  }

  /// Finish building the route by proving an endpoint which requires a structured request body to call.
  pub fn entity_endpoint<T, R, F, D>(self, handler: F, deserializer: D) -> TiiResult<RouterBuilder>
  where
    T: Any + Send + Sync + 'static,
    R: Into<TiiResult<Response>> + Send + 'static,
    F: Fn(&RequestContext, &T) -> R + Send + Sync + 'static,
    D: EntityDeserializer<T> + Send + Sync + 'static,
  {
    let ehp = EntityHttpEndpoint {
      endpoint: handler,
      deserializer,
      _p1: Default::default(),
      _p2: Default::default(),
    };

    self.endpoint(ehp)
  }

  /// Finish building the route by proving a stateful endpoint which requires a structured request body to call.
  pub fn stateful_entity_endpoint<T, S, SR, R, F, D>(
    self,
    state: S,
    handler: F,
    deserializer: D,
  ) -> TiiResult<RouterBuilder>
  where
    T: Any + Send + Sync + 'static,
    R: Into<TiiResult<Response>> + Send + 'static,
    F: Fn(&SR, &RequestContext, &T) -> R + Send + Sync + 'static,
    D: EntityDeserializer<T> + Send + Sync + 'static,
    S: AsRequestState<Target = SR> + Send + Sync + 'static,
    SR: Send + Sync + 'static,
  {
    let ehp = StatefulEntityHttpEndpoint {
      endpoint: handler,
      state,
      deserializer,
      _p1: Default::default(),
      _p2: Default::default(),
      _p4: Default::default(),
    };

    self.endpoint(ehp)
  }
}

impl Default for RouterBuilder {
  fn default() -> Self {
    RouterBuilder {
      router_filter: Box::new(default_pre_routing_filter),
      pre_routing_filters: Vec::default(),
      routing_filters: Vec::default(),
      response_filters: Vec::default(),
      routes: Vec::new(),
      websocket_routes: Vec::new(),
      not_found_handler: default_not_found_handler,
      not_acceptable_handler: default_not_acceptable_handler,
      method_not_allowed_handler: default_method_not_allowed_handler,
      unsupported_media_type_handler: default_unsupported_media_type_handler,
      error_handler: default_error_handler,
    }
  }
}

impl RouterBuilder {
  /// Create a new sub-app with no routes.
  pub fn new() -> Self {
    RouterBuilder::default()
  }

  /// Adds a pre routing filter. This is called before any routing is done.
  /// The filter can modify the path in the request to change the outcome of routing.
  /// This filter gets called for every request, even those that later fail to find a handler.
  pub fn with_pre_routing_request_filter<T>(mut self, filter: T) -> TiiResult<Self>
  where
    T: RequestFilter + 'static,
  {
    self.pre_routing_filters.push(Box::new(filter));
    Ok(self)
  }

  /// Adds a routing filter. This filter gets called once routing is done.
  /// This filter is called directly before a handler is called.
  /// This filter is only called on requests that actually do have a handler.
  pub fn with_request_filter<T>(mut self, filter: T) -> TiiResult<Self>
  where
    T: RequestFilter + 'static,
  {
    self.routing_filters.push(Box::new(filter));
    Ok(self)
  }

  /// Adds a response filter. This filter gets called after the response is created.
  /// This response may have been created by:
  /// 1. a pre routing filter
  /// 2. a routing filter
  /// 3. a handler/endpoint
  /// 4. the error handler
  /// 5. the not found handler
  ///
  /// # Note on Errors:
  /// If the response filter returns an error itself then this will cause invocation of the error handler,
  /// even if the error handler was already called previously for the same request.
  /// However, each "request" will only trigger exactly 1 invocation of the response filter so it is not possible
  /// to create a loop between response filter and error handler.
  pub fn with_response_filter<T>(mut self, filter: T) -> TiiResult<Self>
  where
    T: ResponseFilter + 'static,
  {
    self.response_filters.push(Box::new(filter));
    Ok(self)
  }

  /// Adds a route that will handle all well known reasonable http methods.
  /// - GET
  /// - PUT
  /// - POST
  /// - PATCH
  /// - DELETE
  /// - OPTIONS
  ///
  /// The endpoint will be called for any media type.
  pub fn route_any<T>(self, route: &str, handler: T) -> TiiResult<Self>
  where
    T: HttpEndpoint + 'static,
  {
    let wrapped = RouteWrapper(Arc::new(handler));

    self
      .route_get(route, wrapped.clone())?
      .route_put(route, wrapped.clone())?
      .route_post(route, wrapped.clone())?
      .route_patch(route, wrapped.clone())?
      .route_delete(route, wrapped.clone())?
      .route_options(route, wrapped.clone())?
      .route_head(route, wrapped)
  }

  /// Helper fn to make some builder code look a bit cleaner.
  pub const fn ok(self) -> TiiResult<Self> {
    Ok(self)
  }

  /// Adds a route that will handle the given http method.
  /// The endpoint will be called for any media type.
  pub fn route_method<T: HttpEndpoint + 'static>(
    mut self,
    method: HttpMethod,
    route: &str,
    handler: T,
  ) -> TiiResult<Self> {
    self.routes.push(HttpRoute::new(
      route,
      method,
      HashSet::from([AcceptMimeTypeWithCharset::new(
        AcceptMimeType::Wildcard,
        MimeCharset::Unspecified,
      )]),
      HashSet::new(),
      handler,
    )?);
    Ok(self)
  }

  /// Adds a route that will handle the GET http method.
  /// The endpoint will be called for any media type.
  pub fn route_get<T: HttpEndpoint + 'static>(self, route: &str, handler: T) -> TiiResult<Self> {
    self.route_method(HttpMethod::Get, route, handler)
  }

  /// Adds a route that will handle the POST http method.
  /// The endpoint will be called for any media type.
  pub fn route_post<T: HttpEndpoint + 'static>(self, route: &str, handler: T) -> TiiResult<Self> {
    self.route_method(HttpMethod::Post, route, handler)
  }

  /// Adds a route that will handle the PUT http method.
  /// The endpoint will be called for any media type.
  pub fn route_put<T: HttpEndpoint + 'static>(self, route: &str, handler: T) -> TiiResult<Self> {
    self.route_method(HttpMethod::Put, route, handler)
  }

  /// Adds a route that will handle the PATCH http method.
  /// The endpoint will be called for any media type.
  pub fn route_patch<T: HttpEndpoint + 'static>(self, route: &str, handler: T) -> TiiResult<Self> {
    self.route_method(HttpMethod::Patch, route, handler)
  }

  /// Adds a route that will handle the DELETE http method.
  /// The endpoint will be called for any media type.
  pub fn route_delete<T: HttpEndpoint + 'static>(self, route: &str, handler: T) -> TiiResult<Self> {
    self.route_method(HttpMethod::Delete, route, handler)
  }

  /// Adds a route that will handle the OPTIONS http method.
  /// The endpoint will be called for any media type.
  pub fn route_options<T: HttpEndpoint + 'static>(
    self,
    route: &str,
    handler: T,
  ) -> TiiResult<Self> {
    self.route_method(HttpMethod::Options, route, handler)
  }

  /// Adds a route that will handle the HEAD http method.
  /// The endpoint will be called for any media type.
  pub fn route_head<T: HttpEndpoint + 'static>(self, route: &str, handler: T) -> TiiResult<Self> {
    self.route_method(HttpMethod::Head, route, handler)
  }

  /// Helper fn that will just call the passed closure,
  /// this can be used to write the builder in an indenting way.
  /// This method is purely cosmetic.
  pub fn begin<T: FnOnce(Self) -> TiiResult<Self>>(self, section: T) -> TiiResult<Self> {
    section(self)
  }

  /// Build an endpoint with a GET http method.
  pub fn get(self, route: &str) -> RouteBuilder {
    RouteBuilder::new(self, HttpMethod::Get, route.to_string())
  }

  /// Build an endpoint with a GET http method.
  pub fn begin_get<T: FnOnce(RouteBuilder) -> TiiResult<Self>>(
    self,
    route: &str,
    closure: T,
  ) -> TiiResult<Self> {
    closure(self.get(route))
  }

  /// Build an endpoint with a POST http method.
  pub fn post(self, route: &str) -> RouteBuilder {
    RouteBuilder::new(self, HttpMethod::Post, route.to_string())
  }

  /// Build an endpoint with a POST http method.
  pub fn begin_post<T: FnOnce(RouteBuilder) -> TiiResult<Self>>(
    self,
    route: &str,
    closure: T,
  ) -> TiiResult<Self> {
    closure(self.post(route))
  }

  /// Build an endpoint with a PUT http method.
  pub fn put(self, route: &str) -> RouteBuilder {
    RouteBuilder::new(self, HttpMethod::Put, route.to_string())
  }

  /// Build an endpoint with a PUT http method.
  pub fn begin_put<T: FnOnce(RouteBuilder) -> TiiResult<Self>>(
    self,
    route: &str,
    closure: T,
  ) -> TiiResult<Self> {
    closure(self.put(route))
  }

  /// Build an endpoint with a PATCH http method.
  pub fn patch(self, route: &str) -> RouteBuilder {
    RouteBuilder::new(self, HttpMethod::Patch, route.to_string())
  }

  /// Build an endpoint with a PATCH http method.
  pub fn begin_patch<T: FnOnce(RouteBuilder) -> TiiResult<Self>>(
    self,
    route: &str,
    closure: T,
  ) -> TiiResult<Self> {
    closure(self.patch(route))
  }

  /// Build an endpoint with a DELETE http method.
  pub fn delete(self, route: &str) -> RouteBuilder {
    RouteBuilder::new(self, HttpMethod::Delete, route.to_string())
  }

  /// Build an endpoint with a DELETE http method.
  pub fn begin_delete<T: FnOnce(RouteBuilder) -> TiiResult<Self>>(
    self,
    route: &str,
    closure: T,
  ) -> TiiResult<Self> {
    closure(self.delete(route))
  }

  /// Build an endpoint with a OPTIONS http method.
  pub fn options(self, route: &str) -> RouteBuilder {
    RouteBuilder::new(self, HttpMethod::Options, route.to_string())
  }

  /// Build an endpoint with a OPTIONS http method.
  pub fn begin_options<T: FnOnce(RouteBuilder) -> TiiResult<Self>>(
    self,
    route: &str,
    closure: T,
  ) -> TiiResult<Self> {
    closure(self.delete(route))
  }

  /// Build an endpoint with a less commonly used or custom http method.
  pub fn method(self, method: HttpMethod, route: &str) -> RouteBuilder {
    RouteBuilder::new(self, method, route.to_string())
  }

  /// Build an endpoint with a less commonly used or custom http method.
  pub fn begin_method<T: FnOnce(RouteBuilder) -> TiiResult<Self>>(
    self,
    method: HttpMethod,
    route: &str,
    closure: T,
  ) -> TiiResult<Self> {
    closure(self.method(method, route))
  }

  /// Adds a WebSocket route and associated handler to the sub-app.
  /// Routes can include wildcards, for example `/ws/*`.
  /// The handler is passed a reading and writing end of the websocket.
  /// The endpoint will be called for any commonly used HTTP method.
  /// Ordinary Web-Socket clients only use the GET Method.
  pub fn ws_route_any<T>(self, route: &str, handler: T) -> TiiResult<Self>
  where
    T: WebsocketEndpoint + 'static,
  {
    let wrapped = WSRouteWrapper(Arc::new(handler));

    self
      .ws_route_get(route, wrapped.clone())?
      .ws_route_put(route, wrapped.clone())?
      .ws_route_post(route, wrapped.clone())?
      .ws_route_patch(route, wrapped.clone())?
      .ws_route_delete(route, wrapped.clone())?
      .ws_route_options(route, wrapped)
  }

  /// Adds a WebSocket route and associated handler to the sub-app.
  /// Routes can include wildcards, for example `/ws/*`.
  /// The handler is passed a reading and writing end of the websocket.
  /// The endpoint will only listen for HTTP upgrade requests that use the specified HTTP method.
  /// Ordinary Web-Socket clients only use the GET Method.
  pub fn ws_route_method<T: WebsocketEndpoint + 'static>(
    mut self,
    method: HttpMethod,
    route: &str,
    handler: T,
  ) -> TiiResult<Self> {
    self.websocket_routes.push(WebSocketRoute::new(
      route,
      method,
      HashSet::new(),
      HashSet::new(),
      handler,
    )?);
    Ok(self)
  }

  /// Adds a WebSocket route and associated handler to the sub-app.
  /// Routes can include wildcards, for example `/ws/*`.
  /// The handler is passed a reading and writing end of the websocket.
  /// The endpoint will only listen for HTTP upgrade requests that use the GET HTTP method.
  /// Ordinary Web-Socket clients only use the GET Method and will call this endpoint.
  pub fn ws_route_get<T>(self, route: &str, handler: T) -> TiiResult<Self>
  where
    T: WebsocketEndpoint + 'static,
  {
    self.ws_route_method(HttpMethod::Get, route, handler)
  }

  /// Adds a WebSocket route and associated handler to the sub-app.
  /// Routes can include wildcards, for example `/ws/*`.
  /// The handler is passed a reading and writing end of the websocket.
  /// The endpoint will only listen for HTTP upgrade requests that use the POST HTTP method.
  /// Ordinary Web-Socket clients only use the GET Method and will NOT call this endpoint.
  pub fn ws_route_post<T>(self, route: &str, handler: T) -> TiiResult<Self>
  where
    T: WebsocketEndpoint + 'static,
  {
    self.ws_route_method(HttpMethod::Post, route, handler)
  }

  /// Adds a WebSocket route and associated handler to the sub-app.
  /// Routes can include wildcards, for example `/ws/*`.
  /// The handler is passed a reading and writing end of the websocket.
  /// The endpoint will only listen for HTTP upgrade requests that use the PUT HTTP method.
  /// Ordinary Web-Socket clients only use the GET Method and will NOT call this endpoint.
  pub fn ws_route_put<T>(self, route: &str, handler: T) -> TiiResult<Self>
  where
    T: WebsocketEndpoint + 'static,
  {
    self.ws_route_method(HttpMethod::Put, route, handler)
  }

  /// Adds a WebSocket route and associated handler to the sub-app.
  /// Routes can include wildcards, for example `/ws/*`.
  /// The handler is passed a reading and writing end of the websocket.
  /// The endpoint will only listen for HTTP upgrade requests that use the OPTIONS HTTP method.
  /// Ordinary Web-Socket clients only use the GET Method and will NOT call this endpoint.
  pub fn ws_route_options<T>(self, route: &str, handler: T) -> TiiResult<Self>
  where
    T: WebsocketEndpoint + 'static,
  {
    self.ws_route_method(HttpMethod::Options, route, handler)
  }

  /// Adds a WebSocket route and associated handler to the sub-app.
  /// Routes can include wildcards, for example `/ws/*`.
  /// The handler is passed a reading and writing end of the websocket.
  /// The endpoint will only listen for HTTP upgrade requests that use the PATCH HTTP method.
  /// Ordinary Web-Socket clients only use the GET Method and will NOT call this endpoint.
  pub fn ws_route_patch<T>(self, route: &str, handler: T) -> TiiResult<Self>
  where
    T: WebsocketEndpoint + 'static,
  {
    self.ws_route_method(HttpMethod::Patch, route, handler)
  }

  /// Adds a WebSocket route and associated handler to the sub-app.
  /// Routes can include wildcards, for example `/ws/*`.
  /// The handler is passed a reading and writing end of the websocket.
  /// The endpoint will only listen for HTTP upgrade requests that use the DELETE HTTP method.
  /// Ordinary Web-Socket clients only use the GET Method and will NOT call this endpoint.
  pub fn ws_route_delete<T>(self, route: &str, handler: T) -> TiiResult<Self>
  where
    T: WebsocketEndpoint + 'static,
  {
    self.ws_route_method(HttpMethod::Delete, route, handler)
  }

  /// Sets the error handler for this router.
  pub fn with_error_handler(mut self, handler: ErrorHandler) -> TiiResult<Self> {
    self.error_handler = handler;
    Ok(self)
  }

  /// Build the router
  pub fn build(self) -> impl Router + 'static {
    DefaultRouter::new(
      self.router_filter,
      self.pre_routing_filters,
      self.routing_filters,
      self.response_filters,
      self.routes,
      self.websocket_routes,
      self.not_found_handler,
      self.not_acceptable_handler,
      self.method_not_allowed_handler,
      self.unsupported_media_type_handler,
      self.error_handler,
    )
  }

  /// Equivalent of calling Arc::new(builder.build())
  pub fn build_arc(self) -> Arc<impl Router + 'static> {
    Arc::new(self.build())
  }
}