oxcache 0.1.4

A high-performance multi-level cache library for Rust with L1 (memory) and L2 (Redis) caching.
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
//! PostgreSQL分区管理器实现

//! Copyright (c) 2025-2026, Kirky.X
//!
//! MIT License
//!
//! 该模块定义了PostgreSQL分区管理器的实现。

use crate::error::{CacheError, Result};
use chrono::{DateTime, Datelike, NaiveDate, Utc};
use sea_orm::{ConnectOptions, ConnectionTrait, Database, DatabaseConnection, Statement};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tracing::{debug, info, warn};

use crate::database::partition::{PartitionConfig, PartitionInfo, PartitionManager};

/// 连接池统计信息
#[derive(Debug, Clone, Default)]
pub struct PoolStats {
    pub active_connections: u32,
    pub idle_connections: u32,
    pub max_connections: u32,
    pub min_connections: u32,
    pub connection_acquire_ms: f64,
    pub last_acquire: Option<Instant>,
}

impl PoolStats {
    pub fn utilization_rate(&self) -> f64 {
        if self.max_connections > 0 {
            self.active_connections as f64 / self.max_connections as f64
        } else {
            0.0
        }
    }
}

/// PostgreSQL分区管理器
pub struct PostgresPartitionManager {
    config: PartitionConfig,
    connection: Arc<DatabaseConnection>,
    pool_stats: Arc<Mutex<PoolStats>>,
}

impl PostgresPartitionManager {
    /// 创建新的PostgreSQL分区管理器
    pub async fn new(connection_string: &str, config: PartitionConfig) -> Result<Self> {
        let mut opt = ConnectOptions::new(connection_string.to_string());
        opt.max_connections(10)
            .min_connections(2)
            .connect_timeout(Duration::from_secs(5))
            .idle_timeout(Duration::from_secs(8))
            .max_lifetime(Duration::from_secs(1800))
            .acquire_timeout(Duration::from_secs(10));

        let start = Instant::now();
        let connection = Database::connect(opt)
            .await
            .map_err(|e| {
                // 脱敏错误信息,避免泄露连接字符串中的密码
                let error_msg = e.to_string();
                let sanitized_msg = if error_msg.contains("://") {
                    error_msg.split("://")
                        .next()
                        .map(|_| "[REDACTED]")
                        .unwrap_or(&error_msg)
                        .to_string()
                } else {
                    error_msg
                };
                CacheError::DatabaseError(format!(
                    "Failed to connect to PostgreSQL: {}. Please check your connection string and ensure the database server is running.",
                    sanitized_msg
                ))
            })?;

        let acquire_duration = start.elapsed();
        info!(
            "PostgreSQL connection established in {:?}",
            acquire_duration
        );

        if acquire_duration > Duration::from_secs(3) {
            warn!(
                "PostgreSQL connection took longer than expected: {:?}",
                acquire_duration
            );
        }

        Ok(Self {
            config,
            connection: Arc::new(connection),
            pool_stats: Arc::new(Mutex::new(PoolStats {
                active_connections: 1,
                idle_connections: 1,
                max_connections: 10,
                min_connections: 2,
                connection_acquire_ms: acquire_duration.as_secs_f64() * 1000.0,
                last_acquire: Some(Instant::now()),
            })),
        })
    }

    /// 获取连接池统计信息
    pub async fn get_pool_stats(&self) -> PoolStats {
        self.pool_stats.lock().await.clone()
    }

    /// 验证 PostgreSQL 标识符,防止 SQL 注入
    fn validate_identifier(&self, identifier: &str) -> Result<()> {
        if identifier.is_empty() {
            return Err(CacheError::DatabaseError(
                "Identifier cannot be empty".to_string(),
            ));
        }

        // PostgreSQL 标识符规则:只能包含字母、数字、下划线
        if !identifier.chars().all(|c| c.is_alphanumeric() || c == '_') {
            return Err(CacheError::DatabaseError(format!(
                "Invalid identifier '{}': only alphanumeric characters and underscores are allowed",
                identifier
            )));
        }

        // 检查长度限制(PostgreSQL 最大 63 字符)
        if identifier.len() > 63 {
            return Err(CacheError::DatabaseError(
                "Identifier exceeds maximum length of 63 characters".to_string(),
            ));
        }

        // 检查是否以数字开头(PostgreSQL 不允许)
        if identifier
            .chars()
            .next()
            .map(|c| c.is_ascii_digit())
            .unwrap_or(false)
        {
            return Err(CacheError::DatabaseError(
                "Identifier cannot start with a digit".to_string(),
            ));
        }

        // 检查是否是 PostgreSQL 保留关键字
        const RESERVED_KEYWORDS: &[&str] = &[
            "select",
            "from",
            "where",
            "insert",
            "update",
            "delete",
            "create",
            "drop",
            "alter",
            "table",
            "index",
            "view",
            "grant",
            "revoke",
            "commit",
            "rollback",
            "union",
            "intersect",
            "except",
            "join",
            "inner",
            "outer",
            "left",
            "right",
            "order",
            "by",
            "group",
            "having",
            "limit",
            "offset",
            "distinct",
            "all",
            "exists",
            "in",
            "between",
            "like",
            "is",
            "null",
            "and",
            "or",
            "not",
            "true",
            "false",
            "case",
            "when",
            "then",
            "else",
            "end",
        ];

        let lower_identifier = identifier.to_lowercase();
        if RESERVED_KEYWORDS.contains(&lower_identifier.as_str()) {
            return Err(CacheError::DatabaseError(format!(
                "Identifier '{}' is a reserved keyword and cannot be used",
                identifier
            )));
        }

        Ok(())
    }

    /// 验证连接健康状态
    pub async fn health_check(&self) -> bool {
        if let Err(e) = self.ping().await {
            warn!("PostgreSQL health check failed: {}", e);
            return false;
        }
        true
    }

    /// Ping数据库以验证连接
    async fn ping(&self) -> Result<()> {
        let conn = self.connection.as_ref();
        conn.execute(Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            "SELECT 1".to_string(),
        ))
        .await
        .map_err(|e| CacheError::DatabaseError(e.to_string()))?;
        Ok(())
    }

    /// 重新建立连接(用于恢复)
    pub async fn reconnect(&mut self, connection_string: &str) -> Result<()> {
        info!("Attempting to reconnect to PostgreSQL...");

        let mut opt = ConnectOptions::new(connection_string.to_string());
        opt.max_connections(10)
            .min_connections(2)
            .connect_timeout(Duration::from_secs(10))
            .idle_timeout(Duration::from_secs(8));

        let start = Instant::now();
        let connection = Database::connect(opt).await.map_err(|e| {
            // 脱敏错误信息
            let error_msg = e.to_string();
            let sanitized_msg = if error_msg.contains("://") {
                error_msg
                    .split("://")
                    .next()
                    .map(|_| "[REDACTED]")
                    .unwrap_or(&error_msg)
                    .to_string()
            } else {
                error_msg
            };
            CacheError::DatabaseError(format!(
                "Failed to reconnect to PostgreSQL: {}. Please check your database server.",
                sanitized_msg
            ))
        })?;

        let acquire_duration = start.elapsed();
        info!(
            "PostgreSQL reconnection established in {:?}",
            acquire_duration
        );

        self.connection = Arc::new(connection);

        let mut stats = self.pool_stats.lock().await;
        stats.connection_acquire_ms = acquire_duration.as_secs_f64() * 1000.0;
        stats.last_acquire = Some(Instant::now());

        Ok(())
    }

    /// 创建分区表的主表(使用声明式分区)
    async fn create_partitioned_table(&self, table_name: &str, schema: &str) -> Result<()> {
        let conn = self.connection.as_ref();

        // 修改schema为分区表格式
        let partition_schema = schema;

        // 查找表结构中的分区列
        let partition_column = if schema.contains("created_at") {
            "created_at"
        } else if schema.contains("timestamp") {
            "timestamp"
        } else if schema.contains("date_column") {
            "date_column"
        } else {
            "created_at"
        };

        // 移除末尾的右括号并添加分区子句
        let partition_sql = if partition_schema.trim().ends_with(')') {
            format!(
                "{}) PARTITION BY RANGE ({})",
                partition_schema.trim().trim_end_matches(')'),
                partition_column
            )
        } else {
            format!(
                "{}) PARTITION BY RANGE ({})",
                partition_schema, partition_column
            )
        };

        debug!("Generated partition SQL: {}", partition_sql);

        conn.execute(Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            partition_sql,
        ))
            .await
            .map_err(|e| {
                CacheError::DatabaseError(format!(
                    "Failed to create partitioned table: {}. Please check if the table schema is valid.",
                    e
                ))
            })?;

        // 创建默认分区
        let default_partition_sql = format!(
            "CREATE TABLE IF NOT EXISTS {}_default PARTITION OF {} DEFAULT",
            table_name, table_name
        );

        conn.execute(Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            default_partition_sql,
        ))
        .await
        .map_err(|e| {
            CacheError::DatabaseError(format!("Failed to create default partition: {}", e))
        })?;

        Ok(())
    }
}

#[async_trait::async_trait]
impl PartitionManager for PostgresPartitionManager {
    async fn initialize_table(&self, table_name: &str, schema: &str) -> Result<()> {
        if self.config.enabled {
            self.create_partitioned_table(table_name, schema).await
        } else {
            let conn = self.connection.as_ref();
            conn.execute(Statement::from_string(
                sea_orm::DatabaseBackend::Postgres,
                schema.to_string(),
            ))
            .await
            .map_err(|e| {
                CacheError::DatabaseError(format!(
                    "Failed to initialize table: {}. Please check the table schema.",
                    e
                ))
            })?;
            Ok(())
        }
    }

    async fn create_partition(&self, partition: &PartitionInfo) -> Result<()> {
        let conn = self.connection.as_ref();

        debug!("Creating partition with name: {}", partition.name);
        debug!("Partition table_name: {}", partition.table_name);

        let parts: Vec<&str> = partition.name.rsplitn(3, '_').collect();
        let base_table_name = if parts.len() >= 3 {
            parts[2..].join("_")
        } else {
            partition.name.clone()
        };

        let partition_table_name = format!(
            "{}_p{:04}{:02}",
            base_table_name,
            partition.start_date.year(),
            partition.start_date.month()
        );

        debug!("Final partition table name: {}", partition_table_name);

        // 验证所有标识符以防止 SQL 注入
        self.validate_identifier(&base_table_name)?;
        self.validate_identifier(&partition_table_name)?;

        // 使用双引号包裹标识符以避免关键字冲突
        let sql = format!(
            "CREATE TABLE IF NOT EXISTS \"{}\" PARTITION OF \"{}\" FOR VALUES FROM ('{}') TO ('{}')",
            partition_table_name,
            base_table_name,
            partition.start_date.format("%Y-%m-%d"),
            partition.end_date.format("%Y-%m-%d")
        );

        debug!("SQL: {}", sql);

        conn.execute(Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            sql,
        ))
        .await
        .map_err(|e| {
            CacheError::DatabaseError(format!(
                "Failed to create partition {}: {}",
                partition_table_name, e
            ))
        })?;

        Ok(())
    }

    async fn get_partitions(&self, table_name: &str) -> Result<Vec<PartitionInfo>> {
        let conn = self.connection.as_ref();

        let sql = "SELECT
                child.relname AS partition_name,
                pg_get_expr(child.relpartbound, child.oid) AS partition_range
             FROM pg_inherits
             JOIN pg_class parent ON pg_inherits.inhparent = parent.oid
             JOIN pg_class child ON pg_inherits.inhrelid = child.oid
             WHERE parent.relname = $1"
            .to_string();

        let statement = Statement::from_string(sea_orm::DatabaseBackend::Postgres, sql);
        let result = conn.query_all(statement).await.map_err(|e| {
            CacheError::DatabaseError(format!(
                "Failed to get partitions: {}. Please check if the table exists.",
                e
            ))
        })?;

        let mut partitions = Vec::new();
        for row in result {
            let partition_name: String = row.try_get("", "partition_name")?;
            let partition_range: Option<String> = row.try_get("", "partition_range")?;

            if let Some(range_str) = partition_range {
                if let Some(info) =
                    self.parse_postgres_partition_range(&partition_name, &range_str, table_name)
                {
                    partitions.push(info);
                }
            }
        }

        Ok(partitions)
    }

    async fn drop_partition(&self, _table_name: &str, partition_name: &str) -> Result<()> {
        let conn = self.connection.as_ref();

        // 验证标识符以防止 SQL 注入
        self.validate_identifier(partition_name)?;

        // 使用双引号包裹标识符以避免关键字冲突
        let sql = format!("DROP TABLE IF EXISTS \"{}\"", partition_name);
        debug!("Executing drop SQL: {}", sql);

        conn.execute(Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            sql,
        ))
        .await
        .map_err(|e| {
            CacheError::DatabaseError(format!(
                "Failed to drop partition {}: {}",
                partition_name, e
            ))
        })?;

        debug!("Successfully dropped partition: {}", partition_name);
        Ok(())
    }

    async fn ensure_partition_exists(
        &self,
        date: DateTime<Utc>,
        table_name: &str,
    ) -> Result<String> {
        let partition = PartitionInfo::new(date, table_name)?;

        // 检查分区是否已存在
        let existing_partitions = self.get_partitions(table_name).await?;
        let exists = existing_partitions.iter().any(|p| p.name == partition.name);

        if !exists {
            self.create_partition(&partition).await?;
        }

        Ok(partition.table_name)
    }

    fn get_config(&self) -> PartitionConfig {
        self.config.clone()
    }
}

impl PostgresPartitionManager {
    fn parse_postgres_partition_range(
        &self,
        partition_name: &str,
        range_str: &str,
        table_name: &str,
    ) -> Option<PartitionInfo> {
        // PostgreSQL分区范围格式: FOR VALUES FROM ('2024-01-01') TO ('2024-02-01')
        debug!("Parsing partition range for: {}", partition_name);

        // More flexible regex to match various PostgreSQL date formats with optional time and timezone
        let re = regex::Regex::new(r"FROM\s+\('(\d{4}-\d{2}-\d{2})(?:[^)]+)?'\)\s+TO\s+\('(\d{4}-\d{2}-\d{2})(?:[^)]+)?'\)")
            .ok()?;

        if let Some(captures) = re.captures(range_str) {
            let start_date_str = captures.get(1)?.as_str();
            let end_date_str = captures.get(2)?.as_str();

            debug!("Parsed start date: {}", start_date_str);
            debug!("Parsed end date: {}", end_date_str);

            // Parse the dates properly
            let start_date = NaiveDate::parse_from_str(start_date_str, "%Y-%m-%d")
                .ok()?
                .and_hms_opt(0, 0, 0)?
                .and_utc();

            let end_date = NaiveDate::parse_from_str(end_date_str, "%Y-%m-%d")
                .ok()?
                .and_hms_opt(0, 0, 0)?
                .and_utc();

            debug!("Parsed start date as DateTime: {}", start_date);
            debug!("Parsed end date as DateTime: {}", end_date);

            // Create PartitionInfo using the table name from the partition
            let mut info = PartitionInfo::new(start_date, table_name).ok()?;
            info.name = partition_name.to_string();
            info.start_date = start_date;
            info.end_date = end_date;
            info.created = true;

            debug!("Successfully created PartitionInfo");
            return Some(info);
        }

        debug!("Failed to parse partition range");
        None
    }
}