actix-cloud-extra 0.1.6

Extra tools for Actix Cloud.
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
//! REST API helpers: pagination parameters, dynamic query condition building
//! and common request payloads.

use std::cmp;
#[cfg(feature = "seaorm")]
use std::collections::BTreeMap;
use std::hash::Hash;

use actix_cloud::utils;
use anyhow::Result;
use derivative::Derivative;
#[cfg(feature = "seaorm")]
use sea_orm::{
    ExprTrait as _, FromQueryResult, Order, QueryOrder as _,
    entity::prelude::async_trait::async_trait,
    prelude::*,
    sea_query::{ColumnRef, LikeExpr, SimpleExpr},
};
use serde::{Deserialize, Serialize};
use serde_inline_default::serde_inline_default;
use validator::{Validate, ValidationError};

use crate::HyUuid;
#[cfg(feature = "entity")]
use crate::entity::DefaultColumnTrait;
#[cfg(feature = "seaorm")]
use crate::utils::StringUtil as _;

/// Standard paginated response: total item count plus one page of data.
#[derive(Serialize, Debug)]
pub struct PageData<T> {
    /// Total number of items across all pages.
    pub total: u64,
    /// Items of the requested page.
    pub data: Vec<T>,
}

impl<T> PageData<T> {
    /// Build from a `(data, total)` tuple, e.g. as returned by
    /// `Condition::select_page` or [`PaginationParam::split`].
    pub fn new(data: (Vec<T>, u64)) -> Self {
        Self {
            total: data.1,
            data: data.0,
        }
    }
}

/// Pagination parameters (`page` / `size`) accepted from query or body.
///
/// Both fields fall back to defaults (page 1, size 10) when missing. Call
/// `validate` (from `validator`) to enforce `page >= 1` and
/// `1 <= size <= 100`.
#[serde_inline_default]
#[derive(Derivative, Deserialize, Validate, Clone, Debug)]
#[derivative(Default(new = "true"))]
pub struct PaginationParam {
    /// 1-based page index.
    #[validate(range(min = 1))]
    #[serde_inline_default(1)]
    #[derivative(Default(value = "1"))]
    pub page: u64,

    /// Number of items per page, capped at 100 by validation.
    #[validate(range(min = 1, max = 100))]
    #[serde_inline_default(10)]
    #[derivative(Default(value = "10"))]
    pub size: u64,
}

impl PaginationParam {
    /// 0-based index of the first item of the page (saturating).
    pub fn left(&self) -> u64 {
        self.page.saturating_sub(1).saturating_mul(self.size)
    }

    /// Exclusive 0-based end index of the page (saturating).
    pub fn right(&self) -> u64 {
        self.page.saturating_mul(self.size)
    }

    /// Clamp a `u64` offset/count down to [`usize`] so it can be used for
    /// in-memory slicing on any platform.
    pub fn round(p: u64) -> usize {
        cmp::min(p, usize::MAX as u64) as usize
    }

    /// Apply the pagination to an in-memory list, returning the requested page
    /// plus the total item count.
    pub fn split<T>(&self, data: Vec<T>) -> PageData<T> {
        let cnt = data.len();
        PageData::new((
            data.into_iter()
                .skip(Self::round(self.left()))
                .take(Self::round(self.size))
                .collect(),
            cnt as u64,
        ))
    }
}

/// Extension for SeaORM `Select`: execute a query with optional pagination and
/// get back `(items, total_count)`.
#[cfg(feature = "seaorm")]
#[async_trait]
pub trait SelectPage<E, C>
where
    E: EntityTrait,
    C: ConnectionTrait,
{
    /// Fetch one page when `p` is given, or the whole result set (with its
    /// length as total) otherwise.
    async fn select_page(self, db: &C, p: Option<PaginationParam>) -> Result<(Vec<E::Model>, u64)>;
}

#[cfg(feature = "seaorm")]
#[async_trait]
impl<M, E, C> SelectPage<E, C> for Select<E>
where
    E: EntityTrait<Model = M>,
    M: FromQueryResult + Sized + Send + Sync,
    C: ConnectionTrait,
{
    async fn select_page(self, db: &C, p: Option<PaginationParam>) -> Result<(Vec<E::Model>, u64)> {
        if let Some(page) = p {
            let q = self.paginate(db, page.size);
            Ok((
                q.fetch_page(page.page.saturating_sub(1)).await?,
                q.num_items().await?,
            ))
        } else {
            let res = self.all(db).await?;
            let cnt = res.len() as u64;
            Ok((res, cnt))
        }
    }
}

/// Helpers to turn strings into SeaORM/SeaQuery expressions.
#[cfg(feature = "seaorm")]
pub trait IntoExpr {
    /// Build `col LIKE '%<self>%'`, escaping `\`, `%` and `_` in `self`.
    fn like_expr<T>(&self, col: T) -> SimpleExpr
    where
        T: ColumnTrait;
}

#[cfg(feature = "seaorm")]
impl IntoExpr for &String {
    fn like_expr<T>(&self, col: T) -> SimpleExpr
    where
        T: ColumnTrait,
    {
        sea_orm::prelude::Expr::col((col.entity_name(), col))
            .like(LikeExpr::new(format!("%{}%", self.like_escape())).escape('\\'))
    }
}

/// The query condition hub: filters + optional pagination + sort order.
///
/// Built fluently, then applied to a SeaORM `Select` via [`Condition::build`]
/// or executed directly with [`Condition::select_page`]. All CRUD helpers
/// generated by the `default_repo` macro funnel through it.
#[cfg(feature = "seaorm")]
pub struct Condition {
    /// Optional SQL pagination.
    pub page: Option<PaginationParam>,
    /// WHERE filters, `all()` by default.
    pub cond: sea_orm::Condition,
    /// Sort expressions, applied in insertion order.
    pub order: Vec<(SimpleExpr, Order)>,
}

#[cfg(feature = "seaorm")]
impl Default for Condition {
    fn default() -> Self {
        Self {
            cond: sea_orm::Condition::all(),
            page: None,
            order: Vec::new(),
        }
    }
}

#[cfg(feature = "seaorm")]
impl From<sea_orm::Condition> for Condition {
    fn from(cond: sea_orm::Condition) -> Self {
        Self::new(cond)
    }
}

#[cfg(feature = "seaorm")]
impl Condition {
    /// Wrap an existing [`sea_orm::Condition`] as filters.
    pub fn new(cond: sea_orm::Condition) -> Self {
        Self {
            cond,
            page: None,
            order: Vec::new(),
        }
    }

    /// New condition matching everything (`all()`).
    pub fn new_all() -> Self {
        Self::new(Self::all())
    }

    /// New condition matching anything (`any()`).
    pub fn new_any() -> Self {
        Self::new(Self::any())
    }

    /// Append one sort expression; later calls take precedence for ties.
    pub fn add_sort(mut self, col: SimpleExpr, sort: Order) -> Self {
        self.order.push((col, sort));
        self
    }

    /// Attach SQL pagination.
    pub fn add_page(mut self, page: PaginationParam) -> Self {
        self.page = Some(page);
        self
    }

    /// Parse the sort string when present, see [`Condition::parse_sort`].
    pub fn parse_sort_option(mut self, str: &Option<String>, col: Vec<ColumnRef>) -> Self {
        if let Some(str) = str {
            self = self.parse_sort(str, col)
        }
        self
    }

    /// Parse a sort string like `-created_at,+name` into sort expressions.
    ///
    /// `-`/`+` prefixes select descending/ascending order (no prefix =
    /// ascending); names not present in the `col` whitelist are silently
    /// ignored, so this is safe to feed straight from user input.
    pub fn parse_sort(mut self, str: &str, col: Vec<ColumnRef>) -> Self {
        let mut allow: BTreeMap<String, ColumnRef> = col
            .into_iter()
            .map(|x| (x.column().unwrap().to_string(), x))
            .collect();
        for i in str.split(',') {
            let order = if i.starts_with('-') {
                Order::Desc
            } else {
                Order::Asc
            };
            let name = i
                .strip_prefix('+')
                .or_else(|| i.strip_prefix('-'))
                .unwrap_or(i);
            if let Some(x) = allow.remove(name) {
                self = self.add_sort(SimpleExpr::Column(x), order);
            }
        }
        self
    }

    /// Shortcut of [`sea_orm::Condition::any`].
    pub fn any() -> sea_orm::Condition {
        sea_orm::Condition::any()
    }

    /// Shortcut of [`sea_orm::Condition::all`].
    pub fn all() -> sea_orm::Condition {
        sea_orm::Condition::all()
    }

    /// AND one more condition.
    #[allow(clippy::should_implement_trait)]
    pub fn add<C>(mut self, condition: C) -> Self
    where
        C: Into<sea_orm::Condition>,
    {
        self.cond = self.cond.add(condition.into());
        self
    }

    /// AND one more condition, ignored when `None`.
    pub fn add_option<C>(mut self, condition: Option<C>) -> Self
    where
        C: Into<sea_orm::Condition>,
    {
        self.cond = self.cond.add_option(condition);
        self
    }

    /// Apply the sort order and filters to a `Select`.
    ///
    /// Returns the built query together with the detached pagination, ready
    /// for [`SelectPage::select_page`].
    pub fn build<E>(self, mut q: Select<E>) -> (Select<E>, Option<PaginationParam>)
    where
        E: EntityTrait,
    {
        for i in self.order {
            q = q.order_by(i.0, i.1);
        }
        (q.filter(self.cond), self.page)
    }

    /// [`Condition::build`] + [`SelectPage::select_page`] in one call;
    /// returns `(items, total_count)`.
    pub async fn select_page<M, E, C>(self, q: Select<E>, db: &C) -> Result<(Vec<E::Model>, u64)>
    where
        E: EntityTrait<Model = M>,
        M: FromQueryResult + Sized + Send + Sync,
        C: ConnectionTrait,
    {
        let (q, page) = self.build(q);
        q.select_page(db, page).await
    }

    /// Add created/updated time range filters from [`TimeParam`], using the
    /// columns provided by [`DefaultColumnTrait`] (usually implemented by the
    /// `entity_timestamp` macro).
    #[cfg(feature = "entity")]
    pub fn add_time<T>(mut self, p: &TimeParam) -> Self
    where
        T: DefaultColumnTrait,
    {
        self = self.add_option(p.created_start.map(|x| T::get_created_at().gte(x)));
        self = self.add_option(p.created_end.map(|x| T::get_created_at().lte(x)));
        self = self.add_option(p.updated_start.map(|x| T::get_updated_at().gte(x)));
        self = self.add_option(p.updated_end.map(|x| T::get_updated_at().lte(x)));
        self
    }
}

/// `validator` helper checking that a list contains no duplicate items.
///
/// # Errors
/// Will return `Err` when `x` has duplicate items.
pub fn unique_validator<T: Eq + Hash>(x: &Vec<T>) -> Result<(), ValidationError> {
    if utils::is_unique(x) {
        Ok(())
    } else {
        Err(ValidationError::new("not unique"))
    }
}

/// Request payload carrying a list of unique IDs.
#[derive(Debug, Validate, Deserialize)]
pub struct IDsReq {
    /// Entity IDs, must not contain duplicates.
    #[validate(custom(function = "unique_validator"))]
    pub id: Vec<HyUuid>,
}

/// Request payload carrying an optional list of unique IDs.
#[derive(Debug, Validate, Deserialize)]
pub struct OptionIDsReq {
    /// Entity IDs, must not contain duplicates.
    #[validate(custom(function = "unique_validator"))]
    pub id: Option<Vec<HyUuid>>,
}

/// Created/updated time range filters, consumed by
/// [`Condition::add_time`].
///
/// All values are UTC datetimes, the same type the `entity_timestamp`
/// macro stores, and deserialize from RFC 3339 *strings* like
/// `2024-01-01T00:00:00Z` (a timezone offset is required; non-UTC offsets
/// are converted to UTC).
#[cfg(feature = "seaorm")]
#[derive(Debug, Deserialize, Validate)]
pub struct TimeParam {
    /// `created_at >= created_start` filter.
    pub created_start: Option<DateTimeUtc>,
    /// `created_at <= created_end` filter.
    pub created_end: Option<DateTimeUtc>,

    /// `updated_at >= updated_start` filter.
    pub updated_start: Option<DateTimeUtc>,
    /// `updated_at <= updated_end` filter.
    pub updated_end: Option<DateTimeUtc>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn page_data_new() {
        let page = PageData::new((vec![1, 2, 3], 7));
        assert_eq!(page.total, 7);
        assert_eq!(page.data, vec![1, 2, 3]);
    }

    #[test]
    fn page_data_serialize() {
        let value = serde_json::to_value(PageData::new((vec!["a"], 1))).unwrap();
        assert_eq!(value, serde_json::json!({"total": 1, "data": ["a"]}));
    }

    #[test]
    fn pagination_default() {
        let p = PaginationParam::default();
        assert_eq!((p.page, p.size), (1, 10));
        assert_eq!((p.left(), p.right()), (0, 10));

        let p = PaginationParam::new();
        assert_eq!((p.page, p.size), (1, 10));
    }

    #[test]
    fn pagination_deserialize() {
        let p: PaginationParam = serde_json::from_str(r#"{"page": 2, "size": 20}"#).unwrap();
        assert_eq!((p.page, p.size), (2, 20));
        // Missing fields fall back to defaults.
        let p: PaginationParam = serde_json::from_str("{}").unwrap();
        assert_eq!((p.page, p.size), (1, 10));
        // String numbers are rejected.
        assert!(serde_json::from_str::<PaginationParam>(r#"{"page": "2"}"#).is_err());
    }

    #[test]
    fn pagination_validate() {
        // Deserialization alone does not reject out-of-range values.
        let p: PaginationParam = serde_json::from_str(r#"{"page": 0}"#).unwrap();
        assert!(p.validate().is_err());
        let p: PaginationParam = serde_json::from_str(r#"{"size": 101}"#).unwrap();
        assert!(p.validate().is_err());
        let p: PaginationParam = serde_json::from_str(r#"{"page": 5, "size": 100}"#).unwrap();
        assert!(p.validate().is_ok());
    }

    #[test]
    fn pagination_split() {
        let p = PaginationParam { page: 2, size: 3 };
        let page = p.split(vec![1, 2, 3, 4, 5, 6, 7]);
        assert_eq!(page.total, 7);
        assert_eq!(page.data, vec![4, 5, 6]);
    }

    #[test]
    fn pagination_bounds_saturate() {
        // `page: 0` (only reachable without validation) must not underflow.
        let p = PaginationParam { page: 0, size: 10 };
        assert_eq!((p.left(), p.right()), (0, 0));

        // Huge values saturate instead of overflowing.
        let p = PaginationParam {
            page: u64::MAX,
            size: 100,
        };
        assert_eq!(p.left(), u64::MAX);
        assert_eq!(p.right(), u64::MAX);
        assert_eq!(PaginationParam::round(u64::MAX), usize::MAX as usize);

        // An out-of-range window yields an empty page instead of a panic.
        let page = p.split(vec![1, 2, 3]);
        assert_eq!(page.total, 3);
        assert!(page.data.is_empty());
    }

    #[test]
    fn unique_validator_works() {
        assert!(unique_validator(&Vec::<u8>::new()).is_ok());
        assert!(unique_validator(&vec![1, 2, 3]).is_ok());
        assert!(unique_validator(&vec![1, 2, 2]).is_err());
    }

    #[test]
    fn ids_req_validate() {
        let a = HyUuid::new();
        let b = HyUuid::new();

        let req: IDsReq =
            serde_json::from_value(serde_json::json!({ "id": [a.to_string(), b.to_string()] }))
                .unwrap();
        assert!(req.validate().is_ok());

        // Duplicates pass deserialization but fail validation.
        let req: IDsReq =
            serde_json::from_value(serde_json::json!({ "id": [a.to_string(), a.to_string()] }))
                .unwrap();
        assert!(req.validate().is_err());
    }

    #[test]
    fn option_ids_req_validate() {
        let a = HyUuid::new();

        // Missing or null ids skip validation.
        let req: OptionIDsReq = serde_json::from_value(serde_json::json!({})).unwrap();
        assert!(req.id.is_none());
        assert!(req.validate().is_ok());
        let req: OptionIDsReq = serde_json::from_value(serde_json::json!({ "id": null })).unwrap();
        assert!(req.validate().is_ok());

        let req: OptionIDsReq =
            serde_json::from_value(serde_json::json!({ "id": [a.to_string()] })).unwrap();
        assert!(req.validate().is_ok());
        let req: OptionIDsReq =
            serde_json::from_value(serde_json::json!({ "id": [a.to_string(), a.to_string()] }))
                .unwrap();
        assert!(req.validate().is_err());
    }

    #[cfg(feature = "seaorm")]
    #[test]
    fn time_param_deserialize() {
        let p: TimeParam = serde_json::from_str(
            r#"{"created_start": "2024-01-01T00:00:00Z", "created_end": "2024-01-01T23:59:59.5+08:00"}"#,
        )
        .unwrap();
        assert!(p.created_start.is_some());
        assert!(p.created_end.is_some());
        assert!(p.updated_start.is_none());
        assert!(p.updated_end.is_none());
        // Non-UTC offsets are converted to UTC: 23:59:59.5+08:00 is 15:59:59.5Z.
        let expect: DateTimeUtc = "2024-01-01T15:59:59.5Z".parse().unwrap();
        assert_eq!(p.created_end.unwrap(), expect);

        // A timezone offset is required: naive strings are rejected, even
        // with the `T` separator (a space separator is accepted by RFC 3339
        // when the offset is present).
        assert!(
            serde_json::from_str::<TimeParam>(r#"{"created_start": "2024-01-01T00:00:00"}"#)
                .is_err()
        );
    }
}