pg-api 0.2.0

A high-performance PostgreSQL REST API driver with rate limiting, connection pooling, and observability
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
use crate::rate_limit::RateLimitInfo;
use crate::pool::GlobalPool;
use crate::queue::QueueStats;
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use deadpool_postgres::Pool;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{collections::HashMap, sync::Arc};
use tokio::sync::Mutex;
use uuid::Uuid;

#[derive(Clone)]
pub struct AppState {
    pub instances: Arc<tokio::sync::RwLock<HashMap<String, PostgresInstance>>>,
    pub connections: Arc<DashMap<String, Pool>>,
    pub accounts: Arc<tokio::sync::RwLock<HashMap<String, Account>>>,
    pub rate_limiter: Arc<Mutex<HashMap<String, RateLimitInfo>>>,
    pub active_connections: Arc<DashMap<String, u32>>, // account_id -> active connection count
    pub global_pool: Arc<GlobalPool>,
    pub job_queue: Option<tokio::sync::mpsc::Sender<crate::queue::QueuedRequest>>,
    pub queue_stats: Arc<QueueStats>, // NOVO: Pool global compartilhado
}

impl AppState {
    pub async fn new() -> anyhow::Result<Self> {
        
        // Carrega configuração do pool
        let pool_config = crate::config::load_pool_config().await?;
        let global_pool = Arc::new(GlobalPool::new(pool_config).await?);
        
        Ok(Self {
            instances: Arc::new(tokio::sync::RwLock::new(load_instances().await?)),
            connections: Arc::new(DashMap::new()),
            accounts: Arc::new(tokio::sync::RwLock::new(load_accounts().await?)),
            rate_limiter: Arc::new(Mutex::new(HashMap::new())),
            active_connections: Arc::new(DashMap::new()),
            global_pool,
            job_queue: None,
            queue_stats: Arc::new(QueueStats::default()),
        })
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PostgresInstance {
    pub id: String,
    pub name: String,
    pub host: String,
    pub port: u16,
    pub superuser: String,
    pub superuser_password: String,
    pub instance_type: InstanceType,
    pub created_at: DateTime<Utc>,
    pub status: InstanceStatus,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InstanceType {
    Single,
    Primary,
    Replica,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InstanceStatus {
    Active,
    Maintenance,
    Degraded,
    Offline,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Account {
    pub id: String,
    pub name: String,
    pub api_key: String,
    pub instance_id: String,
    pub databases: Vec<DatabaseAccess>,
    pub role: AccountRole,
    pub created_at: DateTime<Utc>,
    pub last_used: DateTime<Utc>,
    pub rate_limit: u32,
    pub max_connections: u32,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub notes: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DatabaseAccess {
    pub database: String,
    pub username: String,
    pub password: String,
    pub permissions: Vec<Permission>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum Permission {
    Select,
    Insert,
    Update,
    Delete,
    Create,
    Drop,
    Truncate,
    References,
    Trigger,
    Execute,
    Usage,
    All,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum AccountRole {
    Superuser,
    Admin,
    Developer,
    Application,
    Readonly,
}

#[derive(Debug, Deserialize)]
pub struct QueryRequest {
    pub query: String,
    pub database: String,
    #[serde(default)]
    pub params: Vec<Value>,
    #[serde(default)]
    #[allow(dead_code)]
    pub options: QueryOptions,
}

#[derive(Debug, Deserialize, Default)]
pub struct QueryOptions {
    #[serde(default)]
    #[allow(dead_code)]
    pub timeout_ms: Option<u64>,
    #[serde(default)]
    #[allow(dead_code)]
    pub read_only: bool,
    #[serde(default)]
    #[allow(dead_code)]
    pub as_transaction: bool,
}

#[derive(Debug, Serialize)]
pub struct ApiResponse<T> {
    pub success: bool,
    pub data: Option<T>,
    pub error: Option<ErrorInfo>,
    pub metadata: ResponseMetadata,
}

#[derive(Debug, Serialize)]
pub struct ErrorInfo {
    pub code: String,
    pub message: String,
    pub details: Option<Value>,
}

#[derive(Debug, Serialize)]
pub struct ResponseMetadata {
    pub request_id: String,
    pub execution_time_ms: u128,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rows_affected: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance_id: Option<String>,
    pub timestamp: DateTime<Utc>,
}

#[derive(Debug, Serialize)]
pub struct QueryResult {
    pub rows: Vec<Value>,
    pub fields: Vec<FieldMetadata>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_plan: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct FieldMetadata {
    pub name: String,
    pub data_type: String,
    pub nullable: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_length: Option<i32>,
}

impl<T: Serialize> ApiResponse<T> {
    pub fn success(data: T, metadata: ResponseMetadata) -> Self {
        Self {
            success: true,
            data: Some(data),
            error: None,
            metadata,
        }
    }

    pub fn error(code: &str, message: String, metadata: ResponseMetadata) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(ErrorInfo {
                code: code.to_string(),
                message,
                details: None,
            }),
            metadata,
        }
    }

    pub fn error_with_details(code: &str, message: String, details: Value, metadata: ResponseMetadata) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(ErrorInfo {
                code: code.to_string(),
                message,
                details: Some(details),
            }),
            metadata,
        }
    }
}

async fn load_instances() -> anyhow::Result<HashMap<String, PostgresInstance>> {
    let mut instances = HashMap::new();
    
    instances.insert(
        "default".to_string(),
        PostgresInstance {
            id: "default".to_string(),
            name: "Primary Instance".to_string(),
            host: "127.0.0.1".to_string(),
            port: 5432,
            superuser: "postgres".to_string(),
            superuser_password: "postgres".to_string(),
            instance_type: InstanceType::Single,
            created_at: Utc::now(),
            status: InstanceStatus::Active,
        },
    );
    
    Ok(instances)
}

async fn load_accounts() -> anyhow::Result<HashMap<String, Account>> {
    let mut accounts = HashMap::new();
    
    // Get config directory from environment or use default
    let config_dir = std::env::var("CONFIG_DIR").unwrap_or_else(|_| "config".to_string());
    let config_path = std::path::PathBuf::from(&config_dir).join("accounts.json");
    
    eprintln!("[ACCOUNT LOADING] Loading accounts from: {}", config_path.display());
    tracing::info!("Loading accounts from: {}", config_path.display());
    
    // Load from config file if exists
    match tokio::fs::read_to_string(&config_path).await {
        Ok(content) => {
            match serde_json::from_str::<Vec<Account>>(&content) {
                Ok(loaded_accounts) => {
                    eprintln!("[ACCOUNT LOADING] Loaded {} accounts from config file", loaded_accounts.len());
                    tracing::info!("Loaded {} accounts from config file", loaded_accounts.len());
                    for account in loaded_accounts {
                        eprintln!("[ACCOUNT LOADING] Loading account: {} with key: {}...", account.name, &account.api_key[..20.min(account.api_key.len())]);
                        tracing::debug!("Loading account: {} with key: {}...", account.name, &account.api_key[..20.min(account.api_key.len())]);
                        accounts.insert(account.api_key.clone(), account);
                    }
                }
                Err(e) => {
                    eprintln!("[ACCOUNT LOADING ERROR] Failed to parse accounts.json: {}", e);
                    tracing::error!("Failed to parse accounts.json: {}", e);
                    return Err(anyhow::anyhow!("Failed to parse accounts configuration: {}", e));
                }
            }
        }
        Err(e) => {
            eprintln!("[ACCOUNT LOADING] Could not read accounts file from {}: {}", config_path.display(), e);
            tracing::warn!("Could not read accounts file from {}: {}", config_path.display(), e);
            // Only use default if file doesn't exist, not on parse errors
            if e.kind() == std::io::ErrorKind::NotFound {
                tracing::info!("Using default account configuration");
                // Default account
                accounts.insert(
                    "TWDo79SIVGM21sdZqbIW68q5FuW+SQTL9jl88t2iF1j5vfP2poxU0wp43NHSVXdI".to_string(),
                    Account {
                        id: Uuid::new_v4().to_string(),
                        name: "sentric-production".to_string(),
                        api_key: "TWDo79SIVGM21sdZqbIW68q5FuW+SQTL9jl88t2iF1j5vfP2poxU0wp43NHSVXdI".to_string(),
                        instance_id: "default".to_string(),
                        databases: vec![
                            DatabaseAccess {
                                database: "camera".to_string(),
                                username: "sentric".to_string(),
                                password: "X5pzEXGqAyLVy9CQQKEbCsrF".to_string(),
                                permissions: vec![Permission::All],
                            },
                            DatabaseAccess {
                                database: "sentric".to_string(),
                                username: "sentric".to_string(),
                                password: "X5pzEXGqAyLVy9CQQKEbCsrF".to_string(),
                                permissions: vec![Permission::All],
                            },
                        ],
                        role: AccountRole::Superuser,
                        created_at: Utc::now(),
                        last_used: Utc::now(),
                        rate_limit: 1000,
                        max_connections: 50,
                        notes: Some("Default account - replace with proper configuration".to_string()),
                    },
                );
            } else {
                return Err(anyhow::anyhow!("Failed to read accounts configuration: {}", e));
            }
        }
    }
    
    Ok(accounts)
}

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

    #[test]
    fn test_api_response_success() {
        let metadata = ResponseMetadata {
            request_id: "test-123".to_string(),
            execution_time_ms: 42,
            rows_affected: Some(1),
            instance_id: Some("acc_001".to_string()),
            timestamp: Utc::now(),
        };

        let data = json!({"message": "success"});
        let response = ApiResponse::success(data, metadata);

        assert!(response.success);
        assert!(response.data.is_some());
        assert!(response.error.is_none());
        assert_eq!(response.metadata.execution_time_ms, 42);
    }

    #[test]
    fn test_api_response_error() {
        let metadata = ResponseMetadata {
            request_id: "test-456".to_string(),
            execution_time_ms: 10,
            rows_affected: None,
            instance_id: Some("acc_001".to_string()),
            timestamp: Utc::now(),
        };

        let response: ApiResponse<Value> = ApiResponse::error(
            "PERMISSION_DENIED",
            "Access denied".to_string(),
            metadata,
        );

        assert!(!response.success);
        assert!(response.data.is_none());
        assert!(response.error.is_some());
        
        let error = response.error.unwrap();
        assert_eq!(error.code, "PERMISSION_DENIED");
        assert_eq!(error.message, "Access denied");
    }

    #[test]
    fn test_query_request_deserialization() {
        let json_str = r#"{
            "query": "SELECT * FROM users WHERE id = $1",
            "database": "mydb",
            "params": [1]
        }"#;

        let request: QueryRequest = serde_json::from_str(json_str).unwrap();
        assert_eq!(request.query, "SELECT * FROM users WHERE id = $1");
        assert_eq!(request.database, "mydb");
        assert_eq!(request.params.len(), 1);
        assert_eq!(request.params[0], 1);
    }

    #[test]
    fn test_query_request_with_options() {
        let json_str = r#"{
            "query": "SELECT * FROM users",
            "database": "mydb",
            "params": [],
            "options": {
                "timeout_ms": 5000,
                "read_only": true
            }
        }"#;

        let request: QueryRequest = serde_json::from_str(json_str).unwrap();
        assert_eq!(request.options.timeout_ms, Some(5000));
        assert_eq!(request.options.read_only, true);
    }

    #[test]
    fn test_permission_serialization() {
        let perms = vec![Permission::Select, Permission::Insert];
        let json = serde_json::to_string(&perms).unwrap();
        assert_eq!(json, "[\"SELECT\",\"INSERT\"]");
    }

    #[test]
    fn test_account_role_deserialization() {
        let json_str = "\"superuser\"";
        let role: AccountRole = serde_json::from_str(json_str).unwrap();
        assert_eq!(role, AccountRole::Superuser);

        let json_str = "\"admin\"";
        let role: AccountRole = serde_json::from_str(json_str).unwrap();
        assert_eq!(role, AccountRole::Admin);

        let json_str = "\"developer\"";
        let role: AccountRole = serde_json::from_str(json_str).unwrap();
        assert_eq!(role, AccountRole::Developer);

        let json_str = "\"application\"";
        let role: AccountRole = serde_json::from_str(json_str).unwrap();
        assert_eq!(role, AccountRole::Application);

        let json_str = "\"readonly\"";
        let role: AccountRole = serde_json::from_str(json_str).unwrap();
        assert_eq!(role, AccountRole::Readonly);
    }

    #[test]
    fn test_database_access_serialization() {
        let access = DatabaseAccess {
            database: "testdb".to_string(),
            username: "testuser".to_string(),
            password: "testpass".to_string(),
            permissions: vec![Permission::Select, Permission::All],
        };

        let json = serde_json::to_string(&access).unwrap();
        assert!(json.contains("testdb"));
        assert!(json.contains("SELECT"));
        assert!(json.contains("ALL"));
    }

    #[test]
    fn test_instance_type_variants() {
        let single = InstanceType::Single;
        let primary = InstanceType::Primary;
        let replica = InstanceType::Replica;

        assert!(matches!(single, InstanceType::Single));
        assert!(matches!(primary, InstanceType::Primary));
        assert!(matches!(replica, InstanceType::Replica));
    }

    #[test]
    fn test_instance_status_variants() {
        assert!(matches!(InstanceStatus::Active, InstanceStatus::Active));
        assert!(matches!(InstanceStatus::Maintenance, InstanceStatus::Maintenance));
        assert!(matches!(InstanceStatus::Degraded, InstanceStatus::Degraded));
        assert!(matches!(InstanceStatus::Offline, InstanceStatus::Offline));
    }
}