Commit Graph
89 Commits
Author SHA1 Message Date
nutcas3 4e4b13f3e8 refactor: Simplify validation parsing using let-chains in sync.rs and wrap unsafe env::set_var in tests
- Replace nested if-let statements with let-chain pattern for VmRSS memory parsing in /proc/self/status
- Replace nested if-let statements with let-chain pattern for Redis used_memory parsing
- Wrap std::env::set_var calls in unsafe blocks in validation_tests.rs for MAX_BYTES_LIMIT and MAX_AMOUNT_LIMIT
2026-05-01 00:43:54 +03:00
nutcas3 11065b827b refactor: Simplify Redis RPS extraction using let-chains in monitoring_impl.rs
- Replace nested if-let statements with let-chain pattern for Redis RPS parsing
- Update module reference from monitoring to monitoring_impl in monitoring.rs
2026-05-01 00:43:41 +03:00
nutcas3 220b7e0380 refactor: Rename monitoring.rs to monitoring_impl.rs in charging-engine 2026-05-01 00:43:22 +03:00
nutcas3 9b64366e25 refactor: Fix Rust edition, remove duplicate lint rule, and improve error handling in charging-engine and packet-gateway
- Change Rust edition from "2026" to "2024" in workspace Cargo.toml
- Remove duplicate expect_used lint rule from workspace lints
- Prefix unused account variable with underscore in calculate_usage_cost
- Split CARGO_MANIFEST_DIR assignment into separate variable in run_migrations
- Clone plan_id before moving plan in add_rating_plan handler
- Replace expect() with unwrap() in governor
2026-04-30 03:17:46 +03:00
nutcas3 ccb2ab7ee8 refactor: Add comprehensive documentation with examples to charging-engine modules
- Add module-level documentation to lib.rs with usage example
- Document Claims and AuthConfig structs with examples in auth.rs
- Add ChargingEngine struct documentation with initialization example
- Document ChargingRule, SubscriberAccount, AccountStatus, UsageEvent, UsageType, and RatingPlan with examples in types.rs
- Add CircuitState, CircuitBreakerError, and CircuitBreaker documentation with examples in circuit_breaker.rs
2026-04-29 04:36:40 +03:00
nutcas3 b4e42d7717 refactor: Improve Redis key consistency and add existence check in credit management
- Change Redis key prefix from "block:" to "blocked:" in unblock_user for consistency
- Replace is_some() check with if let pattern in block_user to avoid unused variable
- Add existence check before attempting to delete blocked user key in unblock_user
- Use if let pattern for blocked status check in unblock_user
- Return Ok(()) silently if user is not blocked instead of attempting deletion
2026-04-29 04:24:49 +03:00
nutcas3 4008a19f4a refactor: Pre-allocate Vec capacity in rating_billing.rs to reduce reallocations
- Set applied_rules capacity to 6 (maximum number of charging rules that can be applied)
- Set keys capacity to 100 in get_usage_history and get_all_accounts (matches SCAN batch size)
- Add comments explaining capacity choices for each Vec initialization
2026-04-29 04:24:22 +03:00
nutcas3 5ec01e591e refactor: Replace fallback defaults with required environment variable validation in charging-engine auth
- Change AuthConfig::from_env() return type from Self to Result<Self, String>
- Remove default JWT_SECRET fallback, require environment variable to be set
- Add validation requiring JWT_SECRET to be at least 32 characters for security
- Replace expect() with ok_or_else in create_token timestamp calculation
- Replace expect() with map_err in DATABASE_URL environment variable loading
2026-04-29 04:23:58 +03:00
nutcas3 8bb332964b refactor: Replace unwrap() with unwrap_or_else fallback in rate limiter configuration
- Add fallback to default GovernorConfig (10 req/s, burst 20) if custom config fails
- Replace unwrap() with unwrap_or_else providing sensible defaults
- Add comment explaining fallback behavior for rate limiter initialization
2026-04-29 04:23:11 +03:00
nutcas3 5340469a1a refactor: Replace expect() with unwrap_or_else fallbacks and improve error handling in charging-engine
- Remove unused _account variable in calculate_usage_cost
- Replace HashMap::with_capacity with HashMap::new and use iterator chain in get_all_plans
- Add std::process::Command import and set current_dir to repo root in run_migrations
- Add comment explaining directory change to locate migrations folder
- Replace expect() with unwrap_or_else providing fallback JSON in SubscriberAccount and UsageEvent
2026-04-29 04:22:52 +03:00
nutcas3 1deecf32fe refactor: Replace manual Display and Error implementations with thiserror derive macro in ChargingError
- Add thiserror::Error derive to ChargingError enum
- Replace manual fmt::Display implementation with #[error] attributes on each variant
- Remove manual std::error::Error implementation (provided by thiserror)
- Remove std::fmt import as it's no longer needed
- Maintain same error message formats and functionality
2026-04-29 04:22:02 +03:00
nutcas3 4cc0b80b1c refactor: Remove unnecessary clone() calls and improve error handling in packet-gateway
- Remove clone() from rating plan parameter in add_rating_plan call
- Remove clone() calls from ChargingEngineClient and EbpfManager initialization
- Remove clone() from Redis client Arc wrapping
- Remove clone() calls from PacketGatewayConfig field assignments
- Replace expect() with proper error handling using map_err and anyhow in health check server
- Remove clone() from IP string in session data collection
2026-04-29 04:21:52 +03:00
nutcas3 b3ff568bd4 feat: Add workspace-level linting rules and cargo-audit configuration
- Add cargo-audit metadata section with placeholder for ignored advisories
- Forbid unsafe_code at workspace level
- Enable all and pedantic clippy warnings
- Deny unwrap_used, expect_used, and panic to enforce error handling
- Add thiserror dependency to charging-engine for improved error handling
2026-04-29 04:21:33 +03:00
nutcas3 69241334aa feat: Add automatic Goose migration execution on startup in charging-engine RatingPlansRepo
- Add std::process::Command import for running external commands
- Implement run_migrations function to execute goose postgres migrations
- Call run_migrations in RatingPlansRepo::connect before returning repository instance
- Update function comments to reflect automatic migration execution on startup
- Add error handling and output capture for migration failures
- Add tracing log for successful migration
2026-04-29 03:00:28 +03:00
nutcas3 eb5b9092c9 refactor: Remove inline schema creation from RatingPlansRepo in favor of centralized migration system
- Remove CREATE TABLE IF NOT EXISTS query for rating_plans table from connect() method
- Update comment to reference migration system (make db-migrate) instead of inline schema creation
- Add note that rating_plans table is created by 000001_init_rating_plans.up.sql migration
- Remove sqlx::query execution and error mapping for schema creation
- Keep database connection pool and circuit breaker initialization
2026-04-29 02:54:41 +03:00
nutcas3 4e5ad491ef refactor: Remove unused CircuitBreaker and ChargingError imports from charging-engine
- Remove unused CircuitBreaker import from credit_management.rs
- Remove unused ChargingError import from engine.rs
- Keep CircuitBreakerError import in credit_management.rs
- Keep CircuitBreaker import in engine.rs
2026-04-26 02:32:23 +03:00
nutcas3 db4d8bf56a refactor: Re-enable rate limiter with environment variable configuration in charging-engine routes
- Add tower_governor imports (GovernorConfigBuilder and GovernorLayer)
- Remove commented-out rate_limit module import
- Add environment variable parsing for RATE_LIMIT_RPS (default: 10) and RATE_LIMIT_BURST (default: 20)
- Create GovernorConfigBuilder with per_second and burst_size configuration
- Replace commented-out rate_limiter layer with GovernorLayer::new(governor_conf)
2026-04-26 02:32:14 +03:00
nutcas3 2094a3b952 refactor: Simplify rate limiter to use default configuration in charging-engine
- Remove unused imports: governor clock/state/Quota, std::num::NonZeroU32, std::sync::Arc, and SmartIpKeyExtractor
- Change create_rate_limiter return type from explicit generic parameters to simple GovernorLayer
- Replace custom rate limit configuration (RATE_LIMIT_RPS, RATE_LIMIT_BURST environment variables) with GovernorConfig::default()
- Remove quota builder logic and pass config directly to GovernorLayer::new()
2026-04-26 02:31:59 +03:00
nutcas3 186bba04a8 refactor: Remove duplicate imports and comment out rate limiter implementation in charging-engine
- Remove duplicate CreditManager and RatingPlansRepo imports from engine.rs
- Add circuit_breaker module to main.rs imports
- Comment out rate_limit module in lib.rs
- Update rate_limit.rs imports to use GovernorConfig and GovernorLayer directly
- Change GovernorConfigBuilder to GovernorConfig::builder() and update config initialization
- Update GovernorLayer::new() to take config reference
2026-04-26 02:17:26 +03:00
nutcas3 a4aec94314 refactor: Re-enable circuit breaker implementation in charging-engine credit management and rating plans
- Uncomment CircuitBreaker and CircuitBreakerError imports in credit_management.rs and rating_plans_repo.rs
- Re-enable redis_circuit_breaker execute calls for all Redis operations (get_balance, add_credit, deduct_credit, block_user, unblock_user, is_user_blocked, get_subscriber_account, update_subscriber_account, record_usage_event)
- Re-enable postgres circuit_breaker execute calls for all database operations
2026-04-26 02:13:07 +03:00
nutcas3 95def1bcab refactor: Re-enable circuit breaker implementation and add conditional eBPF compilation support
- Uncomment CircuitBreaker and CircuitBreakerError imports in charging-engine
- Re-enable redis_circuit_breaker and postgres_circuit_breaker fields in ChargingEngine struct
- Add circuit breaker initialization with environment variable configuration (REDIS_FAILURE_THRESHOLD, REDIS_TIMEOUT, POSTGRES_FAILURE_THRESHOLD, POSTGRES_TIMEOUT)
- Add #[cfg(feature = "ebpf")] conditional compilation directives throughout
2026-04-26 01:50:29 +03:00
nutcas3 d5ebb3bfd8 refactor: Comment out circuit breaker implementation and remove thiserror dependency
- Remove thiserror 2.0.18 dependency from Cargo.toml
- Comment out CircuitBreakerError import and all circuit breaker execute calls in credit_management.rs
- Comment out redis_circuit_breaker and postgres_circuit_breaker fields in ChargingEngine struct
- Comment out circuit breaker initialization code in engine.rs
- Comment out circuit_breaker field and initialization in RatingPlansRepo
- Remove circuit breaker
2026-04-26 01:15:58 +03:00
nutcas3 b6bcad067b refactor: Update rate limiter to use StateInformationMiddleware and QuantaClock
- Change create_rate_limiter return type from InMemoryState/DefaultClock to StateInformationMiddleware with QuantaClock
- Add StateInformationMiddleware import from governor::middleware
- Add Arc import from std::sync
- Remove explicit key_extractor field from GovernorLayer initialization
2026-04-26 00:44:00 +03:00
nutcas3 b4b0966937 refactor: Update charging-engine dependencies and fix rate limiter configuration
- Upgrade tower_governor from 0.4.2 to 0.8.0 and add governor 0.10.4 dependency
- Add thiserror 2.0.18 for error handling
- Update dev dependencies: tokio-test to 0.4.5, mockall to 0.14.0, serial_test to 3.4.0
- Add Copy trait to CircuitState enum
- Add Clone derive to CircuitBreaker struct
- Add error trait bounds to CircuitBreakerError generic type
- Update create_rate_limiter return type to use explicit generic parameters
- Fix Go
2026-04-26 00:42:19 +03:00
nutcas3 f5b22063e3 feat: Add configurable authentication enforcement to charging engine with ENFORCE_AUTH environment variable
- Add ENFORCE_AUTH environment variable with true default to auth middleware
- Add early return when ENFORCE_AUTH=false for development/testing bypass
- Replace development comment with UNAUTHORIZED status code when no valid authentication found
- Move authentication bypass logic from end of function to environment-based check at start
2026-04-25 06:02:06 +03:00
nutcas3 0bb8571b02 feat: Add IP-based rate limiting to charging engine with configurable RPS and burst size
- Add rate_limit module to lib.rs exports
- Add create_rate_limiter function with SmartIpKeyExtractor for IP-based limiting
- Add RATE_LIMIT_RPS environment variable with 10 requests/second default
- Add RATE_LIMIT_BURST environment variable with 20 burst size default
- Add RateLimitResponse struct with TOO_MANY_REQUESTS status code
- Add GovernorLayer with per_second quota and burst_size configuration to router
2026-04-25 06:01:42 +03:00
nutcas3 ce560c0dc4 feat: Add rate limiting with tower-governor and update health endpoint path to /v1/health
- Add tower-governor 0.4.2 dependency to Cargo.toml
- Update health check route from /health to /v1/health for API versioning consistency
2026-04-25 05:58:26 +03:00
nutcas3 d6035c1848 feat: Wrap Redis and PostgreSQL operations in circuit breakers for fault tolerance
- Add CircuitBreakerError import and error mapping to ChargingError::RedisConnection/DatabaseError
- Add redis_circuit_breaker and postgres_circuit_breaker fields to ChargingEngine struct
- Add circuit_breaker field to RatingPlansRepo struct
- Wrap all Redis operations (get_balance, add_credit, deduct_credit, block_user, unblock_user, is_user_blocked, get_subscriber_account, update_subscriber_account, record_usage
2026-04-25 05:49:43 +03:00
nutcas3 f909952320 feat: Add circuit breaker implementation to charging engine with configurable failure threshold and timeout
- Add CircuitState enum with Closed, Open, and HalfOpen states
- Add CircuitBreakerError enum wrapping Open state and inner errors
- Add CircuitBreaker struct with failure_count, failure_threshold, timeout, and last_failure_time fields
- Add execute method with async operation wrapper and state-based error handling
- Add check_state method with automatic Open to HalfOpen transition after timeout
- Add on_success method
2026-04-25 05:49:09 +03:00
nutcas3 e839ffb519 feat: Add precision handling and overflow protection to monthly fee billing
- Add rounding to monthly fee conversion to cents to prevent precision loss
- Replace direct subtraction with saturating_sub to prevent i64 underflow
- Add fee_cents variable for clearer monthly fee calculation in billing cycle
2026-04-25 05:28:43 +03:00
nutcas3 e4b32a096a feat: Add overflow protection to credit addition in charging engine
- Add current balance retrieval before credit increment operation
- Add checked_add validation to prevent u64 overflow when adding credits
- Add InvalidInput error return when credit addition would cause overflow
- Add overflow check between get and incr operations on Redis credit key
2026-04-25 05:28:33 +03:00
nutcas3 7428ed2314 feat: Add API key authentication support to charging-engine auth middleware
- Add api_keys field to AuthConfig struct
- Parse API_KEYS environment variable as comma-separated list in from_env
- Add validate_api_key method to AuthConfig for key verification
- Add X-API-Key header check in auth_middleware before JWT validation
- Update comments to clarify development/testing mode for unauthenticated requests
2026-04-25 03:42:42 +03:00
nutcas3 3cef1fbf03 feat: Add authentication middleware to charging-engine with public and protected route separation
- Add auth module import to main.rs
- Add AuthConfig initialization from environment in main function
- Add auth_config field to AppState struct
- Add auth_middleware layer to protected routes
- Move health check, credit check, deduct, balance, and usage recording to public routes (no auth required for packet-gateway integration)
- Move add credit, subscriber management, rating plans, monitoring, and engine
2026-04-25 03:38:14 +03:00
nutcas3 a41431c17a feat: Add jsonwebtoken dependency to charging-engine for JWT authentication support
- Add jsonwebtoken 10.3.0 dependency to Cargo.toml
2026-04-25 03:37:59 +03:00
nutcas3 c341f4462e feat: Add JWT authentication middleware and token management for charging engine
- Add Claims struct with sub and exp fields for JWT payload
- Add AuthConfig struct with secret field loaded from JWT_SECRET environment variable
- Add create_token function generating 24-hour expiration tokens
- Add validate_token function for JWT verification
- Add auth_middleware for Axum with Authorization header Bearer token validation
- Allow unauthenticated requests temporarily for packet-gateway integration
2026-04-25 03:36:52 +03:00
nutcas3 201ecdf62f feat: Add auth module export to charging-engine library
- Add public auth module export to lib.rs
2026-04-25 03:33:56 +03:00
nutcas3 05eb31e117 feat: Add comprehensive unit tests for charging engine components
- Add credit_management_tests.rs with tests for SubscriberAccount, UsageEvent, UsageType, AccountStatus, and integer arithmetic operations
- Add error_tests.rs with tests for ChargingError Display implementation, cloning, and log_error function
- Add rating_billing_tests.rs with tests for ChargingRule variants, as_str conversion, billing period parsing, timestamp filtering, and cost calculations
- Add validation_tests.rs with tests for validate_bytes, validate
2026-04-25 03:17:21 +03:00
nutcas3 4cdecfc932 feat: Add library module exports for charging engine components
- Add public module exports for charging, errors, handlers, routes, models, and monitoring
2026-04-25 03:17:04 +03:00
nutcas3 379dc251d3 feat: Add library configuration and test dependencies to charging-engine
- Add [lib] section with charging_engine name and src/lib.rs path
- Add dev-dependencies: tokio-test 0.4, mockall 0.13, serial_test 3.2
2026-04-25 03:16:53 +03:00
nutcas3 2dd6c3304d feat: Add configurable expiration times for credit and block operations via environment variables
- Add CREDIT_EXPIRATION_SECONDS environment variable to configure credit key expiration (defaults to 86400)
- Add BLOCK_EXPIRATION_SECONDS environment variable to configure block key expiration (defaults to 86400)
- Replace hardcoded 86400 expiration values with configurable variables in add_credit and block_user
- Update block_user warning message to include expiration duration
2026-04-25 03:06:37 +03:00
nutcas3 ff33263df3 feat: Add configurable limits for bytes and amount validation via environment variables
- Add MAX_BYTES_LIMIT environment variable to configure bytes validation limit (defaults to 1TB)
- Add MAX_AMOUNT_LIMIT environment variable to configure amount validation limit (defaults to 10,000)
- Replace hardcoded 1_000_000_000_000 bytes limit with configurable max_bytes value
- Replace hardcoded 10_000.0 amount limit with configurable max_amount value
2026-04-25 03:05:40 +03:00
nutcas3 c4746970a2 feat: Add DatabaseError variant and improve error response handling
- Add DatabaseError(String) variant to ChargingError enum
- Add DatabaseError case to log_error helper with error-level logging
- Add DatabaseError Display implementation
- Refactor IntoResponse to use generic error messages instead of detailed strings
- Add detail field to error responses containing full error message via to_string()
- Change RedisConnection status code from INTERNAL_SERVER_ERROR to SERVICE_UNAVAILABLE
2026-04-25 03:04:25 +03:00
nutcas3 c9c493fd70 feat: Add ChargingRule enum with string conversion for charging decisions
- Add ChargingRule enum with 7 variants (Allowed, InsufficientCredit, DataLimitExceeded, VoiceLimitExceeded, SmsLimitExceeded, UserBlocked, Blocked)
- Add Debug, Clone, Serialize, Deserialize, PartialEq, Eq derives to ChargingRule
- Add as_str method to convert ChargingRule variants to uppercase string constants
2026-04-25 03:03:37 +03:00
nutcas3 7e47f09e54 feat: Replace RedisOperation with DatabaseError in rating_plans_repo error mapping
- Replace RedisOperation error variant with DatabaseError in new/get/list_map/add/remove methods
- Update 5 map_err calls to use DatabaseError for SQLx operation failures
2026-04-25 03:03:27 +03:00
nutcas3 69a84d85e6 feat: Improve rating_billing with integer arithmetic, overflow checks, and SCAN optimization
- Replace float division with integer arithmetic in calculate_usage_cost for data/voice conversions
- Add checked_add overflow protection for usage accumulation in apply_charging_rules and process_usage
- Replace String-based charging rules with ChargingRule enum variants
- Add Datelike import and implement billing period filtering in generate_invoice
- Replace blocking KEYS command with SCAN cursor iteration
2026-04-25 03:03:06 +03:00
nutcas3 3c5878d3cc feat: Replace unwrap_or with proper error handling in credit_management
- Replace unwrap_or(0) with map_err for get operation in deduct_credit
- Replace unwrap_or(0) with ? operator in check_credit
- Add RedisOperation error mapping for current_balance retrieval
2026-04-25 03:02:36 +03:00
nutcas3 40e9d1f221 remove comments 2026-04-25 02:52:41 +03:00
nutcas3 c37ba6c8f2 feat: Remove handlers module and relocate 25+ API handler functions
- Delete handlers.rs module containing credit management handlers (check_credit, deduct_credit, add_credit, get_balance)
- Remove subscriber account handlers (get_subscriber, update_subscriber)
- Remove usage event handlers (record_usage, calculate_usage_cost, rate_usage, process_usage)
- Remove rating plan handlers (list_rating_plans, get_rating_plan, add_rating_plan, remove_rating_plan)
- Remove user blocking handlers (block_user, unblock_user,
2026-04-25 02:52:27 +03:00
nutcas3 69c54c4a35 feat: Remove dead_code attributes and add duplicate block check to block_user
- Remove dead_code attributes from get_balance/add_credit/start/stop/uptime/rating plan methods in credit_management and engine
- Remove dead_code attributes from calculate_usage_cost in rating_billing
- Remove dead_code attributes from get/list_map/deactivate methods in rating_plans_repo and row_to_plan function
- Remove dead_code attributes from get_performance_metrics/start_background_sync in monitoring modules
2026-04-25 02:43:57 +03:00
nutcas3 607040da6c feat: Add usage processing and invoice generation API endpoints
- Add POST /v1/usage/calculate-cost endpoint to calculate usage cost for events
- Add POST /v1/usage/rate endpoint to rate usage events
- Add POST /v1/usage/process endpoint for full rating and billing processing
- Add GET /v1/invoice/:imsi/:period endpoint to generate invoices for billing periods
- Add list_map call to list_rating_plans handler for internal lookups
- Add session_id validation to all usage endpoints using validate_session_id helper
2026-04-25 02:43:22 +03:00