ngyn_shared 0.5.3

Modular backend framework for web applications
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
use http::Request;
use matchit::Params;
use serde::{Deserialize, Serialize};
use std::{any::Any, collections::HashMap, mem::ManuallyDrop, sync::Arc};

use crate::server::{NgynRequest, NgynResponse, Transformer};

/// Represents the value of a context in Ngyn
#[derive(Serialize, Deserialize)]
struct NgynContextValue<V> {
    value: V,
}

impl<V> NgynContextValue<V> {
    pub fn create(value: V) -> Self {
        Self { value }
    }
}

/// Represents the state of an application in Ngyn

pub trait AppState: Any + Send + Sync + 'static {
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

impl<T: AppState> AppState for Box<T> {
    fn as_any(&self) -> &dyn Any {
        self.as_ref()
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self.as_mut()
    }
}

/// # Panics
/// Panics if the state has been dropped. This should never happen unless the state is dropped manually.
impl From<&Arc<Box<dyn AppState>>> for Box<dyn AppState> {
    fn from(value: &Arc<Box<dyn AppState>>) -> Self {
        // creating a clone is essential since this ref will be dropped after this function returns
        let arc_clone = value.clone();
        let state_ref: &dyn AppState = &**arc_clone;

        let state_ptr: *const dyn AppState = state_ref as *const dyn AppState;

        // SAFETY: state_ptr is never null, it is safe to convert it to a NonNull pointer, this way we can safely convert it back to a Box
        // If it is ever found as null, this is a bug. It probably means the memory has been poisoned
        let nn_ptr = std::ptr::NonNull::new(state_ptr as *mut dyn AppState)
            .expect("State has been dropped, but this should never happen, ensure it is being cloned correctly."); // This should never happen, if it does, it's a bug
        let raw_ptr = nn_ptr.as_ptr();

        unsafe { Box::from_raw(raw_ptr) }
    }
}

/// Represents the context of a request in Ngyn
pub struct NgynContext<'a> {
    request: Request<Vec<u8>>,
    pub(crate) response: NgynResponse,
    pub(crate) params: Option<Params<'a, 'a>>,
    store: HashMap<&'a str, String>,
    pub(crate) state: Option<ManuallyDrop<Box<dyn AppState>>>,
}

impl<'a> NgynContext<'a> {
    /// Retrieves the request associated with the context.
    ///
    /// ### Returns
    ///
    /// A reference to the request associated with the context.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    /// use hyper::Request;
    ///
    /// let request = Request::new(Vec::new());
    /// let context = NgynContext::from_request(request);
    ///
    /// let request_ref = context.request();
    /// ```
    pub fn request(&self) -> &Request<Vec<u8>> {
        &self.request
    }

    #[deprecated(since = "0.5.2", note = "use `response_mut()` instead")]
    pub fn response(&mut self) -> &mut NgynResponse {
        &mut self.response
    }

    /// Retrieves the response associated with the context.
    ///
    /// ### Returns
    ///
    /// A mutable reference to the response associated with the context.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    /// use http::Request;
    ///
    /// let request = Request::new(Vec::new());
    /// let context = NgynContext::from_request(request);
    ///
    /// let response_ref = context.response_mut();
    /// ```
    pub fn response_mut(&mut self) -> &mut NgynResponse {
        &mut self.response
    }

    /// Retrieves the params associated with the context.
    ///
    /// ### Returns
    ///
    /// An optional reference to the params associated with the context.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".to_string());
    ///
    /// let params_ref = context.params();
    /// ```
    pub fn params(&self) -> Option<&Params<'a, 'a>> {
        self.params.as_ref()
    }
}

impl NgynContext<'_> {
    /// Retrieves the state of the context as a reference to the specified type.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The type of the state to retrieve.
    ///
    /// ### Returns
    ///
    /// An optional reference to the state of the specified type. Returns `None` if the state is not found or if it cannot be downcasted to the specified type.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    ///
    /// let state_ref = context.state::<TestAppState>();
    /// ```
    pub fn state<T: 'static>(&self) -> Option<&T> {
        match &self.state {
            Some(value) => value.as_any().downcast_ref::<T>(),
            None => None,
        }
    }

    /// Retrieves the state of the context as a mutable reference to the specified type.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The type of the state to retrieve.
    ///
    /// ### Returns
    ///
    /// An optional reference to the state of the specified type. Returns `None` if the state is not found or if it cannot be downcasted to the specified type.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    ///
    /// let state_ref = context.state::<TestAppState>();
    /// ```
    pub fn state_mut<T: 'static>(&mut self) -> Option<&mut T> {
        match &mut self.state {
            Some(value) => value.as_any_mut().downcast_mut::<T>(),
            None => None,
        }
    }
}

impl<'b> NgynContext<'b> {
    /// Retrieves the value associated with the given key from the context.
    ///
    /// ### Arguments
    ///
    /// * `key` - The key (case-insensitive) to retrieve the value for.
    ///
    /// ### Returns
    ///
    /// A reference to the value associated with the key. If the key is not found, returns a reference to an empty context value.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".to_string());
    ///
    /// let value: String = context.get("name").unwrap();
    /// assert_eq!(value, "John".to_string());
    /// ```
    pub fn get<V: for<'a> Deserialize<'a>>(&self, key: &str) -> Option<V> {
        let value = self.store.get(key.to_lowercase().trim());
        if let Some(value) = value {
            if let Ok(stored_cx) = serde_json::from_str::<NgynContextValue<V>>(value) {
                return Some(stored_cx.value);
            }
        }
        None
    }

    /// Sets the value associated with the given key in the context.
    ///
    /// ### Arguments
    ///
    /// * `key` - The key (case-insensitive) to set the value for.
    /// * `value` - The value to associate with the key.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".to_string());
    ///
    /// let value: String = context.get("name").unwrap();
    /// assert_eq!(value, "John".to_string());
    /// ```
    pub fn set<V: Serialize>(&mut self, key: &'b str, value: V) {
        if let Ok(value) = serde_json::to_string(&NgynContextValue::create(value)) {
            self.store.insert(key.trim(), value);
        }
    }

    /// Removes the value associated with the given key from the context.
    ///
    /// ### Arguments
    ///
    /// * `key` - The key (case-insensitive) to remove the value for.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".to_string());
    ///
    /// context.remove("name");
    /// let value = context.get::<String>("name");
    /// assert_eq!(value, None);
    /// ```
    pub fn remove(&mut self, key: &str) {
        self.store.remove(key.to_lowercase().trim());
    }

    /// Clears all values from the context.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".to_string());
    /// context.set("age", 30.into());
    ///
    /// context.clear();
    /// assert_eq!(context.len(), 0);
    /// ```
    pub fn clear(&mut self) {
        self.store.clear();
    }

    /// Returns the number of values in the context.
    ///
    /// ### Returns
    ///
    /// The number of values in the context.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".to_string());
    /// context.set("age", 30.into());
    ///
    /// assert_eq!(context.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.store.len()
    }

    /// Checks if the context is empty.
    ///
    /// ### Returns
    ///
    /// `true` if the context is empty, `false` otherwise.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    ///
    /// assert!(context.is_empty());
    ///
    /// context.set("name", "John".to_string());
    /// assert!(!context.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.store.is_empty()
    }

    /// Checks if the context contains a value for the given key.
    ///
    /// ### Arguments
    ///
    /// * `key` - The key (case-insensitive) to check for.
    ///
    /// ### Returns
    ///
    /// `true` if the context contains a value for the key, `false` otherwise.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    ///
    /// let mut context = NgynContext::from_request(request);
    /// context.set("name", "John".to_string());
    ///
    /// assert!(context.has("name"));
    /// assert!(!context.has("age"));
    /// ```
    pub fn has(&self, key: &str) -> bool {
        self.store.contains_key(key.to_lowercase().trim())
    }
}

impl NgynContext<'_> {
    /// Creates a new `NgynContext` from the given request.
    ///
    /// ### Arguments
    ///
    /// * `request` - The request to create the context from.
    ///
    /// ### Returns
    ///
    /// A new `NgynContext` instance.
    ///
    /// ### Examples
    ///
    /// ```rust ignore
    /// use ngyn_shared::core::context::NgynContext;
    /// use hyper::Request;
    ///
    /// let request = Request::new(Vec::new());
    /// let context = NgynContext::from_request(request);
    /// assert!(context.is_empty());
    /// ```
    pub(crate) fn from_request(request: Request<Vec<u8>>) -> Self {
        NgynContext {
            request,
            response: NgynResponse::default(),
            store: HashMap::new(),
            params: None,
            state: None,
        }
    }
}

impl<'a> Transformer<'a> for &'a NgynContext<'a> {
    fn transform(cx: &'a mut NgynContext) -> Self {
        cx
    }
}

// impl<'a: 'b, 'b> Transformer<'a> for &'a mut NgynContext<'b> {
//     fn transform(cx: &'a mut NgynContext) -> Self {
//         cx
//     }
// }

impl<'a> Transformer<'a> for &'a NgynRequest {
    fn transform(cx: &'a mut NgynContext) -> Self {
        cx.request()
    }
}

impl Transformer<'_> for NgynRequest {
    fn transform(cx: &mut NgynContext) -> Self {
        cx.request().clone()
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use http::Method;

    struct TestAppState {
        value: u128,
    }
    impl AppState for TestAppState {
        fn as_any(&self) -> &dyn Any {
            self
        }

        fn as_any_mut(&mut self) -> &mut dyn Any {
            self
        }
    }

    #[test]
    fn test_request() {
        let request = Request::new(Vec::new());
        let context = NgynContext::from_request(request);

        let request_ref = context.request();
        assert_eq!(request_ref.method(), Method::GET);
    }

    #[test]
    fn test_state() {
        let request = Request::new(Vec::new());
        let mut context = NgynContext::from_request(request);

        let state_ref = context.state::<TestAppState>();
        assert!(state_ref.is_none());

        context.state = Some(ManuallyDrop::new(Box::new(TestAppState { value: 1 })));

        let state_ref = context.state::<TestAppState>();
        assert!(state_ref.is_some());
    }

    #[test]
    fn test_state_mut() {
        let request = Request::new(Vec::new());
        let mut context = NgynContext::from_request(request);
        context.state = Some(ManuallyDrop::new(Box::new(TestAppState { value: 1 })));

        let state_ref = context.state_mut::<TestAppState>();
        assert!(state_ref.is_some());

        state_ref.unwrap().value = 2;

        let state_ref = context.state::<TestAppState>();
        assert_eq!(state_ref.unwrap().value, 2);
    }

    #[test]
    fn test_box_state_impl() {
        let mut state = Box::new(TestAppState { value: 42 });

        // Test as_any
        let any_ref = state.as_any();
        let downcast_result = any_ref.downcast_ref::<TestAppState>();
        assert!(downcast_result.is_some());
        let result = downcast_result.unwrap();
        assert_eq!(result.value, 42);

        // Test as_any_mut
        let any_mut_ref = state.as_any_mut();
        let downcast_mut_result = any_mut_ref.downcast_mut::<TestAppState>();
        assert!(downcast_mut_result.is_some());
        downcast_mut_result.unwrap().value = 99;
        assert_eq!(state.value, 99);
    }

    #[test]
    fn test_get() {
        let request = Request::new(Vec::new());
        let mut context = NgynContext::from_request(request);
        context.set("name", "John".to_string());

        let value: String = context.get("name").unwrap();
        assert_eq!(value, "John".to_string());
    }

    #[test]
    fn test_set() {
        let request = Request::new(Vec::new());
        let mut context = NgynContext::from_request(request);
        context.set("name", "John".to_string());

        let value: String = context.get("name").unwrap();
        assert_eq!(value, "John".to_string());
    }

    #[test]
    fn test_remove() {
        let request = Request::new(Vec::new());
        let mut context = NgynContext::from_request(request);
        context.set("name", "John".to_string());

        context.remove("name");
        let value = context.get::<String>("name");
        assert_eq!(value, None);
    }

    #[test]
    fn test_clear() {
        let request = Request::new(Vec::new());
        let mut context = NgynContext::from_request(request);
        context.set("name", "John".to_string());
        context.set("age", 30);

        context.clear();
        assert_eq!(context.len(), 0);
    }

    #[test]
    fn test_len() {
        let request = Request::new(Vec::new());
        let mut context = NgynContext::from_request(request);
        context.set("name", "John".to_string());
        context.set("age", 30);

        assert_eq!(context.len(), 2);
    }

    #[test]
    fn test_is_empty() {
        let request = Request::new(Vec::new());
        let mut context = NgynContext::from_request(request);

        assert!(context.is_empty());

        context.set("name", "John".to_string());
        assert!(!context.is_empty());
    }

    #[test]
    fn test_has() {
        let request = Request::new(Vec::new());
        let mut context = NgynContext::from_request(request);
        context.set("name", "John".to_string());

        assert!(context.has("name"));
        assert!(!context.has("age"));
    }
}