Class: Synthra::MockServer
- Inherits:
-
Object
- Object
- Synthra::MockServer
- Defined in:
- lib/synthra/mock_server.rb
Overview
Production-Ready Mock Server with Recording
A full-featured mock server that can:
- Serve generated data via REST API
- Record real API responses for replay
- Support multiple response modes
- Handle rate limiting and behaviors
Constant Summary collapse
- DEFAULT_PORT =
3000
Instance Attribute Summary collapse
-
#options ⇒ Object
readonly
Returns the value of attribute options.
-
#recordings ⇒ Object
readonly
Returns the value of attribute recordings.
-
#registry ⇒ Object
readonly
Returns the value of attribute registry.
Class Method Summary collapse
Instance Method Summary collapse
- #add_cors_headers(res) ⇒ Object private
- #apply_behaviors(schema, res) ⇒ Object private
- #banner ⇒ Object private
- #handle_batch_generate(req, res, schema_name) ⇒ Object private
- #handle_generate(req, res, schema_name) ⇒ Object private
- #handle_generate_with_overrides(req, res, schema_name) ⇒ Object private
- #handle_list_schemas(_req, res) ⇒ Object private
- #handle_recording(req, res, name) ⇒ Object private
- #handle_schema_info(_req, res, schema_name) ⇒ Object private
- #handle_stream_generate(req, res, schema_name) ⇒ Object private
-
#initialize(schema_dir:, **options) ⇒ MockServer
constructor
Create a new mock server.
- #load_recordings ⇒ Object private
- #normalize_schema_name(name) ⇒ Object private
- #parse_query_params(req) ⇒ Object private
- #rate_limited?(req) ⇒ Boolean private
- #record_response(schema_name, data) ⇒ Object private
- #route_request(req, res) ⇒ Object private
- #save_recordings ⇒ Object private
- #setup_routes ⇒ Object private
-
#start ⇒ Object
Start the mock server.
-
#start_async ⇒ Object
Start server in background thread.
-
#stop ⇒ Object
Stop the server.
- #to_snake_case(str) ⇒ Object private
Constructor Details
#initialize(schema_dir:, **options) ⇒ MockServer
Create a new mock server
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/synthra/mock_server.rb', line 40 def initialize(schema_dir:, **) @options = { port: DEFAULT_PORT, recording: false, recordings_dir: "recordings", cors: true, rate_limit: 0, default_mode: :random }.merge() @registry = Registry.new @registry.load_dir(schema_dir) @recordings = {} @request_counts = Hash.new(0) @last_reset = Time.now # Monitor (reentrant) so handle_recording can call save_recordings without self-deadlock. @mutex = Monitor.new load_recordings if @options[:recording] end |
Instance Attribute Details
#options ⇒ Object (readonly)
Returns the value of attribute options.
25 26 27 |
# File 'lib/synthra/mock_server.rb', line 25 def @options end |
#recordings ⇒ Object (readonly)
Returns the value of attribute recordings.
25 26 27 |
# File 'lib/synthra/mock_server.rb', line 25 def recordings @recordings end |
#registry ⇒ Object (readonly)
Returns the value of attribute registry.
25 26 27 |
# File 'lib/synthra/mock_server.rb', line 25 def registry @registry end |
Class Method Details
.start(**options) ⇒ Object
111 112 113 |
# File 'lib/synthra/mock_server.rb', line 111 def start(**) new(**).start end |
Instance Method Details
#add_cors_headers(res) ⇒ Object (private)
398 399 400 401 402 403 |
# File 'lib/synthra/mock_server.rb', line 398 def add_cors_headers(res) res["Access-Control-Allow-Origin"] = "*" res["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS" res["Access-Control-Allow-Headers"] = "Content-Type, Authorization" res["Access-Control-Max-Age"] = "86400" end |
#apply_behaviors(schema, res) ⇒ Object (private)
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
# File 'lib/synthra/mock_server.rb', line 381 def apply_behaviors(schema, res) schema.behaviors.each do |behavior| case behavior[:type] when :latency min_ms = behavior[:min_ms] || 0 max_ms = behavior[:max_ms] || min_ms delay = rand(min_ms..max_ms) / 1000.0 sleep(delay) when :failure if rand < (behavior[:rate] || 0) res.status = behavior[:status] || 500 throw :response_sent end end end end |
#banner ⇒ Object (private)
118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/synthra/mock_server.rb', line 118 def <<~BANNER ╔═══════════════════════════════════════════════════════════════╗ ║ ║ ║ 🎲 Synthra Mock Server ║ ║ ║ ║ Production-ready data generation API ║ ║ http://localhost:#{@options[:port].to_s.ljust(5)} ║ ║ ║ ╚═══════════════════════════════════════════════════════════════╝ BANNER end |
#handle_batch_generate(req, res, schema_name) ⇒ Object (private)
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |
# File 'lib/synthra/mock_server.rb', line 252 def handle_batch_generate(req, res, schema_name) schema_name = normalize_schema_name(schema_name) unless @registry.schema?(schema_name) res.status = 404 res["Content-Type"] = "application/json" res.body = JSON.generate({ error: "Schema not found" }) return end schema = @registry.schema(schema_name) params = parse_query_params(req) count = [params[:count] || 10, 10000].min data = schema.generate_many( count, seed: params[:seed], mode: params[:mode] || @options[:default_mode], registry: @registry ) apply_behaviors(schema, res) res["Content-Type"] = "application/json" res.body = JSON.pretty_generate({ data: data, meta: { count: data.length, seed: params[:seed], mode: (params[:mode] || @options[:default_mode]).to_s, schema: schema_name } }) end |
#handle_generate(req, res, schema_name) ⇒ Object (private)
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
# File 'lib/synthra/mock_server.rb', line 190 def handle_generate(req, res, schema_name) schema_name = normalize_schema_name(schema_name) unless @registry.schema?(schema_name) res.status = 404 res["Content-Type"] = "application/json" res.body = JSON.generate({ error: "Schema not found", schema: schema_name, available: @registry.names }) return end schema = @registry.schema(schema_name) params = parse_query_params(req) data = schema.generate( seed: params[:seed], mode: params[:mode] || @options[:default_mode], registry: @registry ) # Apply behaviors (latency, failure) apply_behaviors(schema, res) res["Content-Type"] = "application/json" res.body = JSON.pretty_generate(data) record_response(schema_name, data) if @options[:recording] end |
#handle_generate_with_overrides(req, res, schema_name) ⇒ Object (private)
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
# File 'lib/synthra/mock_server.rb', line 222 def handle_generate_with_overrides(req, res, schema_name) schema_name = normalize_schema_name(schema_name) unless @registry.schema?(schema_name) res.status = 404 res["Content-Type"] = "application/json" res.body = JSON.generate({ error: "Schema not found" }) return end schema = @registry.schema(schema_name) body = JSON.parse(req.body || "{}") rescue {} overrides = body["overrides"] || {} count = body["count"] || 1 seed = body["seed"] mode = (body["mode"] || @options[:default_mode]).to_sym if count > 1 data = schema.generate_many(count, seed: seed, mode: mode, registry: @registry, overrides: overrides) else data = schema.generate(seed: seed, mode: mode, registry: @registry, overrides: overrides) end apply_behaviors(schema, res) res["Content-Type"] = "application/json" res.body = JSON.pretty_generate(data) end |
#handle_list_schemas(_req, res) ⇒ Object (private)
181 182 183 184 185 186 187 188 |
# File 'lib/synthra/mock_server.rb', line 181 def handle_list_schemas(_req, res) res["Content-Type"] = "application/json" res.body = JSON.pretty_generate({ schemas: @registry.names.sort, count: @registry.names.count, endpoints: @registry.names.map { |n| "/api/#{to_snake_case(n)}" } }) end |
#handle_recording(req, res, name) ⇒ Object (private)
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 |
# File 'lib/synthra/mock_server.rb', line 341 def handle_recording(req, res, name) @mutex.synchronize do if req.request_method == "POST" # Save recording body = JSON.parse(req.body || "{}") rescue {} @recordings[name] = { data: body["data"], recorded_at: Time.now.iso8601, content_type: body["content_type"] || "application/json" } save_recordings res["Content-Type"] = "application/json" res.body = JSON.generate({ saved: name }) elsif @recordings[name] recording = @recordings[name] res["Content-Type"] = recording["content_type"] || "application/json" res.body = recording["data"].is_a?(String) ? recording["data"] : JSON.generate(recording["data"]) else res.status = 404 res["Content-Type"] = "application/json" res.body = JSON.generate({ error: "Recording not found", name: name }) end end end |
#handle_schema_info(_req, res, schema_name) ⇒ Object (private)
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
# File 'lib/synthra/mock_server.rb', line 312 def handle_schema_info(_req, res, schema_name) schema_name = normalize_schema_name(schema_name) unless @registry.schema?(schema_name) res.status = 404 res["Content-Type"] = "application/json" res.body = JSON.generate({ error: "Schema not found" }) return end schema = @registry.schema(schema_name) res["Content-Type"] = "application/json" res.body = JSON.pretty_generate({ name: schema.name, fields: schema.fields.map do |f| { name: f.name, type: f.type_name, optional: f.optional?, nullable: f.nullable?, args: f.type_args } end, behaviors: schema.behaviors, version: schema.respond_to?(:version) ? schema.version : nil }) end |
#handle_stream_generate(req, res, schema_name) ⇒ Object (private)
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
# File 'lib/synthra/mock_server.rb', line 287 def handle_stream_generate(req, res, schema_name) schema_name = normalize_schema_name(schema_name) unless @registry.schema?(schema_name) res.status = 404 res["Content-Type"] = "application/json" res.body = JSON.generate({ error: "Schema not found" }) return end schema = @registry.schema(schema_name) params = parse_query_params(req) count = [params[:count] || 100, 100000].min res["Content-Type"] = "application/x-ndjson" res["Transfer-Encoding"] = "chunked" # Stream NDJSON output = +"" schema.generate_stream(count: count, mode: params[:mode] || @options[:default_mode]).each do |record| output << JSON.generate(record) << "\n" end res.body = output end |
#load_recordings ⇒ Object (private)
429 430 431 432 433 434 435 436 437 438 439 |
# File 'lib/synthra/mock_server.rb', line 429 def load_recordings dir = @options[:recordings_dir] return unless Dir.exist?(dir) @mutex.synchronize do Dir.glob(File.join(dir, "*.json")).each do |file| name = File.basename(file, ".json") @recordings[name] = JSON.parse(File.read(file)) end end end |
#normalize_schema_name(name) ⇒ Object (private)
376 377 378 379 |
# File 'lib/synthra/mock_server.rb', line 376 def normalize_schema_name(name) # Convert snake_case to PascalCase name.split("_").map(&:capitalize).join end |
#parse_query_params(req) ⇒ Object (private)
367 368 369 370 371 372 373 374 |
# File 'lib/synthra/mock_server.rb', line 367 def parse_query_params(req) query = req.query || {} { seed: query["seed"]&.to_i, mode: query["mode"]&.to_sym, count: query["count"]&.to_i } end |
#rate_limited?(req) ⇒ Boolean (private)
405 406 407 408 409 410 411 412 413 414 415 416 417 |
# File 'lib/synthra/mock_server.rb', line 405 def rate_limited?(req) client_ip = req.peeraddr[2] @mutex.synchronize do # Reset counts every minute if Time.now - @last_reset > 60 @request_counts.clear @last_reset = Time.now end @request_counts[client_ip] += 1 @request_counts[client_ip] > @options[:rate_limit] end end |
#record_response(schema_name, data) ⇒ Object (private)
419 420 421 422 423 424 425 426 427 |
# File 'lib/synthra/mock_server.rb', line 419 def record_response(schema_name, data) @mutex.synchronize do @recordings["#{schema_name}_#{Time.now.to_i}"] = { data: data, recorded_at: Time.now.iso8601, schema: schema_name } end end |
#route_request(req, res) ⇒ Object (private)
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/synthra/mock_server.rb', line 153 def route_request(req, res) path = req.path method = req.request_method case path when "/api/schemas" handle_list_schemas(req, res) when %r{^/api/recordings/(.+)$} handle_recording(req, res, $1) when %r{^/api/([^/]+)/batch$} handle_batch_generate(req, res, $1) when %r{^/api/([^/]+)/stream$} handle_stream_generate(req, res, $1) when %r{^/api/([^/]+)/schema$} handle_schema_info(req, res, $1) when %r{^/api/([^/]+)$} if method == "POST" handle_generate_with_overrides(req, res, $1) else handle_generate(req, res, $1) end else res.status = 404 res["Content-Type"] = "application/json" res.body = JSON.generate({ error: "Not found", path: path }) end end |
#save_recordings ⇒ Object (private)
441 442 443 444 445 446 447 448 449 450 |
# File 'lib/synthra/mock_server.rb', line 441 def save_recordings dir = @options[:recordings_dir] FileUtils.mkdir_p(dir) @mutex.synchronize do @recordings.each do |name, data| File.write(File.join(dir, "#{name}.json"), JSON.pretty_generate(data)) end end end |
#setup_routes ⇒ Object (private)
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
# File 'lib/synthra/mock_server.rb', line 131 def setup_routes # CORS preflight @server.mount_proc "/" do |req, res| add_cors_headers(res) if @options[:cors] if req.request_method == "OPTIONS" res.status = 204 next end # Rate limiting if @options[:rate_limit] > 0 && rate_limited?(req) res.status = 429 res["Content-Type"] = "application/json" res.body = JSON.generate({ error: "Rate limit exceeded" }) next end route_request(req, res) end end |
#start ⇒ Object
Start the mock server
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/synthra/mock_server.rb', line 62 def start # :nocov: binds a real TCP port and blocks on WEBrick#start — exercised via integration use. puts puts "" puts "📊 Available schemas: #{@registry.names.sort.join(', ')}" puts "" puts "🔗 Endpoints:" puts " GET /api/schemas - List all schemas" puts " GET /api/:schema - Generate single record" puts " GET /api/:schema/batch - Generate multiple records" puts " GET /api/:schema/stream - Stream records (NDJSON)" puts " POST /api/:schema - Generate with overrides" puts " GET /api/:schema/schema - Get schema definition" puts "" if @options[:recording] puts "📼 Recording mode: ENABLED" puts " POST /api/recordings/:name - Save recording" puts " GET /api/recordings/:name - Replay recording" puts "" end puts "Press Ctrl+C to stop" puts "" @server = WEBrick::HTTPServer.new( Port: @options[:port], Logger: WEBrick::Log.new($stderr, WEBrick::Log::INFO), AccessLog: [[File.open("/dev/null", "w"), WEBrick::AccessLog::COMBINED_LOG_FORMAT]] ) setup_routes trap("INT") { @server.shutdown } @server.start # :nocov: end |
#start_async ⇒ Object
Start server in background thread
99 100 101 102 103 |
# File 'lib/synthra/mock_server.rb', line 99 def start_async # :nocov: spawns a thread that binds a port — integration-only. Thread.new { start } # :nocov: end |
#stop ⇒ Object
Stop the server
106 107 108 |
# File 'lib/synthra/mock_server.rb', line 106 def stop @server&.shutdown end |
#to_snake_case(str) ⇒ Object (private)
452 453 454 455 456 |
# File 'lib/synthra/mock_server.rb', line 452 def to_snake_case(str) str.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase end |