allsource-core 0.19.1

High-performance event store core built in Rust
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
use crate::{
    application::dto::{
        AccessTokenDto, CheckAccessRequest, CheckAccessResponse, GrantAccessResponse,
        GrantFreeAccessRequest, ListAccessTokensResponse, RevokeAccessRequest,
        RevokeAccessResponse,
    },
    domain::{
        entities::{AccessToken, AccessTokenId},
        repositories::{AccessTokenRepository, ArticleRepository},
        value_objects::{ArticleId, WalletAddress},
    },
    error::Result,
};
use sha2::{Digest, Sha256};
use std::sync::Arc;

/// Use Case: Grant Free Access
///
/// Grants free (promotional) access to an article for a reader.
/// This is used for promotional access, reviewer access, etc.
///
/// Responsibilities:
/// - Validate input
/// - Verify article exists
/// - Check for existing valid access
/// - Create access token
/// - Persist via repository
/// - Return response with raw token
pub struct GrantFreeAccessUseCase {
    access_token_repository: Arc<dyn AccessTokenRepository>,
    article_repository: Arc<dyn ArticleRepository>,
}

impl GrantFreeAccessUseCase {
    pub fn new(
        access_token_repository: Arc<dyn AccessTokenRepository>,
        article_repository: Arc<dyn ArticleRepository>,
    ) -> Self {
        Self {
            access_token_repository,
            article_repository,
        }
    }

    pub async fn execute(&self, request: GrantFreeAccessRequest) -> Result<GrantAccessResponse> {
        // Parse IDs
        let article_id = ArticleId::new(request.article_id)?;
        let reader_wallet = WalletAddress::new(request.reader_wallet)?;
        let tenant_id = crate::domain::value_objects::TenantId::new(request.tenant_id)?;

        // Verify article exists
        let article = self
            .article_repository
            .find_by_id(&article_id)
            .await?
            .ok_or_else(|| {
                crate::error::AllSourceError::EntityNotFound("Article not found".to_string())
            })?;

        // Check for existing valid access
        if self
            .access_token_repository
            .has_valid_access(&article_id, &reader_wallet)
            .await?
        {
            return Err(crate::error::AllSourceError::ValidationError(
                "Reader already has valid access to this article".to_string(),
            ));
        }

        // Duration defaults to 30 days
        let duration_days = request.duration_days.unwrap_or(30);

        // Generate token hash
        let raw_token = generate_raw_token(&article_id, &reader_wallet);
        let token_hash = hash_token(&raw_token);

        // Create access token
        let access_token = AccessToken::new_free(
            tenant_id,
            article_id,
            *article.creator_id(),
            reader_wallet,
            token_hash,
            duration_days,
        )?;

        // Persist access token
        self.access_token_repository.save(&access_token).await?;

        Ok(GrantAccessResponse {
            access_token: AccessTokenDto::from(&access_token),
            raw_token,
        })
    }
}

/// Use Case: Check Access
///
/// Checks if a reader has valid access to an article.
pub struct CheckAccessUseCase {
    repository: Arc<dyn AccessTokenRepository>,
}

impl CheckAccessUseCase {
    pub fn new(repository: Arc<dyn AccessTokenRepository>) -> Self {
        Self { repository }
    }

    pub async fn execute(&self, request: CheckAccessRequest) -> Result<CheckAccessResponse> {
        let article_id = ArticleId::new(request.article_id)?;
        let wallet = WalletAddress::new(request.wallet_address)?;

        let token = self
            .repository
            .find_valid_token(&article_id, &wallet)
            .await?;

        match token {
            Some(token) => Ok(CheckAccessResponse {
                has_access: true,
                remaining_days: Some(token.remaining_days()),
                access_token: Some(AccessTokenDto::from(&token)),
            }),
            None => Ok(CheckAccessResponse {
                has_access: false,
                remaining_days: None,
                access_token: None,
            }),
        }
    }
}

/// Use Case: Validate Token
///
/// Validates a raw access token and records access if valid.
pub struct ValidateTokenUseCase {
    repository: Arc<dyn AccessTokenRepository>,
}

impl ValidateTokenUseCase {
    pub fn new(repository: Arc<dyn AccessTokenRepository>) -> Self {
        Self { repository }
    }

    pub async fn execute(
        &self,
        raw_token: &str,
        article_id: &str,
        wallet_address: &str,
    ) -> Result<AccessTokenDto> {
        let article_id = ArticleId::new(article_id.to_string())?;
        let wallet = WalletAddress::new(wallet_address.to_string())?;

        // Hash the raw token
        let token_hash = hash_token(raw_token);

        // Find token by hash
        let mut token = self
            .repository
            .find_by_hash(&token_hash)
            .await?
            .ok_or_else(|| {
                crate::error::AllSourceError::EntityNotFound("Token not found".to_string())
            })?;

        // Verify token grants access to this article and wallet
        if !token.grants_access_to(&article_id, &wallet) {
            return Err(crate::error::AllSourceError::ValidationError(
                "Token does not grant access to this article".to_string(),
            ));
        }

        // Record access
        token.record_access();

        // Note: In a real implementation, we would save the updated token here
        // For now, we return the DTO with the recorded access

        Ok(AccessTokenDto::from(&token))
    }
}

/// Use Case: Revoke Access
///
/// Revokes an access token.
pub struct RevokeAccessUseCase {
    repository: Arc<dyn AccessTokenRepository>,
}

impl RevokeAccessUseCase {
    pub fn new(repository: Arc<dyn AccessTokenRepository>) -> Self {
        Self { repository }
    }

    pub async fn execute(&self, request: RevokeAccessRequest) -> Result<RevokeAccessResponse> {
        let token_id = AccessTokenId::parse(&request.token_id)?;

        // Find token
        let mut token = self
            .repository
            .find_by_id(&token_id)
            .await?
            .ok_or_else(|| {
                crate::error::AllSourceError::EntityNotFound("Token not found".to_string())
            })?;

        // Revoke token
        token.revoke(&request.reason)?;

        // Persist via repository
        let revoked = self.repository.revoke(&token_id, &request.reason).await?;

        Ok(RevokeAccessResponse {
            revoked,
            access_token: AccessTokenDto::from(&token),
        })
    }
}

/// Use Case: Extend Access
///
/// Extends the duration of an access token.
pub struct ExtendAccessUseCase;

impl ExtendAccessUseCase {
    pub fn execute(mut token: AccessToken, additional_days: i64) -> Result<AccessTokenDto> {
        token.extend(additional_days)?;
        Ok(AccessTokenDto::from(&token))
    }
}

/// Use Case: Record Access
///
/// Records that an access token was used.
pub struct RecordAccessUseCase;

impl RecordAccessUseCase {
    pub fn execute(mut token: AccessToken) -> AccessTokenDto {
        token.record_access();
        AccessTokenDto::from(&token)
    }
}

/// Use Case: List Access Tokens
///
/// Returns a list of access tokens.
pub struct ListAccessTokensUseCase;

impl ListAccessTokensUseCase {
    pub fn execute(tokens: &[AccessToken]) -> ListAccessTokensResponse {
        let token_dtos: Vec<AccessTokenDto> = tokens.iter().map(AccessTokenDto::from).collect();
        let count = token_dtos.len();

        ListAccessTokensResponse {
            tokens: token_dtos,
            count,
        }
    }
}

/// Use Case: Cleanup Expired Tokens
///
/// Deletes expired tokens for cleanup.
pub struct CleanupExpiredTokensUseCase {
    repository: Arc<dyn AccessTokenRepository>,
}

impl CleanupExpiredTokensUseCase {
    pub fn new(repository: Arc<dyn AccessTokenRepository>) -> Self {
        Self { repository }
    }

    pub async fn execute(&self, before: chrono::DateTime<chrono::Utc>) -> Result<usize> {
        self.repository.delete_expired(before).await
    }
}

/// Generate a raw token for access
fn generate_raw_token(article_id: &ArticleId, wallet: &WalletAddress) -> String {
    use rand::RngExt;
    let random_bytes: [u8; 32] = rand::rng().random();
    let mut hasher = Sha256::new();
    hasher.update(article_id.to_string().as_bytes());
    hasher.update(wallet.to_string().as_bytes());
    hasher.update(random_bytes);
    hasher.update(chrono::Utc::now().to_rfc3339().as_bytes());
    format!("{:x}", hasher.finalize())
}

/// Hash a raw token for storage
fn hash_token(raw_token: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(raw_token.as_bytes());
    format!("{:x}", hasher.finalize())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{
        entities::PaywallArticle,
        repositories::{AccessTokenQuery, ArticleQuery},
        value_objects::{CreatorId, TenantId, TransactionId},
    };
    use async_trait::async_trait;
    use chrono::{DateTime, Utc};
    use std::sync::Mutex;

    const VALID_WALLET: &str = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
    const VALID_TOKEN_HASH: &str =
        "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd";

    struct MockAccessTokenRepository {
        tokens: Mutex<Vec<AccessToken>>,
    }

    impl MockAccessTokenRepository {
        fn new() -> Self {
            Self {
                tokens: Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait]
    impl AccessTokenRepository for MockAccessTokenRepository {
        async fn save(&self, token: &AccessToken) -> Result<()> {
            self.tokens.lock().unwrap().push(token.clone());
            Ok(())
        }

        async fn find_by_id(&self, id: &AccessTokenId) -> Result<Option<AccessToken>> {
            let tokens = self.tokens.lock().unwrap();
            Ok(tokens.iter().find(|t| t.id() == id).cloned())
        }

        async fn find_by_hash(&self, token_hash: &str) -> Result<Option<AccessToken>> {
            let tokens = self.tokens.lock().unwrap();
            Ok(tokens
                .iter()
                .find(|t| t.token_hash() == token_hash)
                .cloned())
        }

        async fn find_by_transaction(
            &self,
            _transaction_id: &TransactionId,
        ) -> Result<Option<AccessToken>> {
            Ok(None)
        }

        async fn find_by_article_and_wallet(
            &self,
            article_id: &ArticleId,
            wallet: &WalletAddress,
        ) -> Result<Vec<AccessToken>> {
            let tokens = self.tokens.lock().unwrap();
            Ok(tokens
                .iter()
                .filter(|t| t.article_id() == article_id && t.reader_wallet() == wallet)
                .cloned()
                .collect())
        }

        async fn find_valid_token(
            &self,
            article_id: &ArticleId,
            wallet: &WalletAddress,
        ) -> Result<Option<AccessToken>> {
            let tokens = self.tokens.lock().unwrap();
            Ok(tokens
                .iter()
                .find(|t| {
                    t.article_id() == article_id && t.reader_wallet() == wallet && t.is_valid()
                })
                .cloned())
        }

        async fn find_by_reader(
            &self,
            _wallet: &WalletAddress,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<AccessToken>> {
            Ok(Vec::new())
        }

        async fn find_by_article(
            &self,
            _article_id: &ArticleId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<AccessToken>> {
            Ok(Vec::new())
        }

        async fn find_by_creator(
            &self,
            _creator_id: &CreatorId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<AccessToken>> {
            Ok(Vec::new())
        }

        async fn count(&self) -> Result<usize> {
            Ok(self.tokens.lock().unwrap().len())
        }

        async fn count_valid(&self) -> Result<usize> {
            Ok(0)
        }

        async fn count_by_article(&self, _article_id: &ArticleId) -> Result<usize> {
            Ok(0)
        }

        async fn revoke(&self, _id: &AccessTokenId, _reason: &str) -> Result<bool> {
            Ok(true)
        }

        async fn revoke_by_transaction(
            &self,
            _transaction_id: &TransactionId,
            _reason: &str,
        ) -> Result<usize> {
            Ok(1)
        }

        async fn delete_expired(&self, _before: DateTime<Utc>) -> Result<usize> {
            Ok(0)
        }

        async fn query(&self, _query: &AccessTokenQuery) -> Result<Vec<AccessToken>> {
            Ok(Vec::new())
        }
    }

    struct MockArticleRepository {
        articles: Mutex<Vec<PaywallArticle>>,
    }

    impl MockArticleRepository {
        fn new() -> Self {
            Self {
                articles: Mutex::new(Vec::new()),
            }
        }

        fn add_article(&self, article: PaywallArticle) {
            self.articles.lock().unwrap().push(article);
        }
    }

    #[async_trait]
    impl ArticleRepository for MockArticleRepository {
        async fn save(&self, _article: &PaywallArticle) -> Result<()> {
            Ok(())
        }

        async fn find_by_id(&self, id: &ArticleId) -> Result<Option<PaywallArticle>> {
            let articles = self.articles.lock().unwrap();
            Ok(articles.iter().find(|a| a.id() == id).cloned())
        }

        async fn find_by_url(&self, _url: &str) -> Result<Option<PaywallArticle>> {
            Ok(None)
        }

        async fn find_by_creator(
            &self,
            _creator_id: &CreatorId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_by_tenant(
            &self,
            _tenant_id: &TenantId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_active_by_creator(
            &self,
            _creator_id: &CreatorId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_by_status(
            &self,
            _status: crate::domain::entities::ArticleStatus,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn count(&self) -> Result<usize> {
            Ok(0)
        }

        async fn count_by_creator(&self, _creator_id: &CreatorId) -> Result<usize> {
            Ok(0)
        }

        async fn count_by_status(
            &self,
            _status: crate::domain::entities::ArticleStatus,
        ) -> Result<usize> {
            Ok(0)
        }

        async fn delete(&self, _id: &ArticleId) -> Result<bool> {
            Ok(false)
        }

        async fn query(&self, _query: &ArticleQuery) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_top_by_revenue(
            &self,
            _creator_id: Option<&CreatorId>,
            _limit: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_recent(
            &self,
            _creator_id: Option<&CreatorId>,
            _limit: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }
    }

    #[tokio::test]
    async fn test_grant_free_access() {
        let token_repo = Arc::new(MockAccessTokenRepository::new());
        let article_repo = Arc::new(MockArticleRepository::new());

        // Create and add article
        let tenant_id = TenantId::new("test-tenant".to_string()).unwrap();
        let article_id = ArticleId::new("test-article".to_string()).unwrap();
        let creator_id = CreatorId::new();

        let article = PaywallArticle::new(
            article_id.clone(),
            tenant_id.clone(),
            creator_id,
            "Test Article".to_string(),
            "https://example.com/article".to_string(),
            50,
        )
        .unwrap();
        article_repo.add_article(article);

        let use_case = GrantFreeAccessUseCase::new(token_repo.clone(), article_repo);

        let request = GrantFreeAccessRequest {
            tenant_id: "test-tenant".to_string(),
            article_id: "test-article".to_string(),
            reader_wallet: VALID_WALLET.to_string(),
            duration_days: Some(7),
            reason: Some("Promotional access".to_string()),
        };

        let response = use_case.execute(request).await;
        assert!(response.is_ok());

        let response = response.unwrap();
        assert!(!response.raw_token.is_empty());
        assert!(response.access_token.is_valid);
    }

    #[tokio::test]
    async fn test_check_access_no_token() {
        let token_repo = Arc::new(MockAccessTokenRepository::new());
        let use_case = CheckAccessUseCase::new(token_repo);

        let request = CheckAccessRequest {
            article_id: "test-article".to_string(),
            wallet_address: VALID_WALLET.to_string(),
        };

        let response = use_case.execute(request).await;
        assert!(response.is_ok());

        let response = response.unwrap();
        assert!(!response.has_access);
        assert!(response.access_token.is_none());
    }

    #[tokio::test]
    async fn test_check_access_with_token() {
        let token_repo = Arc::new(MockAccessTokenRepository::new());

        // Add a valid token
        let tenant_id = TenantId::new("test-tenant".to_string()).unwrap();
        let article_id = ArticleId::new("test-article".to_string()).unwrap();
        let creator_id = CreatorId::new();
        let wallet = WalletAddress::new(VALID_WALLET.to_string()).unwrap();

        let token = AccessToken::new_free(
            tenant_id,
            article_id.clone(),
            creator_id,
            wallet.clone(),
            VALID_TOKEN_HASH.to_string(),
            30,
        )
        .unwrap();

        token_repo.save(&token).await.unwrap();

        let use_case = CheckAccessUseCase::new(token_repo);

        let request = CheckAccessRequest {
            article_id: "test-article".to_string(),
            wallet_address: VALID_WALLET.to_string(),
        };

        let response = use_case.execute(request).await;
        assert!(response.is_ok());

        let response = response.unwrap();
        assert!(response.has_access);
        assert!(response.access_token.is_some());
    }

    #[test]
    fn test_extend_access() {
        let tenant_id = TenantId::new("test-tenant".to_string()).unwrap();
        let article_id = ArticleId::new("test-article".to_string()).unwrap();
        let creator_id = CreatorId::new();
        let wallet = WalletAddress::new(VALID_WALLET.to_string()).unwrap();

        let token = AccessToken::new_free(
            tenant_id,
            article_id,
            creator_id,
            wallet,
            VALID_TOKEN_HASH.to_string(),
            7,
        )
        .unwrap();

        let original_days = token.remaining_days();

        let result = ExtendAccessUseCase::execute(token, 7);
        assert!(result.is_ok());

        let dto = result.unwrap();
        assert!(dto.remaining_days >= original_days + 6); // Allow for timing variations
    }

    #[test]
    fn test_list_access_tokens() {
        let tenant_id = TenantId::new("test-tenant".to_string()).unwrap();
        let article_id = ArticleId::new("test-article".to_string()).unwrap();
        let creator_id = CreatorId::new();
        let wallet = WalletAddress::new(VALID_WALLET.to_string()).unwrap();

        let tokens = vec![
            AccessToken::new_free(
                tenant_id,
                article_id,
                creator_id,
                wallet,
                VALID_TOKEN_HASH.to_string(),
                30,
            )
            .unwrap(),
        ];

        let response = ListAccessTokensUseCase::execute(&tokens);
        assert_eq!(response.count, 1);
        assert_eq!(response.tokens.len(), 1);
    }

    #[test]
    fn test_token_hashing() {
        let raw_token = "test_token_12345";
        let hash1 = hash_token(raw_token);
        let hash2 = hash_token(raw_token);

        // Same input should produce same hash
        assert_eq!(hash1, hash2);

        // Hash should be 64 characters (SHA-256 hex)
        assert_eq!(hash1.len(), 64);
    }
}