Class: Synthra::Export::Protobuf

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

Overview

Protocol Buffers / gRPC Export

Generates .proto files from Synthra schemas for use with gRPC services.

Examples:

Generate proto file

exporter = Synthra::Export::Protobuf.new(schema, registry: registry)
proto = exporter.export

CLI usage

$ synthra export User -d schemas -f protobuf -o user.proto

Constant Summary collapse

TYPE_MAP =

Type mapping from Synthra to Protocol Buffers

{
  # Strings
  "text" => "string",
  "name" => "string",
  "full_name" => "string",
  "first_name" => "string",
  "last_name" => "string",
  "email" => "string",
  "url" => "string",
  "phone" => "string",
  "address" => "string",
  "city" => "string",
  "state" => "string",
  "country" => "string",
  "country_code" => "string",
  "postal_code" => "string",
  "street" => "string",
  "company" => "string",
  "job_title" => "string",
  "username" => "string",
  "password" => "string",
  "slug" => "string",
  "sentence" => "string",
  "paragraph" => "string",
  "domain" => "string",
  "ip" => "string",
  "ipv6" => "string",
  "mac_address" => "string",
  "user_agent" => "string",
  "color" => "string",
  "hex_color" => "string",
  "file_name" => "string",
  "file_path" => "string",
  "mime_type" => "string",
  "credit_card" => "string",
  "iban" => "string",
  "bic" => "string",
  "ssn" => "string",
  "ein" => "string",
  "license_plate" => "string",
  "vin" => "string",

  # IDs
  "uuid" => "string",
  "ulid" => "string",
  "nanoid" => "string",

  # Numbers (integers)
  "number" => "int64",
  "integer" => "int64",
  "int" => "int32",
  "int32" => "int32",
  "int64" => "int64",
  "age" => "int32",
  "airport_elevation" => "int64",
  "discount" => "int64",
  "formula" => "int64",
  "row_number" => "int64",
  "sequence" => "int64",
  "id_sequence" => "int64",

  # Numbers (floats)
  "float" => "double",
  "double" => "double",
  "money" => "double",
  "decimal" => "string", # Decimal as string for precision
  "percentage" => "double",
  "latitude" => "double",
  "longitude" => "double",
  "airport_latitude" => "double",
  "airport_longitude" => "double",
  "product_price" => "double",
  "tax_rate" => "double",
  "transaction_amount" => "double",

  # Boolean
  "boolean" => "bool",
  "bool" => "bool",

  # Timestamps
  "timestamp" => "google.protobuf.Timestamp",
  "date" => "string", # ISO date string
  "date_between" => "string",
  "time" => "string", # ISO time string
  "datetime" => "google.protobuf.Timestamp",
  "now" => "string", # Date value rendered as ISO date string
  "past_date" => "string",
  "future_date" => "string",
  "mobile_device_release_date" => "string",

  # Binary
  "binary" => "bytes",
  "base64" => "bytes",

  # Complex
  "object" => "google.protobuf.Struct",
  "json" => "string",
  "array" => "repeated"
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema, registry: nil, **options) ⇒ Protobuf

Create a new Protobuf exporter

Parameters:

  • schema (Schema)

    the schema to export

  • registry (Registry) (defaults to: nil)

    registry for resolving references

  • options (Hash)

    export options

Options Hash (**options):

  • :package (String)

    package name (default: "generated")

  • :go_package (String)

    Go package path

  • :with_service (Boolean)

    generate gRPC service definition

  • :syntax (String)

    proto syntax version (default: "proto3")



130
131
132
133
134
135
136
137
138
# File 'lib/synthra/export/protobuf.rb', line 130

def initialize(schema, registry: nil, **options)
  @schema = schema
  @registry = registry
  @options = {
    package: "generated",
    syntax: "proto3",
    with_service: true
  }.merge(options)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



118
119
120
# File 'lib/synthra/export/protobuf.rb', line 118

def options
  @options
end

#registryObject (readonly)

Returns the value of attribute registry.



118
119
120
# File 'lib/synthra/export/protobuf.rb', line 118

def registry
  @registry
end

#schemaObject (readonly)

Returns the value of attribute schema.



118
119
120
# File 'lib/synthra/export/protobuf.rb', line 118

def schema
  @schema
end

Class Method Details

.export_all(registry, **options) ⇒ String

Export all schemas from registry

Parameters:

  • registry (Registry)

    schema registry

  • options (Hash)

    export options

Returns:

  • (String)

    combined .proto file



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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
251
252
# File 'lib/synthra/export/protobuf.rb', line 202

def self.export_all(registry, **options)
  lines = []
  package = options[:package] || "generated"
  
  lines << "syntax = \"proto3\";"
  lines << ""
  lines << "package #{package};"
  lines << ""
  
  if options[:go_package]
    lines << "option go_package = \"#{options[:go_package]}\";"
    lines << ""
  end
  
  # Collect all imports
  lines << "import \"google/protobuf/timestamp.proto\";"
  lines << "import \"google/protobuf/struct.proto\";"
  lines << ""
  
  # All enums first
  all_enums = []
  registry.names.each do |name|
    schema = registry.schema(name)
    schema.fields.each do |field|
      if field.type_name == "enum" && field.type_args[:values]
        enum_name = "#{schema.name}#{field.name.capitalize}"
        all_enums << { name: enum_name, values: field.type_args[:values] }
      end
    end
  end
  
  all_enums.uniq { |e| e[:name] }.each do |enum|
    lines << generate_enum_static(enum)
    lines << ""
  end
  
  # All messages
  registry.names.sort.each do |name|
    schema = registry.schema(name)
    exporter = new(schema, registry: registry, **options.merge(with_service: false))
    lines << exporter.generate_message(schema)
    lines << ""
  end
  
  # Combined service
  if options[:with_service] != false
    lines << generate_combined_service(registry, package)
  end
  
  lines.join("\n")
end

.generate_combined_service(registry, package) ⇒ Object



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/synthra/export/protobuf.rb', line 442

def self.generate_combined_service(registry, package)
  lines = []
  lines << "// Combined Data Generation Service"
  lines << "service DataGenerationService {"
  
  registry.names.sort.each do |name|
    snake_name = name.gsub(/([A-Z])/, '_\1').downcase.sub(/^_/, '')
    lines << "  // Generate #{name}"
    lines << "  rpc Generate#{name}(Generate#{name}Request) returns (#{name});"
    lines << "  rpc GenerateMany#{name}s(GenerateManyRequest) returns (stream #{name});"
  end
  
  lines << "}"
  lines << ""
  
  # Common request messages
  lines << "message GenerateManyRequest {"
  lines << "  int32 count = 1;"
  lines << "  optional int64 seed = 2;"
  lines << "  optional string mode = 3;"
  lines << "}"
  
  registry.names.sort.each do |name|
    lines << ""
    lines << "message Generate#{name}Request {"
    lines << "  optional int64 seed = 1;"
    lines << "  optional string mode = 2;"
    lines << "  map<string, string> overrides = 3;"
    lines << "}"
  end
  
  lines.join("\n")
end

.generate_enum_static(enum) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/synthra/export/protobuf.rb', line 313

def self.generate_enum_static(enum)
  lines = []
  lines << "enum #{enum[:name]} {"
  lines << "  #{enum[:name].upcase}_UNSPECIFIED = 0;"
  
  enum[:values].each_with_index do |value, index|
    value_str = value.respond_to?(:value) ? value.value : value.to_s
    enum_value = "#{enum[:name].upcase}_#{value_str.upcase.gsub(/[^A-Z0-9]/, '_')}"
    lines << "  #{enum_value} = #{index + 1};"
  end
  
  lines << "}"
  lines.join("\n")
end

Instance Method Details

#collect_importsObject (private)



272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/synthra/export/protobuf.rb', line 272

def collect_imports
  imports = Set.new
  
  @schema.fields.each do |field|
    type = field.type_name
    if %w[timestamp datetime now].include?(type)
      imports.add("google/protobuf/timestamp.proto")
    elsif type == "object"
      imports.add("google/protobuf/struct.proto")
    end
  end
  
  imports.to_a.sort
end

#collect_referenced_schemasObject (private)



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/synthra/export/protobuf.rb', line 369

def collect_referenced_schemas
  return [] unless @registry
  
  referenced = Set.new
  
  @schema.fields.each do |field|
    type_name = field.type_name
    
    if @registry.schema?(type_name)
      referenced.add(@registry.schema(type_name))
    end
    
    if type_name == "array"
      element = field.type_args[:element]
      if element && @registry.schema?(element.to_s)
        referenced.add(@registry.schema(element.to_s))
      end
    end
  end
  
  referenced.to_a
end

#exportString

Export schema to Protocol Buffers format

Returns:

  • (String)

    .proto file content



144
145
146
147
148
149
150
151
152
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/synthra/export/protobuf.rb', line 144

def export
  lines = []
  
  # Syntax declaration
  lines << "syntax = \"#{@options[:syntax]}\";"
  lines << ""
  
  # Package
  lines << "package #{@options[:package]};"
  lines << ""
  
  # Options
  if @options[:go_package]
    lines << "option go_package = \"#{@options[:go_package]}\";"
    lines << ""
  end
  
  # Imports
  imports = collect_imports
  if imports.any?
    imports.each { |imp| lines << "import \"#{imp}\";" }
    lines << ""
  end
  
  # Enums (extracted from enum fields)
  enums = extract_enums
  enums.each do |enum|
    lines << generate_enum(enum)
    lines << ""
  end
  
  # Message definition
  lines << generate_message(@schema)
  
  # Generate referenced schemas
  if @registry
    referenced = collect_referenced_schemas
    referenced.each do |ref_schema|
      lines << ""
      lines << generate_message(ref_schema)
    end
  end
  
  # gRPC Service definition
  if @options[:with_service]
    lines << ""
    lines << generate_service
  end
  
  lines.join("\n")
end

#extract_enumsObject (private)



287
288
289
290
291
292
293
294
295
296
# File 'lib/synthra/export/protobuf.rb', line 287

def extract_enums
  enums = []
  @schema.fields.each do |field|
    if field.type_name == "enum" && field.type_args[:values]
      enum_name = "#{@schema.name}#{field.name.capitalize}"
      enums << { name: enum_name, values: field.type_args[:values], field: field.name }
    end
  end
  enums
end

#field_to_proto(field) ⇒ Object (private)



328
329
330
331
332
333
334
335
336
337
338
339
340
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
366
367
# File 'lib/synthra/export/protobuf.rb', line 328

def field_to_proto(field)
  type_name = field.type_name
  
  # Handle arrays
  if type_name == "array"
    element_type = field.type_args[:element]
    if element_type && @registry&.schema?(element_type.to_s)
      return ["repeated #{element_type}", {}]
    else
      inner_type = TYPE_MAP[element_type.to_s] || "string"
      return ["repeated #{inner_type}", {}]
    end
  end
  
  # Handle enums
  if type_name == "enum"
    enum_name = "#{@schema.name}#{field.name.capitalize}"
    return [enum_name, {}]
  end
  
  # Handle schema references
  if @registry&.schema?(type_name)
    return [type_name, {}]
  end
  
  # Handle const
  if type_name == "const"
    value = field.type_args[:value]
    case value
    when Integer then return ["int64", {}]
    when Float then return ["double", {}]
    when TrueClass, FalseClass then return ["bool", {}]
    else return ["string", {}]
    end
  end
  
  # Standard type mapping
  proto_type = TYPE_MAP[type_name] || "string"
  [proto_type, {}]
end

#generate_enum(enum) ⇒ Object (private)



298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/synthra/export/protobuf.rb', line 298

def generate_enum(enum)
  lines = []
  lines << "enum #{enum[:name]} {"
  lines << "  #{enum[:name].upcase}_UNSPECIFIED = 0;"
  
  enum[:values].each_with_index do |value, index|
    value_str = value.respond_to?(:value) ? value.value : value.to_s
    enum_value = "#{enum[:name].upcase}_#{value_str.upcase.gsub(/[^A-Z0-9]/, '_')}"
    lines << "  #{enum_value} = #{index + 1};"
  end
  
  lines << "}"
  lines.join("\n")
end

#generate_message(schema) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/synthra/export/protobuf.rb', line 254

def generate_message(schema)
  lines = []
  lines << "message #{schema.name} {"
  
  schema.fields.each_with_index do |field, index|
    field_num = index + 1
    proto_type, field_options = field_to_proto(field)
    
    optional = field.optional? ? "optional " : ""
    lines << "  #{optional}#{proto_type} #{to_snake_case(field.name)} = #{field_num};"
  end
  
  lines << "}"
  lines.join("\n")
end

#generate_serviceObject (private)



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/synthra/export/protobuf.rb', line 392

def generate_service
  name = @schema.name
  snake_name = to_snake_case(name)
  
  <<~SERVICE
    // gRPC Service for #{name}
    service #{name}Service {
      // Get a single #{name} by ID
      rpc Get#{name}(Get#{name}Request) returns (#{name});
      
      // List multiple #{name} records
      rpc List#{name}s(List#{name}sRequest) returns (List#{name}sResponse);
      
      // Generate fake #{name} data
      rpc Generate#{name}(Generate#{name}Request) returns (#{name});
      
      // Generate multiple fake #{name} records
      rpc GenerateMany#{name}s(GenerateMany#{name}sRequest) returns (stream #{name});
    }

    message Get#{name}Request {
      string id = 1;
    }

    message List#{name}sRequest {
      int32 page = 1;
      int32 page_size = 2;
    }

    message List#{name}sResponse {
      repeated #{name} #{snake_name}s = 1;
      int32 total_count = 2;
      int32 page = 3;
      int32 page_size = 4;
    }

    message Generate#{name}Request {
      optional int64 seed = 1;
      optional string mode = 2; // random, edge, invalid, hostile
      map<string, string> overrides = 3;
    }

    message GenerateMany#{name}sRequest {
      int32 count = 1;
      optional int64 seed = 2;
      optional string mode = 3;
    }
  SERVICE
end

#to_snake_case(str) ⇒ Object (private)



476
477
478
479
480
# File 'lib/synthra/export/protobuf.rb', line 476

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