A high-performance Swift framework providing efficient task execution, memory caching, and data management utilities with intelligent execution merging, TTL caching, and retry logic.
- β‘ High Performance: O(1) time complexity for core operations
- π§ Memory Efficient: Object pooling and optimized data structures
- β° TTL Support: Automatic expiration with time-to-live functionality
- π‘οΈ Thread Safe: Designed for concurrent access patterns
- π Comprehensive Testing: Extensive unit and performance tests
- π Performance Benchmarked: Detailed performance analysis and comparisons
- π Task Execution: Intelligent execution merging and caching
- π Retry Logic: Configurable retry strategies with exponential backoff
- π― Queue Management: Separate queues for execution and callbacks
- MonstraBase: Foundation utilities including CPUTimeStamp, Heap, and data structures
- Monstore: Memory caching system with LRU and TTL support
- Monstask: Task execution framework with caching and retry logic
- LRUQueue: High-performance LRU cache implementation with optimized doubly-linked list
- TTLPriorityLRUQueue: LRU cache with automatic time-to-live (TTL) expiration
- Heap: Efficient heap data structure implementation
- CPUTimeStamp: High-precision CPU timestamp utilities for performance measurement
- MemoryCache: Core memory caching functionality
- MonoTask: Single-instance task executor with TTL caching and retry logic
Monstra/
βββ Sources/
β βββ MonstraBase/ # Foundation utilities
β β βββ CPUTimeStamp.swift # High-precision timing
β β βββ Heap.swift # Efficient heap data structure
β β βββ DoublyLink.swift # Doubly-linked list implementation
β β βββ HashQueue.swift # Hash-based queue
β βββ Monstore/ # Memory caching system
β β βββ MemoryCache/ # LRU and TTL cache implementations
β βββ Monstask/ # Task execution framework
β βββ MonoTask.swift # Single-instance task executor
β βββ KVHeavyTasksManager.swift # Heavy task management
β βββ KVLightTasksManager.swift # Light task management
βββ Tests/ # Comprehensive test suite
βββ MonstraBaseTests/ # Foundation utility tests
βββ MonstoreTests/ # Caching system tests
βββ MonstaskTests/ # Task execution tests
Add Monstra to your Package.swift
:
dependencies: [
.package(url: "https://github.com/yangchenlarkin/Monstra.git", from: "1.0.0")
]
Or add it directly in Xcode:
- File β Add Package Dependencies
- Enter the repository URL:
https://github.com/yangchenlarkin/Monstra.git
- Select the version you want to use
Add Monstra to your Podfile
:
pod 'Monstra'
Or specify specific components:
pod 'Monstra/MonstraBase' # Foundation utilities only
pod 'Monstra/Monstore' # Caching system only
pod 'Monstra/Monstask' # Task execution only
import Monstore
// Create an LRU cache with capacity 100
let cache = LRUQueue<String, Int>(capacity: 100)
// Set values
cache.setValue(42, for: "answer")
cache.setValue(100, for: "score")
// Get values
let answer = cache.getValue(for: "answer") // Returns 42
// Remove values
let removed = cache.removeValue(for: "score") // Returns 100
// Check status
print(cache.count) // Current number of items
print(cache.isEmpty) // Whether cache is empty
print(cache.isFull) // Whether cache is at capacity
import Monstore
// Create TTL cache with automatic expiration
let ttlCache = TTLPriorityLRUQueue<String, Int>(capacity: 100)
// Set value with TTL (expires in 5 seconds)
ttlCache.unsafeSet(value: 42, for: "answer", expiredIn: 5.0)
// Get value (returns nil if expired)
let answer = ttlCache.getValue(for: "answer")
// Wait for expiration...
Thread.sleep(forTimeInterval: 6.0)
let expired = ttlCache.getValue(for: "answer") // Returns nil
import Monstask
// Create a task with caching and retry logic
let networkTask = MonoTask<Data>(
retry: .count(count: 3, intervalProxy: .exponentialBackoff(initialTimeInterval: 1.0)),
resultExpireDuration: 300.0 // 5 minutes cache
) { callback in
// Your network request logic here
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
callback(.failure(error))
} else if let data = data {
callback(.success(data))
}
}.resume()
}
// Execute with async/await
let result = await networkTask.asyncExecute()
switch result {
case .success(let data):
print("Got data: \(data.count) bytes")
case .failure(let error):
print("Error: \(error)")
}
// Multiple concurrent calls - only one network request
let result1 = await networkTask.asyncExecute() // Network call happens
let result2 = await networkTask.asyncExecute() // Returns cached result
let result3 = await networkTask.asyncExecute() // Returns cached result
Operation | LRUQueue | TTLPriorityLRUQueue |
---|---|---|
Insert/Update | O(1) | O(1) |
Retrieve | O(1) | O(1) |
Remove | O(1) | O(1) |
TTL Management | N/A | O(log n) |
Based on comprehensive testing with 10,000 operations:
- LRUQueue: 97.3x time scaling (near-linear O(1))
- TTLPriorityLRUQueue: 79.7x time scaling (better than linear)
- Memory Usage: 50-60% less than NSCache
- Access Performance: Comparable to NSCache
See Performance Test Report for detailed benchmarks.
# Run all tests
swift test
# Run specific test suites
swift test --filter LRUQueueTests
swift test --filter PerformanceTests
swift test --filter ScaleTests
# Run with verbose output
swift test --verbose
- β Unit tests for all components
- β Performance benchmarks
- β Scale testing (10,000 operations)
- β Time complexity verification
- β Memory usage analysis
- β Thread safety considerations
- Swift 5.10+
- Xcode 15+ (for iOS/macOS development)
- SwiftLint and SwiftFormat
# Clone the repository
git clone https://github.com/yourusername/Monstra.git
cd Monstra
# Install development tools
brew install swiftlint swiftformat sourcekitten
# Build the project
swift build
# Run tests
swift test
# Run linting
swiftlint lint Sources/
# Format code
swiftformat .
class LRUQueue<K: Hashable, Element> {
init(capacity: Int)
func setValue(_ value: Element, for key: K) -> Element?
func getValue(for key: K) -> Element?
func removeValue(for key: K) -> Element?
var count: Int { get }
var isEmpty: Bool { get }
var isFull: Bool { get }
}
class TTLPriorityLRUQueue<Key: Hashable, Value> {
init(capacity: Int)
func unsafeSet(value: Value, for key: Key, expiredIn duration: TimeInterval) -> Value?
func getValue(for key: Key) -> Value?
func unsafeRemoveValue(for key: Key) -> Value?
}
class MonoTask<TaskResult> {
init(retry: RetryCount, resultExpireDuration: Double, taskQueue: DispatchQueue, callbackQueue: DispatchQueue, task: @escaping CallbackExecution)
func execute(then completionHandler: ResultCallback?)
func asyncExecute() async -> Result<TaskResult, Error>
func executeThrows() async throws -> TaskResult
func justExecute()
func clearResult(ongoingExecutionStrategy: OngoingExecutionStrategy)
var currentResult: TaskResult? { get }
var isExecuting: Bool { get }
}
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Thread-safe variants
- Disk persistence support
- Compression algorithms
- Advanced eviction policies
- Metrics and monitoring
- SwiftUI integration examples
- π Documentation
- π Issue Tracker
- π¬ Discussions
- π§ Email Support
- Inspired by high-performance cache implementations
- Built with Swift's excellent type system and performance characteristics
- Tested extensively for production readiness
Made with β€οΈ for the Swift community