Class: Synthra::APIServer

Inherits:
Object
  • Object
show all
Defined in:
lib/synthra/api_server.rb

Overview

Production API Server

A production-ready API server for data generation. Designed to be the core of your data generation platform.

Examples:

Start standalone server

Synthra::APIServer.start(
  schema_dir: "schemas/",
  port: 3000,
  environment: :production
)

Use as Rack middleware

# config.ru
require 'synthra'
run Synthra::APIServer.rack_app(schema_dir: "schemas/")

With authentication

Synthra::APIServer.start(
  schema_dir: "schemas/",
  auth: { type: :api_key, keys: ["secret-key-123"] }
)

Defined Under Namespace

Classes: Cache, Metrics, RackRequest, RackResponse, RateLimiter, WEBrickRequest, WEBrickResponse

Constant Summary collapse

VERSION =
"1.0.0"
DEFAULT_CONFIG =

Server configuration defaults

{
  port: 3000,
  host: "0.0.0.0",
  environment: :development,
  cors: true,
  rate_limit: 0,
  max_batch_size: 10_000,
  max_stream_size: 1_000_000,
  auth: nil,
  log_level: :info,
  request_timeout: 30,
  enable_metrics: true,
  enable_caching: false,
  cache_ttl: 60
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema_dir:, **config) ⇒ APIServer

Create a new API server

Parameters:

  • schema_dir (String)

    directory containing DSL schemas

  • config (Hash)

    server configuration



59
60
61
62
63
64
65
66
# File 'lib/synthra/api_server.rb', line 59

def initialize(schema_dir:, **config)
  @config = DEFAULT_CONFIG.merge(config)
  @registry = Registry.new
  @registry.load_dir(schema_dir)
  @metrics = Metrics.new if @config[:enable_metrics]
  @cache = Cache.new(@config[:cache_ttl]) if @config[:enable_caching]
  @rate_limiter = RateLimiter.new(@config[:rate_limit]) if @config[:rate_limit] > 0
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



35
36
37
# File 'lib/synthra/api_server.rb', line 35

def config
  @config
end

#registryObject (readonly)

Returns the value of attribute registry.



35
36
37
# File 'lib/synthra/api_server.rb', line 35

def registry
  @registry
end

Class Method Details

.rack_app(schema_dir:, **config) ⇒ Object

Rack application for use with Puma, etc.



101
102
103
104
105
106
107
# File 'lib/synthra/api_server.rb', line 101

def self.rack_app(schema_dir:, **config)
  server = new(schema_dir: schema_dir, **config)
  
  lambda do |env|
    server.handle_rack_request(env)
  end
end

.start(**options) ⇒ Object



120
121
122
# File 'lib/synthra/api_server.rb', line 120

def start(**options)
  new(**options).start
end

Instance Method Details

#add_cors_headers(response) ⇒ Object (private)



450
451
452
453
454
455
# File 'lib/synthra/api_server.rb', line 450

def add_cors_headers(response)
  response.headers["Access-Control-Allow-Origin"] = "*"
  response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
  response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-API-Key"
  response.headers["Access-Control-Max-Age"] = "86400"
end

#authenticate(request) ⇒ Object (private)



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/synthra/api_server.rb', line 419

def authenticate(request)
  return true unless @config[:auth]

  case @config[:auth][:type]
  when :api_key
    # SECURITY: header only (never the query string — keys in URLs leak into access logs,
    # browser history and Referer headers) and a constant-time compare (Array#include? leaks
    # the key length/prefix via a timing oracle).
    secure_match?(request.headers["X-API-Key"], @config[:auth][:keys])
  when :bearer
    auth = request.headers["Authorization"]
    return false unless auth&.start_with?("Bearer ")

    secure_match?(auth[7..], @config[:auth][:tokens])
  else
    true
  end
end

#create_loggerObject (private)



168
169
170
171
172
173
# File 'lib/synthra/api_server.rb', line 168

def create_logger
  WEBrick::Log.new(
    $stderr,
    @config[:log_level] == :debug ? WEBrick::Log::DEBUG : WEBrick::Log::INFO
  )
end

#find_schema(slug) ⇒ Object (private)



398
399
400
401
402
403
404
405
406
407
408
# File 'lib/synthra/api_server.rb', line 398

def find_schema(slug)
  # Try exact match first
  return @registry.schema(slug) if @registry.schema?(slug)
  
  # Try PascalCase
  pascal = slug.split("_").map(&:capitalize).join
  return @registry.schema(pascal) if @registry.schema?(pascal)
  
  # Try case-insensitive match
  @registry.names.find { |n| n.downcase == slug.downcase }&.then { |n| @registry.schema(n) }
end

#handle_batch(request, response, schema_slug) ⇒ Object (private)



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/synthra/api_server.rb', line 323

def handle_batch(request, response, schema_slug)
  schema = find_schema(schema_slug)
  return schema_not_found(response, schema_slug) unless schema
  
  params = request.query_params
  count = [[params[:count]&.to_i || 10, 1].max, @config[:max_batch_size]].min
  
  data = schema.generate_many(
    count,
    seed: params[:seed]&.to_i,
    mode: (params[:mode] || :random).to_sym,
    registry: @registry
  )
  
  response.json({
    data: data,
    meta: {
      count: data.length,
      schema: schema.name,
      seed: params[:seed]&.to_i,
      mode: params[:mode] || "random"
    }
  })
end

#handle_error(error, response) ⇒ Object (private)



457
458
459
460
461
462
463
464
# File 'lib/synthra/api_server.rb', line 457

def handle_error(error, response)
  response.status = 500
  response.json({
    error: error.class.name,
    message: error.message,
    backtrace: @config[:environment] == :development ? error.backtrace&.first(10) : nil
  })
end

#handle_generate(request, response, schema_slug) ⇒ Object (private)



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/synthra/api_server.rb', line 274

def handle_generate(request, response, schema_slug)
  schema = find_schema(schema_slug)
  return schema_not_found(response, schema_slug) unless schema
  
  params = request.query_params
  cache_key = "#{schema.name}:#{params[:seed]}:#{params[:mode]}"
  
  if @cache && (cached = @cache.get(cache_key))
    response.json(cached)
    return
  end
  
  data = schema.generate(
    seed: params[:seed]&.to_i,
    mode: (params[:mode] || @config[:default_mode] || :random).to_sym,
    registry: @registry
  )
  
  @cache&.set(cache_key, data)
  response.json(data)
end

#handle_generate_post(request, response, schema_slug) ⇒ Object (private)



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/synthra/api_server.rb', line 296

def handle_generate_post(request, response, schema_slug)
  schema = find_schema(schema_slug)
  return schema_not_found(response, schema_slug) unless schema
  
  body = request.json_body || {}
  count = [body["count"] || 1, @config[:max_batch_size]].min
  
  if count > 1
    data = schema.generate_many(
      count,
      seed: body["seed"]&.to_i,
      mode: (body["mode"] || :random).to_sym,
      overrides: body["overrides"] || {},
      registry: @registry
    )
  else
    data = schema.generate(
      seed: body["seed"]&.to_i,
      mode: (body["mode"] || :random).to_sym,
      overrides: body["overrides"] || {},
      registry: @registry
    )
  end
  
  response.json(data)
end

#handle_health(response) ⇒ Object (private)



252
253
254
255
256
257
258
259
# File 'lib/synthra/api_server.rb', line 252

def handle_health(response)
  response.json({
    status: "healthy",
    version: VERSION,
    schemas: @registry.names.count,
    uptime: uptime
  })
end

#handle_list_schemas(response) ⇒ Object (private)



261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/synthra/api_server.rb', line 261

def handle_list_schemas(response)
  response.json({
    schemas: @registry.names.sort.map do |name|
      schema = @registry.schema(name)
      {
        name: name,
        fields: schema.fields.count,
        endpoint: "/api/#{to_snake_case(name)}"
      }
    end
  })
end

#handle_metrics(response) ⇒ Object (private)



390
391
392
393
394
395
396
# File 'lib/synthra/api_server.rb', line 390

def handle_metrics(response)
  if @metrics
    response.json(@metrics.to_h)
  else
    response.json({ enabled: false })
  end
end

#handle_openapi(request, response, schema_slug) ⇒ Object (private)



364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/synthra/api_server.rb', line 364

def handle_openapi(request, response, schema_slug)
  schema = find_schema(schema_slug)
  return schema_not_found(response, schema_slug) unless schema
  
  # Create a mini registry with just this schema
  mini_registry = Registry.new
  mini_registry.register_schema(schema.name, schema)
  
  exporter = Export::OpenAPI.new(mini_registry)
  spec = exporter.export_as(request.query_params[:format]&.to_sym || :yaml)
  
  response.content_type = request.query_params[:format] == "json" ? "application/json" : "application/yaml"
  response.body = spec
end

#handle_protobuf(request, response, schema_slug) ⇒ Object (private)



379
380
381
382
383
384
385
386
387
388
# File 'lib/synthra/api_server.rb', line 379

def handle_protobuf(request, response, schema_slug)
  schema = find_schema(schema_slug)
  return schema_not_found(response, schema_slug) unless schema
  
  exporter = Export::Protobuf.new(schema, registry: @registry)
  proto = exporter.export
  
  response.content_type = "text/plain"
  response.body = proto
end

#handle_rack_request(env) ⇒ Object

Handle Rack request



110
111
112
113
114
115
116
117
# File 'lib/synthra/api_server.rb', line 110

def handle_rack_request(env)
  request = RackRequest.new(env)
  response = RackResponse.new
  
  handle_request_internal(request, response)
  
  [response.status, response.headers, [response.body]]
end

#handle_request(req, res) ⇒ Object (private)



175
176
177
178
179
180
181
# File 'lib/synthra/api_server.rb', line 175

def handle_request(req, res)
  # :nocov: WEBrick mount_proc glue — wraps live WEBrick request/response objects.
  request = WEBrickRequest.new(req)
  response = WEBrickResponse.new(res)
  handle_request_internal(request, response)
  # :nocov:
end

#handle_request_internal(request, response) ⇒ Object (private)



183
184
185
186
187
188
189
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
221
222
# File 'lib/synthra/api_server.rb', line 183

def handle_request_internal(request, response)
  start_time = Time.now
  
  # CORS
  add_cors_headers(response) if @config[:cors]
  
  if request.options?
    response.status = 204
    return
  end
  
  # Authentication
  if @config[:auth] && !authenticate(request)
    response.status = 401
    response.json({ error: "Unauthorized" })
    return
  end
  
  # Rate limiting
  if @rate_limiter && @rate_limiter.limited?(request.client_ip)
    response.status = 429
    response.json({ error: "Rate limit exceeded", retry_after: @rate_limiter.retry_after(request.client_ip) })
    return
  end
  
  # Route
  route(request, response)
  
  # Metrics
  if @metrics
    @metrics.record(
      path: request.path,
      method: request.method,
      status: response.status,
      duration: Time.now - start_time
    )
  end
rescue StandardError => e
  handle_error(e, response)
end

#handle_stream(request, response, schema_slug) ⇒ Object (private)



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/synthra/api_server.rb', line 348

def handle_stream(request, response, schema_slug)
  schema = find_schema(schema_slug)
  return schema_not_found(response, schema_slug) unless schema
  
  params = request.query_params
  count = [[params[:count]&.to_i || 100, 1].max, @config[:max_stream_size]].min
  
  response.content_type = "application/x-ndjson"
  
  output = +""
  schema.generate_stream(count: count, mode: (params[:mode] || :random).to_sym).each do |record|
    output << JSON.generate(record) << "\n"
  end
  response.body = output
end


127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/synthra/api_server.rb', line 127

def print_banner
  puts <<~BANNER
    
    ╔══════════════════════════════════════════════════════════════════╗
    ║                                                                  ║
    ║   🚀 Synthra API Server v#{VERSION}    ║                                                                  ║
    ║   Production-Ready Data Generation API                           ║
    ║                                                                  ║
    ╠══════════════════════════════════════════════════════════════════╣
    ║                                                                  ║
    ║   Server:      http://#{@config[:host]}:#{@config[:port]}#{" " * (29 - @config[:host].length - @config[:port].to_s.length)}    ║   Environment: #{@config[:environment].to_s.ljust(42)}    ║   Schemas:     #{@registry.names.count.to_s.ljust(42)}    ║                                                                  ║
    ╚══════════════════════════════════════════════════════════════════╝
    
    📊 Available Schemas:
    #{@registry.names.map { |n| "#{n}" }.join("\n")}
    
    🔗 API Endpoints:
       GET  /                          Health check
       GET  /api/schemas               List schemas
       GET  /api/:schema               Generate record
       GET  /api/:schema/batch         Generate batch
       GET  /api/:schema/stream        Stream records (NDJSON)
       POST /api/:schema               Generate with overrides
       GET  /api/:schema/openapi       OpenAPI spec for schema
       GET  /api/:schema/protobuf      Protobuf spec for schema
       GET  /metrics                   Server metrics
    
    Press Ctrl+C to stop
    
  BANNER
end

#route(request, response) ⇒ Object (private)



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/api_server.rb', line 224

def route(request, response)
  case request.path
  when "/"
    handle_health(response)
  when "/api/schemas"
    handle_list_schemas(response)
  when "/metrics"
    handle_metrics(response)
  when %r{^/api/([^/]+)/openapi$}
    handle_openapi(request, response, $1)
  when %r{^/api/([^/]+)/protobuf$}
    handle_protobuf(request, response, $1)
  when %r{^/api/([^/]+)/batch$}
    handle_batch(request, response, $1)
  when %r{^/api/([^/]+)/stream$}
    handle_stream(request, response, $1)
  when %r{^/api/([^/]+)$}
    if request.post?
      handle_generate_post(request, response, $1)
    else
      handle_generate(request, response, $1)
    end
  else
    response.status = 404
    response.json({ error: "Not found", path: request.path })
  end
end

#schema_not_found(response, slug) ⇒ Object (private)



410
411
412
413
414
415
416
417
# File 'lib/synthra/api_server.rb', line 410

def schema_not_found(response, slug)
  response.status = 404
  response.json({
    error: "Schema not found",
    requested: slug,
    available: @registry.names.map { |n| to_snake_case(n) }
  })
end

#secure_match?(provided, allowed) ⇒ Boolean (private)

Constant-time membership test against a list of secrets. fixed_length_secure_compare raises on length mismatch, so the bytesize guard short-circuits non-matches without leaking timing.

Returns:

  • (Boolean)


440
441
442
443
444
445
446
447
448
# File 'lib/synthra/api_server.rb', line 440

def secure_match?(provided, allowed)
  return false unless provided.is_a?(String) && allowed

  allowed.any? do |candidate|
    candidate.is_a?(String) &&
      candidate.bytesize == provided.bytesize &&
      OpenSSL.fixed_length_secure_compare(candidate, provided)
  end
end

#setup_signal_handlersObject (private)



163
164
165
166
# File 'lib/synthra/api_server.rb', line 163

def setup_signal_handlers
  trap("INT") { stop }
  trap("TERM") { stop }
end

#startObject

Start the server



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/synthra/api_server.rb', line 69

def start
  # :nocov: binds a real TCP port and blocks on WEBrick#start — exercised via integration use.
  print_banner
  setup_signal_handlers

  @server = WEBrick::HTTPServer.new(
    Port: @config[:port],
    BindAddress: @config[:host],
    Logger: create_logger,
    AccessLog: []
  )

  @server.mount_proc("/", &method(:handle_request))
  @server.start
  # :nocov:
end

#start_asyncObject

Start in background



87
88
89
90
91
92
93
# File 'lib/synthra/api_server.rb', line 87

def start_async
  # :nocov: spawns a thread that binds a port and sleeps — integration-only.
  @thread = Thread.new { start }
  sleep 0.5 # Wait for server to start
  @thread
  # :nocov:
end

#stopObject

Stop the server



96
97
98
# File 'lib/synthra/api_server.rb', line 96

def stop
  @server&.shutdown
end

#to_snake_case(str) ⇒ Object (private)



471
472
473
474
475
# File 'lib/synthra/api_server.rb', line 471

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

#uptimeObject (private)



466
467
468
469
# File 'lib/synthra/api_server.rb', line 466

def uptime
  @start_time ||= Time.now
  (Time.now - @start_time).round
end