CocoaPods trunk is moving to be read-only. Read more on the blog, there are 16 months to go.

Monstra 0.1.0

Monstra 0.1.0

Maintained by larkin.



Monstra 0.1.0

  • By
  • Larkin

Monstra

Swift Platform License Swift Package Manager CocoaPods

A high-performance Swift framework providing efficient task execution, memory caching, and data management utilities with intelligent execution merging, TTL caching, and retry logic.

πŸš€ Features

  • ⚑ 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

πŸ“¦ Components

Core Components

  • 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

Detailed Components

  • 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

πŸ—οΈ Architecture

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

πŸš€ Quick Start

Installation

Swift Package Manager (Recommended)

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:

  1. File β†’ Add Package Dependencies
  2. Enter the repository URL: https://github.com/yangchenlarkin/Monstra.git
  3. Select the version you want to use

CocoaPods

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

Basic Usage

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

TTL Cache Usage

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

Task Execution with MonoTask

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

πŸ“Š Performance

Time Complexity

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)

Benchmark Results

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.

πŸ§ͺ Testing

Running Tests

# 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

Test Coverage

  • βœ… Unit tests for all components
  • βœ… Performance benchmarks
  • βœ… Scale testing (10,000 operations)
  • βœ… Time complexity verification
  • βœ… Memory usage analysis
  • βœ… Thread safety considerations

πŸ”§ Development

Prerequisites

  • Swift 5.10+
  • Xcode 15+ (for iOS/macOS development)
  • SwiftLint and SwiftFormat

Setup

# 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 .

πŸ“š API Reference

LRUQueue

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 }
}

TTLPriorityLRUQueue

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?
}

MonoTask

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 }
}

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Workflow

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ—ΊοΈ Roadmap

  • Thread-safe variants
  • Disk persistence support
  • Compression algorithms
  • Advanced eviction policies
  • Metrics and monitoring
  • SwiftUI integration examples

πŸ“ž Support

πŸ™ Acknowledgments

  • 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