|
| 1 | +# Hasty Server Architecture |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +Hasty Server is a lightweight, educational HTTP server framework built from scratch using Node.js raw TCP sockets. It provides Express.js-like functionality without any third-party dependencies, making it perfect for learning HTTP internals and server architecture. |
| 6 | + |
| 7 | +## Core Architecture |
| 8 | + |
| 9 | +### 1. Modular Design |
| 10 | + |
| 11 | +The server is organized into distinct modules, each with a specific responsibility: |
| 12 | + |
| 13 | +``` |
| 14 | +hasty-server/ |
| 15 | +├── server/ |
| 16 | +│ ├── index.js # Main server class and routing logic |
| 17 | +│ └── response.js # HTTP response handling |
| 18 | +├── lib/ |
| 19 | +│ ├── httpParser.js # HTTP request parsing |
| 20 | +│ ├── cors.js # CORS utilities |
| 21 | +│ ├── utils.js # General utilities |
| 22 | +│ └── mimeDb.js # MIME type database |
| 23 | +└── test-server.js # Example usage |
| 24 | +``` |
| 25 | + |
| 26 | +### 2. Request/Response Flow |
| 27 | + |
| 28 | +``` |
| 29 | +Incoming TCP Connection |
| 30 | + ↓ |
| 31 | + Socket Handler |
| 32 | + ↓ |
| 33 | + HTTP Parser (lib/httpParser.js) |
| 34 | + ↓ |
| 35 | + Route Matcher (server/index.js) |
| 36 | + ↓ |
| 37 | + Route Handler (user-defined) |
| 38 | + ↓ |
| 39 | + Response Builder (server/response.js) |
| 40 | + ↓ |
| 41 | + CORS Headers (lib/cors.js) |
| 42 | + ↓ |
| 43 | + TCP Socket Response |
| 44 | +``` |
| 45 | + |
| 46 | +## Core Components |
| 47 | + |
| 48 | +### 1. Server Class (`server/index.js`) |
| 49 | + |
| 50 | +**Purpose**: Main server orchestration and routing |
| 51 | + |
| 52 | +**Key Features**: |
| 53 | +- TCP server creation and management |
| 54 | +- Route registration and matching |
| 55 | +- Request lifecycle management |
| 56 | +- Error handling and timeouts |
| 57 | + |
| 58 | +**Architecture**: |
| 59 | +```javascript |
| 60 | +class Hasty extends Server { |
| 61 | + // Route registration methods (get, post, put, delete, etc.) |
| 62 | + // CORS configuration |
| 63 | + // Static file serving |
| 64 | + // Server lifecycle management |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +### 2. Response Class (`server/response.js`) |
| 69 | + |
| 70 | +**Purpose**: HTTP response construction and sending |
| 71 | + |
| 72 | +**Key Features**: |
| 73 | +- Chainable API (`res.status(200).json(data)`) |
| 74 | +- Multiple response types (JSON, files, streams) |
| 75 | +- Automatic content-type detection |
| 76 | +- CORS header integration |
| 77 | + |
| 78 | +**Architecture**: |
| 79 | +```javascript |
| 80 | +class Response { |
| 81 | + // Status code management |
| 82 | + // Header manipulation |
| 83 | + // Content sending (send, json, sendFile, download) |
| 84 | + // CORS integration |
| 85 | +} |
| 86 | +``` |
| 87 | + |
| 88 | +### 3. HTTP Parser (`lib/httpParser.js`) |
| 89 | + |
| 90 | +**Purpose**: Raw HTTP request parsing |
| 91 | + |
| 92 | +**Key Features**: |
| 93 | +- Request line parsing (method, path, version) |
| 94 | +- Header parsing with validation |
| 95 | +- Body parsing (JSON, form-urlencoded) |
| 96 | +- Query string parsing |
| 97 | +- Safe fallbacks for malformed requests |
| 98 | + |
| 99 | +### 4. CORS Utility (`lib/cors.js`) |
| 100 | + |
| 101 | +**Purpose**: Centralized CORS handling |
| 102 | + |
| 103 | +**Key Features**: |
| 104 | +- Default CORS headers |
| 105 | +- Preflight OPTIONS handling |
| 106 | +- Configurable CORS policies |
| 107 | + |
| 108 | +## Data Flow |
| 109 | + |
| 110 | +### 1. Connection Handling |
| 111 | + |
| 112 | +```javascript |
| 113 | +// 1. TCP connection established |
| 114 | +socket.on('data', (chunk) => { |
| 115 | + // 2. Accumulate request data |
| 116 | + requestData = Buffer.concat([requestData, chunk]); |
| 117 | + |
| 118 | + // 3. Check for complete request |
| 119 | + if (requestData.includes('\r\n\r\n')) { |
| 120 | + processRequest(socket, requestData, context); |
| 121 | + } |
| 122 | +}); |
| 123 | +``` |
| 124 | + |
| 125 | +### 2. Request Processing |
| 126 | + |
| 127 | +```javascript |
| 128 | +async function processRequest(socket, requestData, context) { |
| 129 | + // 1. Parse HTTP request |
| 130 | + const req = await httpParser(requestData.toString()); |
| 131 | + |
| 132 | + // 2. Handle CORS preflight |
| 133 | + if (req.method === 'OPTIONS' && context.enableCors) { |
| 134 | + return handlePreflight(res); |
| 135 | + } |
| 136 | + |
| 137 | + // 3. Find matching route |
| 138 | + const route = findMatchingRoute(req.method, req.path, context.routes); |
| 139 | + |
| 140 | + // 4. Extract parameters and query |
| 141 | + req.params = extractParams(route.path, req.path); |
| 142 | + req.query = parseQuery(req.path); |
| 143 | + |
| 144 | + // 5. Execute route handler |
| 145 | + await route.callback(req, res); |
| 146 | +} |
| 147 | +``` |
| 148 | + |
| 149 | +### 3. Route Matching |
| 150 | + |
| 151 | +The server uses a two-phase matching strategy: |
| 152 | + |
| 153 | +1. **Exact Match**: Direct path comparison |
| 154 | +2. **Parameter Match**: Pattern matching with `:param` syntax |
| 155 | + |
| 156 | +```javascript |
| 157 | +// Route: /users/:id |
| 158 | +// Path: /users/123 |
| 159 | +// Result: { params: { id: '123' } } |
| 160 | +``` |
| 161 | + |
| 162 | +### 4. Response Generation |
| 163 | + |
| 164 | +```javascript |
| 165 | +class Response { |
| 166 | + send(data) { |
| 167 | + // 1. Apply CORS headers if enabled |
| 168 | + this._applyCorsHeaders(); |
| 169 | + |
| 170 | + // 2. Set content headers |
| 171 | + this.setHeader('Content-Type', contentType); |
| 172 | + this.setHeader('Content-Length', contentLength); |
| 173 | + |
| 174 | + // 3. Send HTTP response |
| 175 | + this.socket.write(`HTTP/1.1 ${statusCode} ${statusText}\r\n${headers}\r\n\r\n`); |
| 176 | + this.socket.write(data); |
| 177 | + } |
| 178 | +} |
| 179 | +``` |
| 180 | + |
| 181 | +## Type Safety |
| 182 | + |
| 183 | +The entire codebase uses JSDoc annotations for TypeScript compatibility: |
| 184 | + |
| 185 | +```javascript |
| 186 | +/** |
| 187 | + * @typedef {Object} Route |
| 188 | + * @property {string} method - HTTP method |
| 189 | + * @property {string} path - URL path pattern |
| 190 | + * @property {Function} callback - Route handler |
| 191 | + */ |
| 192 | + |
| 193 | +/** |
| 194 | + * Registers a route with the server |
| 195 | + * @param {string} method - HTTP method |
| 196 | + * @param {string} path - URL path pattern |
| 197 | + * @param {Function} callback - Route handler |
| 198 | + */ |
| 199 | +_registerRoute(method, path, callback) { ... } |
| 200 | +``` |
| 201 | + |
| 202 | +## Error Handling |
| 203 | + |
| 204 | +### 1. Connection Level |
| 205 | +- Socket timeouts (30 seconds) |
| 206 | +- Connection error handling |
| 207 | +- Resource cleanup |
| 208 | + |
| 209 | +### 2. Request Level |
| 210 | +- Malformed HTTP request handling |
| 211 | +- Invalid route handling (404) |
| 212 | +- Route handler errors (500) |
| 213 | + |
| 214 | +### 3. Response Level |
| 215 | +- Header validation |
| 216 | +- Stream error handling |
| 217 | +- File serving errors |
| 218 | + |
| 219 | +## Security Features |
| 220 | + |
| 221 | +### 1. Input Validation |
| 222 | +- HTTP method validation |
| 223 | +- Path normalization |
| 224 | +- Parameter URL decoding |
| 225 | + |
| 226 | +### 2. File Serving Security |
| 227 | +- Directory traversal prevention |
| 228 | +- Safe path joining |
| 229 | +- MIME type validation |
| 230 | + |
| 231 | +### 3. Resource Management |
| 232 | +- Connection timeouts |
| 233 | +- Memory-efficient streaming |
| 234 | +- Proper socket cleanup |
| 235 | + |
| 236 | +## Performance Considerations |
| 237 | + |
| 238 | +### 1. Efficient Parsing |
| 239 | +- Single-pass HTTP parsing |
| 240 | +- Minimal memory allocation |
| 241 | +- Stream-based file serving |
| 242 | + |
| 243 | +### 2. Route Optimization |
| 244 | +- Exact match priority |
| 245 | +- Efficient parameter extraction |
| 246 | +- Route caching potential |
| 247 | + |
| 248 | +### 3. Connection Management |
| 249 | +- Non-blocking I/O |
| 250 | +- Connection pooling ready |
| 251 | +- Graceful shutdown support |
| 252 | + |
| 253 | +## Usage Examples |
| 254 | + |
| 255 | +### Basic Server |
| 256 | +```javascript |
| 257 | +const Hasty = require('./server/index.js'); |
| 258 | +const app = new Hasty(); |
| 259 | + |
| 260 | +app.cors(true); |
| 261 | +app.get('/', (req, res) => { |
| 262 | + res.json({ message: 'Hello World!' }); |
| 263 | +}); |
| 264 | + |
| 265 | +app.listen(3000); |
| 266 | +``` |
| 267 | + |
| 268 | +### Advanced Features |
| 269 | +```javascript |
| 270 | +// Parameterized routes |
| 271 | +app.get('/users/:id', (req, res) => { |
| 272 | + res.json({ userId: req.params.id }); |
| 273 | +}); |
| 274 | + |
| 275 | +// Static file serving |
| 276 | +app.static('./public', { prefix: '/assets' }); |
| 277 | + |
| 278 | +// Custom CORS handling |
| 279 | +app.options('/api/*', (req, res) => { |
| 280 | + res.status(200).end(); |
| 281 | +}); |
| 282 | +``` |
| 283 | + |
| 284 | +## Educational Value |
| 285 | + |
| 286 | +This architecture demonstrates: |
| 287 | +- Raw TCP socket programming |
| 288 | +- HTTP protocol implementation |
| 289 | +- Asynchronous JavaScript patterns |
| 290 | +- Modular code organization |
| 291 | +- Type-safe JavaScript development |
| 292 | +- Security best practices |
| 293 | +- Performance optimization techniques |
| 294 | + |
| 295 | +The codebase serves as an excellent learning resource for understanding how modern web frameworks work under the hood while maintaining production-ready code quality. |
0 commit comments