raisfast 0.2.23

The last backend you'll ever need. Rust-powered headless CMS with built-in blog, ecommerce, wallet, payment and 4 plugin engines.
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
604
605
606
607
608
609
610
611
612
613
614
615
616
//! AOP cross-cutting infrastructure
//!
//! Aspect-Oriented Programming framework providing unified cross-cutting abstractions.
//! All data paths (Content Type CRUD, built-in table Services) share the same Aspect dispatch.
//!
//! Four-layer model:
//! - HTTP Layer — request/response interception (Phase 5)
//! - Access Layer — route-level + data-level permissions (Phase 5)
//! - Data Layer — pre/post CRUD interception (core layer, Phase 1)
//! - Event Layer — event publish/consume interception (Phase 3)

pub mod engine;
pub mod excerpt_aspect;
pub mod slug_aspect;

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use serde_json::Value;

use crate::content_type::schema::ContentTypeSchema;

// ─── Layer / Operation / When ───

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Layer {
    Http,
    Access,
    Data,
    Event,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Operation {
    Create,
    Read,
    Update,
    Delete,
    Publish,
    Consume,
    Check,
    Filter,
    Request,
    Response,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum When {
    Before,
    After,
}

// ─── JoinPointId ───

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct JoinPointId {
    pub layer: Layer,
    pub operation: Operation,
    pub when: When,
}

// ─── Pointcut ───

#[derive(Debug, Clone)]
pub enum TargetMatcher {
    All,
    Tables(Vec<String>),
}

#[derive(Debug, Clone)]
pub struct Pointcut {
    pub layer: Layer,
    pub operation: Operation,
    pub when: When,
    pub target: TargetMatcher,
}

impl Pointcut {
    fn join_point_id(&self) -> JoinPointId {
        JoinPointId {
            layer: self.layer,
            operation: self.operation,
            when: self.when,
        }
    }
}

// ─── Advice ───

#[derive(Debug)]
pub enum Advice {
    Continue,
    /// Skip remaining Aspects, but the original operation continues (like loop's break).
    /// Use case: skip subsequent Aspect data processing on cache hit.
    Skip,
    Return(Value),
}

pub type AspectResult = Result<Advice, anyhow::Error>;

// ─── Extensions ───

pub struct Extensions {
    map: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

impl Clone for Extensions {
    fn clone(&self) -> Self {
        Self {
            map: HashMap::new(),
        }
    }
}

impl Extensions {
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
        }
    }

    pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) {
        self.map.insert(TypeId::of::<T>(), Box::new(val));
    }

    pub fn get<T: 'static>(&self) -> Option<&T> {
        self.map
            .get(&TypeId::of::<T>())
            .and_then(|v| v.downcast_ref::<T>())
    }

    pub fn remove<T: 'static>(&mut self) -> Option<T> {
        self.map
            .remove(&TypeId::of::<T>())
            .and_then(|v| v.downcast::<T>().ok())
            .map(|b| *b)
    }
}

impl Default for Extensions {
    fn default() -> Self {
        Self::new()
    }
}

// ─── BaseContext ───

#[derive(Clone)]
pub struct BaseContext {
    pub user_id: Option<String>,
    pub user_int_id: Option<i64>,
    pub user_role: Option<String>,
    pub tenant_id: String,
    pub now: String,
    pub request_id: String,
    pub extensions: Extensions,
    pub pool: Option<crate::db::pool::Pool>,
}

impl BaseContext {
    pub fn new(user_id: Option<String>, tenant_id: String, now: String) -> Self {
        Self {
            user_id,
            user_int_id: None,
            user_role: None,
            tenant_id,
            now,
            request_id: String::new(),
            extensions: Extensions::new(),
            pool: None,
        }
    }

    pub fn with_pool(mut self, pool: crate::db::pool::Pool) -> Self {
        self.pool = Some(pool);
        self
    }

    pub fn with_user_int_id(mut self, user_int_id: Option<i64>) -> Self {
        self.user_int_id = user_int_id;
        self
    }
}

// ─── Data Layer Contexts ───

pub type Record = serde_json::Map<String, Value>;

/// Result of an aspect data dispatch, with convenience methods for reading fields.
pub struct Dispatched(pub Record);

impl Dispatched {
    pub fn str(&self, key: &str) -> Option<String> {
        self.0
            .get(key)
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    }

    pub fn str_or<F: FnOnce() -> String>(&self, key: &str, default: F) -> String {
        self.str(key).unwrap_or_else(default)
    }
}

pub struct DataBeforeCreateContext {
    pub base: BaseContext,
    pub table: String,
    pub record: Record,
    pub schema: Option<Arc<ContentTypeSchema>>,
}

pub struct DataAfterCreateContext {
    pub base: BaseContext,
    pub table: String,
    pub record: Record,
    pub schema: Option<Arc<ContentTypeSchema>>,
}

pub struct DataBeforeReadContext {
    pub base: BaseContext,
    pub table: String,
    pub query: ReadQuery,
    pub schema: Option<Arc<ContentTypeSchema>>,
}

pub struct DataAfterReadContext {
    pub base: BaseContext,
    pub table: String,
    pub records: Vec<Record>,
    pub schema: Option<Arc<ContentTypeSchema>>,
}

pub struct DataBeforeUpdateContext {
    pub base: BaseContext,
    pub table: String,
    pub old_record: Record,
    pub new_record: Record,
    pub schema: Option<Arc<ContentTypeSchema>>,
}

pub struct DataAfterUpdateContext {
    pub base: BaseContext,
    pub table: String,
    pub old_record: Record,
    pub new_record: Record,
    pub schema: Option<Arc<ContentTypeSchema>>,
}

pub struct DataBeforeDeleteContext {
    pub base: BaseContext,
    pub table: String,
    pub record: Record,
    pub soft_delete: bool,
    pub schema: Option<Arc<ContentTypeSchema>>,
}

pub struct DataAfterDeleteContext {
    pub base: BaseContext,
    pub table: String,
    pub record: Record,
    pub schema: Option<Arc<ContentTypeSchema>>,
}

pub struct ReadQuery {
    pub filters: Vec<(String, String)>,
    pub order_by: Option<String>,
    pub page: u64,
    pub page_size: u64,
    pub fields: Option<Vec<String>>,
}

impl Default for ReadQuery {
    fn default() -> Self {
        Self {
            filters: Vec::new(),
            order_by: None,
            page: 1,
            page_size: 25,
            fields: None,
        }
    }
}

// ─── Access Layer Contexts ───

pub struct AccessCheckContext {
    pub base: BaseContext,
    pub route: String,
    pub method: String,
    pub table: Option<String>,
    pub action: String,
}

pub struct AccessFilterContext {
    pub base: BaseContext,
    pub table: String,
    pub conditions: Vec<String>,
    pub params: Vec<String>,
}

// ─── Event Layer Context ───

pub struct EventContext {
    pub base: BaseContext,
    pub event_type: String,
    pub payload: Value,
    pub table: Option<String>,
}

// ─── HTTP Layer Contexts ───

pub struct HttpBeforeContext {
    pub base: BaseContext,
    pub method: String,
    pub path: String,
    pub headers: HashMap<String, String>,
}

pub struct HttpAfterContext {
    pub base: BaseContext,
    pub status_code: u16,
    pub response_body: Option<Value>,
}

// ─── SqlType (re-export) ───

pub use crate::db::sql_type::SqlType;

// ─── ColumnDef ───

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnDef {
    pub name: String,
    pub sql_type: SqlType,
    pub default: Option<String>,
}

// ─── Aspect Trait ───

#[async_trait]
pub trait Aspect: Send + Sync + 'static {
    fn name(&self) -> &str;

    fn priority(&self) -> i32 {
        0
    }

    fn pointcuts(&self) -> Vec<Pointcut>;

    fn columns(&self) -> Vec<ColumnDef> {
        vec![]
    }

    // ─── Data Layer ───

    async fn on_data_before_create(&self, _ctx: &mut DataBeforeCreateContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_data_after_create(&self, _ctx: &mut DataAfterCreateContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_data_before_read(&self, _ctx: &mut DataBeforeReadContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_data_after_read(&self, _ctx: &mut DataAfterReadContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_data_before_update(&self, _ctx: &mut DataBeforeUpdateContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_data_after_update(&self, _ctx: &mut DataAfterUpdateContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_data_before_delete(&self, _ctx: &mut DataBeforeDeleteContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_data_after_delete(&self, _ctx: &mut DataAfterDeleteContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    // ─── Access Layer ───

    async fn on_access_check(&self, _ctx: &mut AccessCheckContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_access_filter(&self, _ctx: &mut AccessFilterContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    // ─── Event Layer ───

    async fn on_event_before_publish(&self, _ctx: &mut EventContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_event_after_publish(&self, _ctx: &mut EventContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_event_before_consume(&self, _ctx: &mut EventContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_event_after_consume(&self, _ctx: &mut EventContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    // ─── HTTP Layer ───

    async fn on_http_before(&self, _ctx: &mut HttpBeforeContext) -> AspectResult {
        Ok(Advice::Continue)
    }

    async fn on_http_after(&self, _ctx: &mut HttpAfterContext) -> AspectResult {
        Ok(Advice::Continue)
    }
}

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

    #[test]
    fn extensions_insert_get_remove() {
        let mut ext = Extensions::new();
        assert!(ext.get::<String>().is_none());

        ext.insert::<String>("hello".into());
        assert_eq!(ext.get::<String>().unwrap(), "hello");

        let removed = ext.remove::<String>();
        assert_eq!(removed.unwrap(), "hello");
        assert!(ext.get::<String>().is_none());
    }

    #[test]
    fn extensions_different_types() {
        let mut ext = Extensions::new();
        ext.insert::<i32>(42);
        ext.insert::<String>("world".into());
        assert_eq!(*ext.get::<i32>().unwrap(), 42);
        assert_eq!(ext.get::<String>().unwrap(), "world");
    }

    #[test]
    fn extensions_overwrite() {
        let mut ext = Extensions::new();
        ext.insert::<i32>(1);
        ext.insert::<i32>(2);
        assert_eq!(*ext.get::<i32>().unwrap(), 2);
    }

    #[test]
    fn extensions_remove_missing() {
        let mut ext = Extensions::new();
        assert!(ext.remove::<i32>().is_none());
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct OwnableData {
        created_by: String,
    }

    #[test]
    fn extensions_custom_type() {
        let mut ext = Extensions::new();
        ext.insert(OwnableData {
            created_by: "user-1".into(),
        });
        let data = ext.get::<OwnableData>().unwrap();
        assert_eq!(data.created_by, "user-1");
    }

    #[test]
    fn base_context_construction() {
        let ctx = BaseContext::new(
            Some("user-1".into()),
            "tenant-1".into(),
            "2026-01-01T00:00:00Z".into(),
        );
        assert_eq!(ctx.user_id.as_deref(), Some("user-1"));
        assert_eq!(ctx.tenant_id, "tenant-1");
        assert_eq!(ctx.now, "2026-01-01T00:00:00Z");
        assert!(ctx.user_role.is_none());
        assert!(ctx.request_id.is_empty());
    }

    #[test]
    fn base_context_with_extensions() {
        let mut ctx = BaseContext::new(None, "default".into(), "now".into());
        ctx.extensions.insert::<String>("test-value".into());
        assert_eq!(ctx.extensions.get::<String>().unwrap(), "test-value");
    }

    #[test]
    fn join_point_id_equality() {
        let a = JoinPointId {
            layer: Layer::Data,
            operation: Operation::Create,
            when: When::Before,
        };
        let b = JoinPointId {
            layer: Layer::Data,
            operation: Operation::Create,
            when: When::Before,
        };
        let c = JoinPointId {
            layer: Layer::Data,
            operation: Operation::Create,
            when: When::After,
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn join_point_id_hash() {
        use std::collections::HashSet;
        let a = JoinPointId {
            layer: Layer::Data,
            operation: Operation::Create,
            when: When::Before,
        };
        let b = JoinPointId {
            layer: Layer::Data,
            operation: Operation::Create,
            when: When::Before,
        };
        let mut set = HashSet::new();
        set.insert(a.clone());
        assert!(set.contains(&b));
    }

    #[test]
    fn pointcut_join_point_id() {
        let pc = Pointcut {
            layer: Layer::Data,
            operation: Operation::Update,
            when: When::After,
            target: TargetMatcher::All,
        };
        let jpid = pc.join_point_id();
        assert_eq!(jpid.layer, Layer::Data);
        assert_eq!(jpid.operation, Operation::Update);
        assert_eq!(jpid.when, When::After);
    }

    #[test]
    fn layer_operation_when_variants() {
        assert_ne!(Layer::Http, Layer::Data);
        assert_ne!(Operation::Create, Operation::Read);
        assert_ne!(When::Before, When::After);
    }

    #[test]
    fn read_query_default() {
        let q = ReadQuery::default();
        assert!(q.filters.is_empty());
        assert!(q.order_by.is_none());
        assert_eq!(q.page, 1);
        assert_eq!(q.page_size, 25);
        assert!(q.fields.is_none());
    }

    #[test]
    fn column_def_construction() {
        let col = ColumnDef {
            name: "created_by".into(),
            sql_type: SqlType::Text,
            default: None,
        };
        assert_eq!(col.name, "created_by");
        assert_eq!(col.sql_type, SqlType::Text);
        assert_eq!(col.sql_type.as_str(), "TEXT");
        assert!(col.default.is_none());
    }

    #[test]
    fn sql_type_as_str() {
        assert_eq!(SqlType::Text.as_str(), "TEXT");
        assert_eq!(SqlType::Integer.as_str(), "INTEGER");
        assert_eq!(SqlType::Boolean.as_str(), "BOOLEAN");
    }

    #[test]
    fn advice_variants() {
        let a = Advice::Continue;
        let b = Advice::Skip;
        let c = Advice::Return(serde_json::json!({"key": "val"}));
        assert!(matches!(a, Advice::Continue));
        assert!(matches!(b, Advice::Skip));
        assert!(matches!(c, Advice::Return(_)));
    }

    #[test]
    fn record_operations() {
        let mut r = Record::new();
        r.insert("id".into(), serde_json::json!("abc"));
        r.insert("count".into(), serde_json::json!(42));
        assert_eq!(r.get("id").unwrap(), &serde_json::json!("abc"));
        assert_eq!(r.get("count").unwrap(), &serde_json::json!(42));
        assert!(r.get("missing").is_none());
        r.remove("count");
        assert!(r.get("count").is_none());
    }
}