# Asterisk: Technical Rundown ## Architecture Overview Asterisk is a Rust CLI application that combines intelligent route parsing with HTTP request handling. It uses a multi-stage matching system to find endpoints in server files and sends requests with configurable parameters. ## Core Components ### 1. CLI Interface - **clap**: Command-line argument parsing with structured type definitions - **colored**: Terminal output formatting and coloring ### 2. Route Detection - **regex**: Pattern matching for route definitions across frameworks - **strsim**: String similarity scoring for fuzzy endpoint matching - **glob**: File pattern matching for server file detection ### 3. HTTP Client - **reqwest**: Async HTTP client for making API requests - **tokio**: Async runtime for handling HTTP operations - **serde_json**: JSON serialization/deserialization ### 4. Error Handling - **thiserror**: Error type definitions and handling - **anyhow**: Error propagation and context ## How It Works ### 1. Server File Processing ```rust fn find_server_file(filename: &str) -> Result ``` - Locates server file using exact or pattern matching - Supports relative and absolute paths - Falls back to common server file patterns ### 2. Route Detection ```rust fn extract_routes(content: &str, method: &str) -> Vec ``` - Uses regex to find route definitions - Handles various framework syntaxes - Extracts full route paths ### 3. Endpoint Matching ```rust fn find_matching_endpoint(content: &str, endpoint: &str, method: &str) -> Option ``` - Three-stage matching: 1. Exact match 2. Partial path match 3. Fuzzy component match - Scores matches based on similarity - Handles API prefixes and variations ### 4. Request Handling ```rust async fn send_request(endpoint: &EndpointInfo, args: &Args) -> Result<(), AsteriskError> ``` - Builds request with headers and body - Handles authentication - Measures request timing - Formats response output ## Key Features Implementation ### Intelligent Route Matching - Removes common API prefixes - Component-level matching - Fuzzy string similarity - Framework-specific patterns ### Framework Support - Express.js: `app.method('/path')` - NestJS: `@Method('/path')` - Spring: `@RequestMapping` - General: `router.method('/path')` ### Request Timing ```rust struct RequestTiming { start: Instant, first_byte: Option, end: Option, } ``` - Measures total request time - Tracks time to first byte - Handles async operations ## Dependencies Explained ### Core - **clap**: Modern argument parser with derive macros - **reqwest**: Feature-rich HTTP client with async support - **tokio**: Efficient async runtime for I/O operations ### Utility - **regex**: Fast pattern matching and extraction - **strsim**: String similarity algorithms (Jaro-Winkler) - **glob**: File system pattern matching ### Data Handling - **serde**: Serialization framework - **serde_json**: JSON support - **colored**: ANSI color formatting ### Error Management - **thiserror**: Custom error types - **anyhow**: Error context and propagation ## Performance Considerations - Lazy regex compilation - Efficient string matching algorithms - Async I/O operations - Minimal memory footprint - Fast binary startup time ## Security Features - No persistent data storage - Optional Bearer token support - Header validation - Safe JSON parsing - No shell command execution ## 🔄 Technical Data Flow ### 1. CLI Argument Processing 1. User invokes `asterisk` with arguments (e.g., `asterisk server.js users get`) 2. `main.rs` calls `Cli::new()` which: - Checks for help flag using `std::env::args()` - If help flag present, renders colorful help menu via `format_help()` - Otherwise, uses `clap` to parse arguments into `Cli` struct ### 2. Server File Processing 1. `main.rs` creates instances of core components: ```rust let logger = Logger::new(cli.verbose); let matcher = RouteMatcher::new(cli.verbose); let http_client = HttpClient::new(); ``` 2. Reads server file using `std::fs`: ```rust let server_file = Path::new(&cli.server_file); let content = fs::read_to_string(&server_file)?; ``` ### 3. Route Matching 1. `RouteMatcher` processes server file content: ```rust matcher.find_matching_endpoint(&content, &cli.endpoint, &cli.method) ``` 2. Uses regex patterns to extract routes: - Matches Express.js style routes (`app.get('/users', ...)`) - Supports various HTTP methods (GET, POST, PUT, etc.) 3. Performs matching in order: 1. Exact match check 2. Case-insensitive comparison 3. Fuzzy matching using Jaro-Winkler algorithm ### 4. HTTP Request Building 1. `HttpClient` constructs request: ```rust let headers = HttpClient::parse_headers(headers_str, token)?; let url = format!("{}{}", cli.url, endpoint); ``` 2. Header processing: - Parses custom headers from "key:value" format - Adds Bearer token if provided - Sets content type for JSON bodies ### 5. Request Execution 1. `HttpClient` sends request: ```rust let (status, body, timing) = http_client .send_request(&url, &cli.method, headers, body) .await?; ``` 2. Measures request timing: - Records start time - Tracks total execution time - Formats timing information ### 6. Response Processing 1. `Logger` formats and displays response: ```rust logger.response(status, &timing, &body); ``` 2. In verbose mode: - Shows detailed status information - Pretty-prints JSON responses - Displays timing metrics 3. In normal mode: - Shows concise status code - Displays raw response - Shows basic timing ### 7. Error Handling 1. Uses custom `AsteriskError` enum for all errors: ```rust pub enum AsteriskError { NoServerFile, Io(std::io::Error), Http(reqwest::Error), InvalidHeaders, NoEndpointMatch, InvalidJson(String), } ``` 2. Error propagation through `Result` types 3. Friendly error messages via `thiserror` derive macro ## 📖 Command Manual ``` 🌟 Asterisk CLI Universal API Testing Tool USAGE: asterisk ARGUMENTS: SERVER_FILE Path to server file (e.g., server.js) ENDPOINT API endpoint to test (e.g., users) METHOD HTTP method (GET, POST, etc.) OPTIONS: -b, --body Request body -H, --headers HTTP headers (key:value,...) -t, --token Bearer token -u, --url Base URL [default: http://localhost:3000] -v, --verbose Enable detailed output -h, --help Show this help message COMMANDS: list List all available endpoints info Show endpoint details EXAMPLES: Basic request: asterisk server.js users get With body: asterisk server.js sign-up post -b '{"name":"john"}' List endpoints: asterisk server.js list With token: asterisk server.js users get -t 'mytoken' 5. Custom Base URL: ```bash asterisk server.js health get -u "https://api.example.com" ``` - Tests GET /health endpoint - Uses custom base URL - Supports HTTPS 6. Testing Specific URL: ```bash asterisk server.js users/123/profile get -u "https://api.production.com" -H "X-API-Version:2" -v ``` - Tests GET /users/123/profile endpoint - Uses production API URL - Adds API version header - Shows verbose output with: ``` Response Details: Status Code: 200 Status Text: OK Performance: Total: 123ms (First byte: 89ms) Response Body: { "user_id": 123, "name": "John Doe", "email": "john@example.com", "created_at": "2024-01-20T10:30:00Z", "preferences": { "theme": "dark", "notifications": true } } ``` - Demonstrates real-world API interaction - Shows JSON pretty-printing in verbose mode