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
// Payment HTTP handlers - delegate to PaymentCoordinator
// Clean Architecture: Infrastructure Layer (HTTP) -> Application Layer (Coordinator)

use crate::{
    application::{
        dto::{
            AccessTokenDto, BlockchainDto, CheckAccessRequest, CheckAccessResponse,
            ConfirmTransactionRequest, ConfirmTransactionResponse, GrantAccessResponse,
            GrantFreeAccessRequest, InitiatePaymentRequest, InitiatePaymentResponse,
            ListAccessTokensResponse, ListTransactionsResponse, RefundTransactionRequest,
            RefundTransactionResponse, TransactionDto,
        },
        services::PaymentCoordinator,
        use_cases::{ListTransactionsUseCase, RefundTransactionUseCase},
    },
    domain::{
        entities::AccessToken,
        repositories::{
            AccessTokenRepository, ArticleRepository, CreatorRepository, TransactionRepository,
        },
        value_objects::{ArticleId, TransactionId, WalletAddress},
    },
    error::Result,
};
use axum::{
    Json,
    extract::{Path, Query, State},
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Application state for payment handlers
#[derive(Clone)]
pub struct PaymentHandlerState {
    pub coordinator: Arc<PaymentCoordinator>,
    pub transaction_repo: Arc<dyn TransactionRepository>,
    pub article_repo: Arc<dyn ArticleRepository>,
    pub creator_repo: Arc<dyn CreatorRepository>,
    pub access_token_repo: Arc<dyn AccessTokenRepository>,
}

/// Query parameters for listing transactions
#[derive(Debug, Deserialize)]
pub struct ListTransactionsParams {
    pub tenant_id: Option<String>,
    pub article_id: Option<String>,
    pub creator_id: Option<String>,
    pub reader_wallet: Option<String>,
    pub limit: Option<usize>,
    pub offset: Option<usize>,
}

/// Query parameters for listing access tokens
#[derive(Debug, Deserialize)]
pub struct ListAccessTokensParams {
    pub article_id: Option<String>,
    pub wallet_address: Option<String>,
    pub limit: Option<usize>,
    pub offset: Option<usize>,
}

/// Request for extending access
#[derive(Debug, Deserialize)]
pub struct ExtendAccessRequest {
    pub additional_days: i64,
}

/// Request for recording access
#[derive(Debug, Deserialize)]
pub struct RecordAccessRequest {
    pub token_id: String,
}

/// Response for purchase operation
#[derive(Debug, Serialize)]
pub struct PurchaseResponse {
    pub status: String,
    pub transaction: Option<TransactionDto>,
    pub access_token: Option<AccessTokenDto>,
    pub already_owned: bool,
}

/// Initiate a payment for an article
///
/// POST /api/v1/payments
pub async fn initiate_payment_handler(
    State(state): State<PaymentHandlerState>,
    Json(request): Json<InitiatePaymentRequest>,
) -> Result<Json<InitiatePaymentResponse>> {
    tracing::info!(
        article_id = %request.article_id,
        reader_wallet = %request.reader_wallet,
        "Initiating payment"
    );

    let response = state.coordinator.initiate_payment(request).await?;

    tracing::info!(
        transaction_id = %response.transaction.id,
        "Payment initiated"
    );

    Ok(Json(response))
}

/// Confirm a transaction and grant access
///
/// POST /api/v1/payments/{transaction_id}/confirm
pub async fn confirm_payment_handler(
    State(state): State<PaymentHandlerState>,
    Path(transaction_id): Path<String>,
) -> Result<Json<ConfirmTransactionResponse>> {
    tracing::info!(
        transaction_id = %transaction_id,
        "Confirming payment"
    );

    let response = state
        .coordinator
        .confirm_and_grant_access(ConfirmTransactionRequest {
            transaction_id: transaction_id.clone(),
        })
        .await?;

    tracing::info!(
        transaction_id = %transaction_id,
        "Payment confirmed"
    );

    Ok(Json(response))
}

/// Check if a user has access to an article
///
/// POST /api/v1/access/check
pub async fn check_access_handler(
    State(state): State<PaymentHandlerState>,
    Json(request): Json<CheckAccessRequest>,
) -> Result<Json<CheckAccessResponse>> {
    let response = state.coordinator.check_access(request).await?;
    Ok(Json(response))
}

/// Purchase an article (full flow: check -> pay -> confirm -> grant)
///
/// POST /api/v1/articles/{article_id}/purchase
#[derive(Debug, Deserialize)]
pub struct PurchaseArticleRequest {
    pub reader_wallet: String,
    pub tx_signature: String,
    pub blockchain: Option<BlockchainDto>,
}

#[derive(Debug, Deserialize)]
pub struct TenantIdParam {
    pub tenant_id: Option<String>,
}

pub async fn purchase_article_handler(
    State(state): State<PaymentHandlerState>,
    Path(article_id): Path<String>,
    Query(tenant_id): Query<TenantIdParam>,
    Json(request): Json<PurchaseArticleRequest>,
) -> Result<Json<PurchaseResponse>> {
    use crate::application::services::PurchaseResult;

    let tenant = tenant_id.tenant_id.unwrap_or_else(|| "default".to_string());

    tracing::info!(
        article_id = %article_id,
        reader_wallet = %request.reader_wallet,
        "Processing article purchase"
    );

    let result = state
        .coordinator
        .purchase_article(
            &tenant,
            &article_id,
            &request.reader_wallet,
            &request.tx_signature,
            request.blockchain,
        )
        .await?;

    let response = match result {
        PurchaseResult::AlreadyOwned { access_token } => PurchaseResponse {
            status: "already_owned".to_string(),
            transaction: None,
            access_token,
            already_owned: true,
        },
        PurchaseResult::Purchased {
            transaction,
            access_token_id: _,
        } => PurchaseResponse {
            status: "purchased".to_string(),
            transaction: Some(transaction),
            access_token: None,
            already_owned: false,
        },
    };

    Ok(Json(response))
}

/// List transactions with filtering
///
/// GET /api/v1/transactions
pub async fn list_transactions_handler(
    State(state): State<PaymentHandlerState>,
    Query(params): Query<ListTransactionsParams>,
) -> Result<Json<ListTransactionsResponse>> {
    let limit = params.limit.unwrap_or(100);
    let offset = params.offset.unwrap_or(0);

    // Build query based on parameters
    let transactions = if let Some(article_id_str) = params.article_id {
        let article_id = ArticleId::new(article_id_str)?;
        state
            .transaction_repo
            .find_by_article(&article_id, limit, offset)
            .await?
    } else if let Some(creator_id_str) = params.creator_id {
        let creator_id = crate::domain::value_objects::CreatorId::parse(&creator_id_str)?;
        state
            .transaction_repo
            .find_by_creator(&creator_id, limit, offset)
            .await?
    } else if let Some(wallet_str) = params.reader_wallet {
        let wallet = WalletAddress::new(wallet_str)?;
        state
            .transaction_repo
            .find_by_reader(&wallet, limit, offset)
            .await?
    } else {
        // Default: return recent transactions
        use crate::domain::repositories::TransactionQuery;
        let query = TransactionQuery::new().with_pagination(limit, offset);
        state.transaction_repo.query(&query).await?
    };

    let response = ListTransactionsUseCase::execute(&transactions);

    tracing::debug!(count = response.count, "Listed transactions");

    Ok(Json(response))
}

/// Get a specific transaction
///
/// GET /api/v1/transactions/{transaction_id}
pub async fn get_transaction_handler(
    State(state): State<PaymentHandlerState>,
    Path(transaction_id): Path<String>,
) -> Result<Json<TransactionDto>> {
    let id = TransactionId::parse(&transaction_id).map_err(|_| {
        crate::error::AllSourceError::InvalidInput("Invalid transaction ID".to_string())
    })?;

    let transaction = state
        .transaction_repo
        .find_by_id(&id)
        .await?
        .ok_or_else(|| {
            crate::error::AllSourceError::EntityNotFound(format!(
                "Transaction not found: {transaction_id}"
            ))
        })?;

    Ok(Json(TransactionDto::from(&transaction)))
}

/// Refund a transaction
///
/// POST /api/v1/transactions/{transaction_id}/refund
pub async fn refund_transaction_handler(
    State(state): State<PaymentHandlerState>,
    Path(transaction_id): Path<String>,
    Json(mut request): Json<RefundTransactionRequest>,
) -> Result<Json<RefundTransactionResponse>> {
    // Ensure the transaction ID matches the path parameter
    request.transaction_id = transaction_id.clone();

    let use_case = RefundTransactionUseCase::new(
        state.transaction_repo.clone(),
        state.access_token_repo.clone(),
    );

    let response = use_case.execute(request).await?;

    tracing::info!(
        transaction_id = %transaction_id,
        "Transaction refunded"
    );

    Ok(Json(response))
}

/// Grant free access to an article
///
/// POST /api/v1/access/grant-free
pub async fn grant_free_access_handler(
    State(state): State<PaymentHandlerState>,
    Json(request): Json<GrantFreeAccessRequest>,
) -> Result<Json<GrantAccessResponse>> {
    tracing::info!(
        article_id = %request.article_id,
        reader_wallet = %request.reader_wallet,
        "Granting free access"
    );

    // Validate and get article
    let article_id = ArticleId::new(request.article_id.clone())?;
    let article = state
        .article_repo
        .find_by_id(&article_id)
        .await?
        .ok_or_else(|| {
            crate::error::AllSourceError::EntityNotFound("Article not found".to_string())
        })?;

    // Parse tenant and wallet
    let tenant_id = crate::domain::value_objects::TenantId::new(request.tenant_id)?;
    let wallet = WalletAddress::new(request.reader_wallet)?;

    // Generate token hash
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(article_id.to_string().as_bytes());
    hasher.update(wallet.to_string().as_bytes());
    hasher.update(chrono::Utc::now().to_rfc3339().as_bytes());
    let token_hash = format!("{:x}", hasher.finalize());

    // Create access token with specified duration
    let duration_days = request.duration_days.unwrap_or(365);
    let access_token = AccessToken::new_free(
        tenant_id,
        article_id,
        *article.creator_id(),
        wallet,
        token_hash.clone(),
        duration_days,
    )?;

    // Save access token
    state.access_token_repo.save(&access_token).await?;

    tracing::info!(
        access_token_id = %access_token.id().as_uuid(),
        "Free access granted"
    );

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

/// List access tokens with filtering
///
/// GET /api/v1/access/tokens
pub async fn list_access_tokens_handler(
    State(state): State<PaymentHandlerState>,
    Query(params): Query<ListAccessTokensParams>,
) -> Result<Json<ListAccessTokensResponse>> {
    let limit = params.limit.unwrap_or(100);
    let offset = params.offset.unwrap_or(0);

    let tokens = if let Some(article_id_str) = params.article_id {
        let article_id = ArticleId::new(article_id_str)?;
        state
            .access_token_repo
            .find_by_article(&article_id, limit, offset)
            .await?
    } else if let Some(wallet_str) = params.wallet_address {
        let wallet = WalletAddress::new(wallet_str)?;
        state
            .access_token_repo
            .find_by_reader(&wallet, limit, offset)
            .await?
    } else {
        // Default: use query with pagination
        use crate::domain::repositories::AccessTokenQuery;
        let query = AccessTokenQuery::new().with_pagination(limit, offset);
        state.access_token_repo.query(&query).await?
    };

    let token_dtos: Vec<AccessTokenDto> = tokens.iter().map(AccessTokenDto::from).collect();
    let count = token_dtos.len();

    tracing::debug!(count = count, "Listed access tokens");

    Ok(Json(ListAccessTokensResponse {
        tokens: token_dtos,
        count,
    }))
}

/// Get a specific access token
///
/// GET /api/v1/access/tokens/{token_id}
pub async fn get_access_token_handler(
    State(state): State<PaymentHandlerState>,
    Path(token_id): Path<String>,
) -> Result<Json<AccessTokenDto>> {
    let id = uuid::Uuid::parse_str(&token_id)
        .map_err(|_| crate::error::AllSourceError::InvalidInput("Invalid token ID".to_string()))?;

    let token = state
        .access_token_repo
        .find_by_id(&crate::domain::entities::AccessTokenId::from_uuid(id))
        .await?
        .ok_or_else(|| {
            crate::error::AllSourceError::EntityNotFound(format!(
                "Access token not found: {token_id}"
            ))
        })?;

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

/// Revoke an access token
///
/// POST /api/v1/access/tokens/{token_id}/revoke
#[derive(Debug, Deserialize)]
pub struct RevokeAccessHandlerRequest {
    pub reason: String,
}

pub async fn revoke_access_handler(
    State(state): State<PaymentHandlerState>,
    Path(token_id): Path<String>,
    Json(request): Json<RevokeAccessHandlerRequest>,
) -> Result<Json<serde_json::Value>> {
    let id = uuid::Uuid::parse_str(&token_id)
        .map_err(|_| crate::error::AllSourceError::InvalidInput("Invalid token ID".to_string()))?;

    let revoked = state
        .access_token_repo
        .revoke(
            &crate::domain::entities::AccessTokenId::from_uuid(id),
            &request.reason,
        )
        .await?;

    tracing::info!(
        token_id = %token_id,
        revoked = revoked,
        "Access token revoke attempted"
    );

    Ok(Json(serde_json::json!({
        "revoked": revoked,
        "token_id": token_id
    })))
}

/// Cleanup expired access tokens
///
/// POST /api/v1/access/cleanup
pub async fn cleanup_expired_tokens_handler(
    State(state): State<PaymentHandlerState>,
) -> Result<Json<serde_json::Value>> {
    let count = state
        .access_token_repo
        .delete_expired(chrono::Utc::now())
        .await?;

    tracing::info!(tokens_cleaned = count, "Expired tokens cleaned up");

    Ok(Json(serde_json::json!({
        "tokens_cleaned": count
    })))
}

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

    #[test]
    fn test_list_transactions_params_default() {
        let json = r"{}";
        let params: ListTransactionsParams = serde_json::from_str(json).unwrap();
        assert!(params.tenant_id.is_none());
        assert!(params.article_id.is_none());
    }

    #[test]
    fn test_list_access_tokens_params() {
        let json = r#"{"article_id": "art-123", "limit": 10}"#;
        let params: ListAccessTokensParams = serde_json::from_str(json).unwrap();
        assert_eq!(params.article_id, Some("art-123".to_string()));
        assert_eq!(params.limit, Some(10));
    }

    #[test]
    fn test_purchase_response_serialization() {
        let response = PurchaseResponse {
            status: "purchased".to_string(),
            transaction: None,
            access_token: None,
            already_owned: false,
        };
        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("purchased"));
        assert!(json.contains("\"already_owned\":false"));
    }
}