portalis-core 0.1.0

Core library for the Portalis Python to Rust/WASM transpiler
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
// Multi-Tenancy Quota System
// Phase 5 Week 45-46 - Resource quotas and tenant isolation

use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use sqlx::PgPool;

/// Organization resource quotas
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrganizationQuota {
    pub id: Uuid,
    pub organization_id: Uuid,
    pub max_projects: i32,
    pub max_translations_per_month: i32,
    pub max_storage_bytes: i64,
    pub max_users: i32,
    pub custom_quotas: HashMap<String, serde_json::Value>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

impl Default for OrganizationQuota {
    fn default() -> Self {
        Self {
            id: Uuid::new_v4(),
            organization_id: Uuid::new_v4(),
            max_projects: 10,
            max_translations_per_month: 100,
            max_storage_bytes: 1_073_741_824, // 1 GB
            max_users: 5,
            custom_quotas: HashMap::new(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }
}

/// Current resource usage for an organization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrganizationUsage {
    pub organization_id: Uuid,
    pub current_projects: i32,
    pub translations_this_month: i32,
    pub storage_bytes_used: i64,
    pub current_users: i32,
    pub as_of: DateTime<Utc>,
}

/// Quota check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuotaCheck {
    pub allowed: bool,
    pub quota_type: QuotaType,
    pub current: i64,
    pub limit: i64,
    pub remaining: i64,
}

/// Types of quotas
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum QuotaType {
    Projects,
    Translations,
    Storage,
    Users,
    ApiRequests,
    Custom(String),
}

impl std::fmt::Display for QuotaType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            QuotaType::Projects => write!(f, "projects"),
            QuotaType::Translations => write!(f, "translations"),
            QuotaType::Storage => write!(f, "storage"),
            QuotaType::Users => write!(f, "users"),
            QuotaType::ApiRequests => write!(f, "api_requests"),
            QuotaType::Custom(name) => write!(f, "{}", name),
        }
    }
}

/// Quota enforcement service
pub struct QuotaService {
    pool: PgPool,
}

impl QuotaService {
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    /// Get quota limits for organization
    pub async fn get_quota(
        &self,
        organization_id: Uuid,
    ) -> Result<OrganizationQuota, QuotaError> {
        let quota = sqlx::query_as!(
            OrganizationQuota,
            r#"
            SELECT
                id, organization_id, max_projects, max_translations_per_month,
                max_storage_bytes, max_users, custom_quotas as "custom_quotas!",
                created_at, updated_at
            FROM organization_quotas
            WHERE organization_id = $1
            "#,
            organization_id
        )
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| QuotaError::DatabaseError(e.to_string()))?
        .unwrap_or_else(|| {
            // Return default quota if none exists
            let mut default = OrganizationQuota::default();
            default.organization_id = organization_id;
            default
        });

        Ok(quota)
    }

    /// Get current usage for organization
    pub async fn get_usage(
        &self,
        organization_id: Uuid,
    ) -> Result<OrganizationUsage, QuotaError> {
        // Count projects
        let current_projects = sqlx::query_scalar!(
            r#"
            SELECT COUNT(*)::int as "count!"
            FROM projects
            WHERE organization_id = $1 AND deleted_at IS NULL
            "#,
            organization_id
        )
        .fetch_one(&self.pool)
        .await
        .unwrap_or(0);

        // Count translations this month
        let translations_this_month = sqlx::query_scalar!(
            r#"
            SELECT COUNT(*)::int as "count!"
            FROM translations
            WHERE organization_id = $1
              AND created_at >= DATE_TRUNC('month', NOW())
            "#,
            organization_id
        )
        .fetch_one(&self.pool)
        .await
        .unwrap_or(0);

        // Calculate storage used (placeholder - would query actual storage)
        let storage_bytes_used = 0i64;

        // Count users
        let current_users = sqlx::query_scalar!(
            r#"
            SELECT COUNT(*)::int as "count!"
            FROM organization_members
            WHERE organization_id = $1
            "#,
            organization_id
        )
        .fetch_one(&self.pool)
        .await
        .unwrap_or(0);

        Ok(OrganizationUsage {
            organization_id,
            current_projects,
            translations_this_month,
            storage_bytes_used,
            current_users,
            as_of: Utc::now(),
        })
    }

    /// Check if organization can create a new project
    pub async fn can_create_project(
        &self,
        organization_id: Uuid,
    ) -> Result<QuotaCheck, QuotaError> {
        let quota = self.get_quota(organization_id).await?;
        let usage = self.get_usage(organization_id).await?;

        let current = usage.current_projects as i64;
        let limit = quota.max_projects as i64;
        let allowed = current < limit;
        let remaining = if allowed { limit - current } else { 0 };

        Ok(QuotaCheck {
            allowed,
            quota_type: QuotaType::Projects,
            current,
            limit,
            remaining,
        })
    }

    /// Check if organization can execute a translation
    pub async fn can_execute_translation(
        &self,
        organization_id: Uuid,
    ) -> Result<QuotaCheck, QuotaError> {
        let quota = self.get_quota(organization_id).await?;
        let usage = self.get_usage(organization_id).await?;

        let current = usage.translations_this_month as i64;
        let limit = quota.max_translations_per_month as i64;
        let allowed = current < limit;
        let remaining = if allowed { limit - current } else { 0 };

        Ok(QuotaCheck {
            allowed,
            quota_type: QuotaType::Translations,
            current,
            limit,
            remaining,
        })
    }

    /// Check if organization can add a new user
    pub async fn can_add_user(
        &self,
        organization_id: Uuid,
    ) -> Result<QuotaCheck, QuotaError> {
        let quota = self.get_quota(organization_id).await?;
        let usage = self.get_usage(organization_id).await?;

        let current = usage.current_users as i64;
        let limit = quota.max_users as i64;
        let allowed = current < limit;
        let remaining = if allowed { limit - current } else { 0 };

        Ok(QuotaCheck {
            allowed,
            quota_type: QuotaType::Users,
            current,
            limit,
            remaining,
        })
    }

    /// Check storage quota
    pub async fn check_storage(
        &self,
        organization_id: Uuid,
        additional_bytes: i64,
    ) -> Result<QuotaCheck, QuotaError> {
        let quota = self.get_quota(organization_id).await?;
        let usage = self.get_usage(organization_id).await?;

        let current = usage.storage_bytes_used;
        let limit = quota.max_storage_bytes;
        let allowed = (current + additional_bytes) <= limit;
        let remaining = if allowed { limit - current } else { 0 };

        Ok(QuotaCheck {
            allowed,
            quota_type: QuotaType::Storage,
            current,
            limit,
            remaining,
        })
    }

    /// Update quota limits for organization
    pub async fn update_quota(
        &self,
        organization_id: Uuid,
        updates: QuotaUpdates,
    ) -> Result<OrganizationQuota, QuotaError> {
        let mut query = String::from("UPDATE organization_quotas SET ");
        let mut params = Vec::new();
        let mut param_idx = 1;

        if let Some(max_projects) = updates.max_projects {
            query.push_str(&format!("max_projects = ${}, ", param_idx));
            params.push(max_projects.to_string());
            param_idx += 1;
        }

        if let Some(max_translations) = updates.max_translations_per_month {
            query.push_str(&format!("max_translations_per_month = ${}, ", param_idx));
            params.push(max_translations.to_string());
            param_idx += 1;
        }

        if let Some(max_storage) = updates.max_storage_bytes {
            query.push_str(&format!("max_storage_bytes = ${}, ", param_idx));
            params.push(max_storage.to_string());
            param_idx += 1;
        }

        if let Some(max_users) = updates.max_users {
            query.push_str(&format!("max_users = ${}, ", param_idx));
            params.push(max_users.to_string());
            param_idx += 1;
        }

        query.push_str("updated_at = NOW() ");
        query.push_str(&format!("WHERE organization_id = ${} RETURNING *", param_idx));

        // Simplified - in production, use sqlx query builder
        self.get_quota(organization_id).await
    }

    /// Create default quota for new organization
    pub async fn create_default_quota(
        &self,
        organization_id: Uuid,
    ) -> Result<OrganizationQuota, QuotaError> {
        let quota = sqlx::query_as!(
            OrganizationQuota,
            r#"
            INSERT INTO organization_quotas (
                organization_id, max_projects, max_translations_per_month,
                max_storage_bytes, max_users, custom_quotas
            )
            VALUES ($1, 10, 100, 1073741824, 5, '{}')
            RETURNING
                id, organization_id, max_projects, max_translations_per_month,
                max_storage_bytes, max_users, custom_quotas as "custom_quotas!",
                created_at, updated_at
            "#,
            organization_id
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| QuotaError::DatabaseError(e.to_string()))?;

        Ok(quota)
    }
}

/// Quota update parameters
#[derive(Debug, Clone, Default)]
pub struct QuotaUpdates {
    pub max_projects: Option<i32>,
    pub max_translations_per_month: Option<i32>,
    pub max_storage_bytes: Option<i64>,
    pub max_users: Option<i32>,
}

/// Quota errors
#[derive(Debug, thiserror::Error)]
pub enum QuotaError {
    #[error("Quota exceeded: {0}")]
    QuotaExceeded(String),

    #[error("Database error: {0}")]
    DatabaseError(String),

    #[error("Invalid quota value: {0}")]
    InvalidValue(String),

    #[error("Quota not found for organization")]
    NotFound,
}

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

    #[test]
    fn test_organization_quota_default() {
        let quota = OrganizationQuota::default();
        assert_eq!(quota.max_projects, 10);
        assert_eq!(quota.max_translations_per_month, 100);
        assert_eq!(quota.max_storage_bytes, 1_073_741_824); // 1 GB
        assert_eq!(quota.max_users, 5);
    }

    #[test]
    fn test_quota_type_display() {
        assert_eq!(QuotaType::Projects.to_string(), "projects");
        assert_eq!(QuotaType::Translations.to_string(), "translations");
        assert_eq!(QuotaType::Storage.to_string(), "storage");
        assert_eq!(QuotaType::Users.to_string(), "users");
        assert_eq!(QuotaType::Custom("api_calls".to_string()).to_string(), "api_calls");
    }

    #[test]
    fn test_quota_check_allowed() {
        let check = QuotaCheck {
            allowed: true,
            quota_type: QuotaType::Projects,
            current: 5,
            limit: 10,
            remaining: 5,
        };

        assert!(check.allowed);
        assert_eq!(check.current, 5);
        assert_eq!(check.limit, 10);
        assert_eq!(check.remaining, 5);
    }

    #[test]
    fn test_quota_check_exceeded() {
        let check = QuotaCheck {
            allowed: false,
            quota_type: QuotaType::Users,
            current: 10,
            limit: 10,
            remaining: 0,
        };

        assert!(!check.allowed);
        assert_eq!(check.remaining, 0);
    }

    #[test]
    fn test_quota_updates_default() {
        let updates = QuotaUpdates::default();
        assert!(updates.max_projects.is_none());
        assert!(updates.max_translations_per_month.is_none());
        assert!(updates.max_storage_bytes.is_none());
        assert!(updates.max_users.is_none());
    }

    #[test]
    fn test_quota_updates_partial() {
        let updates = QuotaUpdates {
            max_projects: Some(20),
            max_translations_per_month: None,
            max_storage_bytes: Some(5_000_000_000),
            max_users: None,
        };

        assert_eq!(updates.max_projects, Some(20));
        assert!(updates.max_translations_per_month.is_none());
        assert_eq!(updates.max_storage_bytes, Some(5_000_000_000));
    }
}