Class: ManageIQ::API::Common::OpenApi::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/manageiq/api/common/open_api/generator.rb

Constant Summary collapse

PARAMETERS_PATH =
"/components/parameters".freeze
SCHEMAS_PATH =
"/components/schemas".freeze

Instance Method Summary collapse

Constructor Details

#initializeGenerator

Returns a new instance of Generator.



46
47
48
49
50
51
# File 'lib/manageiq/api/common/open_api/generator.rb', line 46

def initialize
  app_prefix, app_name = base_path.match(/\A(.*)\/(.*)\/v\d+.\d+\z/).captures
  ENV['APP_NAME'] = app_name
  ENV['PATH_PREFIX'] = app_prefix
  Rails.application.reload_routes!
end

Instance Method Details

#api_versionObject

Let’s get the latest api version based on the openapi.json routes



17
18
19
20
21
22
23
24
# File 'lib/manageiq/api/common/open_api/generator.rb', line 17

def api_version
  @api_version ||= Rails.application.routes.routes.each_with_object([]) do |route, array|
    matches = ActionDispatch::Routing::RouteWrapper
              .new(route)
              .path.match(/\A.*\/v(\d+.\d+)\/openapi.json.*\z/)
    array << matches[1] if matches
  end.max
end

#applicable_rails_routesObject



57
58
59
# File 'lib/manageiq/api/common/open_api/generator.rb', line 57

def applicable_rails_routes
  rails_routes.select { |i| i.path.start_with?(base_path) }
end

#base_pathObject



53
54
55
# File 'lib/manageiq/api/common/open_api/generator.rb', line 53

def base_path
  openapi_contents["servers"].first["variables"]["basePath"]["default"]
end

#build_collection_schema(klass_name) ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/manageiq/api/common/open_api/generator.rb', line 225

def build_collection_schema(klass_name)
  collection_name = "#{klass_name.pluralize}Collection"
  schemas[collection_name] = {
    "type"       => "object",
    "properties" => {
      "meta"  => { "$ref" => "##{SCHEMAS_PATH}/CollectionMetadata" },
      "links" => { "$ref" => "##{SCHEMAS_PATH}/CollectionLinks"    },
      "data"  => {
        "type"  => "array",
        "items" => { "$ref" => build_schema(klass_name) }
      }
    }
  }

  "##{SCHEMAS_PATH}/#{collection_name}"
end

#build_parameter(name, value = nil) ⇒ Object



175
176
177
178
# File 'lib/manageiq/api/common/open_api/generator.rb', line 175

def build_parameter(name, value = nil)
  parameters[name] = value
  "##{PARAMETERS_PATH}/#{name}"
end

#build_pathsObject



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'lib/manageiq/api/common/open_api/generator.rb', line 455

def build_paths
  applicable_rails_routes.each_with_object({}) do |route, expected_paths|
    without_format = route.path.split("(.:format)").first
    sub_path = without_format.split(base_path).last.sub(/:[_a-z]*id/, "{id}")
    klass_name = route.controller.split("/").last.camelize.singularize
    verb = route.verb.downcase
    primary_collection = sub_path.split("/")[1].camelize.singularize

    expected_paths[sub_path] ||= {}
    expected_paths[sub_path][verb] =
      case route.action
      when "index"   then openapi_list_description(klass_name, primary_collection)
      when "show"    then openapi_show_description(klass_name)
      when "destroy" then openapi_destroy_description(klass_name)
      when "create"  then openapi_create_description(klass_name)
      when "update"  then openapi_update_description(klass_name, verb)
      else handle_custom_route_action(route.action.camelize, verb, primary_collection)
      end

    next if expected_paths[sub_path][verb]

    # If it's not generic action but a custom method like e.g. `post "order", :to => "service_plans#order"`, we will
    # try to take existing schema, because the description, summary, etc. are likely to be custom.
    expected_paths[sub_path][verb] =
      case verb
      when "post"
        if sub_path == "/graphql" && route.action == "query"
          schemas["GraphQLRequest"]  = ::ManageIQ::API::Common::GraphQL.openapi_graphql_request
          schemas["GraphQLResponse"] = ::ManageIQ::API::Common::GraphQL.openapi_graphql_response
          ::ManageIQ::API::Common::GraphQL.openapi_graphql_description
        else
          openapi_contents.dig("paths", sub_path, verb) || openapi_create_description(klass_name)
        end
      when "get"
        openapi_contents.dig("paths", sub_path, verb) || openapi_show_description(klass_name)
      else
        openapi_contents.dig("paths", sub_path, verb)
      end
  end
end

#build_schema(klass_name) ⇒ Object



103
104
105
106
# File 'lib/manageiq/api/common/open_api/generator.rb', line 103

def build_schema(klass_name)
  schemas[klass_name] = openapi_schema(klass_name)
  "##{SCHEMAS_PATH}/#{klass_name}"
end

#build_schema_error_not_foundObject



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/manageiq/api/common/open_api/generator.rb', line 108

def build_schema_error_not_found
  klass_name = "ErrorNotFound"

  schemas[klass_name] = {
    "type"       => "object",
    "properties" => {
      "errors"  => {
        "type"  => "array",
        "items" => {
          "type"        => "object",
          "properties"  => {
            "status"    => {
              "type"    => "integer",
              "example" => 404
            },
            "detail"    => {
              "type"    => "string",
              "example" => "Record not found"
            }
          }
        }
      }
    }
  }

  "##{SCHEMAS_PATH}/#{klass_name}"
end

#generator_blacklist_allowed_attributesObject



434
435
436
# File 'lib/manageiq/api/common/open_api/generator.rb', line 434

def generator_blacklist_allowed_attributes
  @generator_blacklist_allowed_attributes ||= {}
end

#generator_blacklist_attributesObject



425
426
427
428
429
430
431
432
# File 'lib/manageiq/api/common/open_api/generator.rb', line 425

def generator_blacklist_attributes
  @generator_blacklist_attributes ||= [
    :resource_timestamp,
    :resource_timestamps,
    :resource_timestamps_max,
    :tenant_id,
  ].to_set.freeze
end

#generator_blacklist_substitute_attributesObject



438
439
440
# File 'lib/manageiq/api/common/open_api/generator.rb', line 438

def generator_blacklist_substitute_attributes
  @generator_blacklist_substitute_attributes ||= {}
end

#generator_read_only_attributesObject



442
443
444
445
446
447
448
449
# File 'lib/manageiq/api/common/open_api/generator.rb', line 442

def generator_read_only_attributes
  @generator_read_only_attributes ||= [
    :archived_at,
    :created_at,
    :last_seen_at,
    :updated_at,
  ].to_set.freeze
end

#generator_read_only_definitionsObject



451
452
453
# File 'lib/manageiq/api/common/open_api/generator.rb', line 451

def generator_read_only_definitions
  @generator_read_only_definitions ||= [].to_set.freeze
end

#handle_custom_route_action(_route_action, _verb, _primary_collection) ⇒ Object



496
497
# File 'lib/manageiq/api/common/open_api/generator.rb', line 496

def handle_custom_route_action(_route_action, _verb, _primary_collection)
end

#openapi_contentsObject



40
41
42
43
44
# File 'lib/manageiq/api/common/open_api/generator.rb', line 40

def openapi_contents
  @openapi_contents ||= begin
    JSON.parse(File.read(openapi_file))
  end
end

#openapi_create_description(klass_name) ⇒ Object



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/manageiq/api/common/open_api/generator.rb', line 289

def openapi_create_description(klass_name)
  {
    "summary"     => "Create a new #{klass_name}",
    "operationId" => "create#{klass_name}",
    "description" => "Creates a #{klass_name} object",
    "requestBody" => {
      "content"     => {
        "application/json" => {
          "schema" => { "$ref" => build_schema(klass_name) }
        }
      },
      "description" => "#{klass_name} attributes to create",
      "required"    => true
    },
    "responses"   => {
      "201" => {
        "description" => "#{klass_name} creation successful",
        "content"     => {
          "application/json" => {
            "schema" => { "$ref" => build_schema(klass_name) }
          }
        }
      }
    }
  }
end

#openapi_destroy_description(klass_name) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/manageiq/api/common/open_api/generator.rb', line 269

def openapi_destroy_description(klass_name)
  {
    "summary"     => "Delete an existing #{klass_name}",
    "operationId" => "delete#{klass_name}",
    "description" => "Deletes a #{klass_name} object",
    "parameters"  => [{ "$ref" => build_parameter("ID") }],
    "responses"   => {
      "204" => { "description" => "#{klass_name} deleted" },
      "404" => {
        "description" => "Not found",
        "content"     => {
          "application/json" => {
            "schema"         => { "$ref" => build_schema_error_not_found }
          }
        }
      }
    }
  }
end

#openapi_fileObject



36
37
38
# File 'lib/manageiq/api/common/open_api/generator.rb', line 36

def openapi_file
  @openapi_file ||= Rails.root.join("public", "doc", "openapi-3-v#{api_version}.0.json").to_s
end

#openapi_list_description(klass_name, primary_collection) ⇒ Object



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
223
# File 'lib/manageiq/api/common/open_api/generator.rb', line 188

def openapi_list_description(klass_name, primary_collection)
  sub_collection = (primary_collection != klass_name)
  {
    "summary"     => "List #{klass_name.pluralize}#{" for #{primary_collection}" if sub_collection}",
    "operationId" => "list#{primary_collection if sub_collection}#{klass_name.pluralize}",
    "description" => "Returns an array of #{klass_name} objects",
    "parameters"  => [
      { "$ref" => "##{PARAMETERS_PATH}/QueryLimit"  },
      { "$ref" => "##{PARAMETERS_PATH}/QueryOffset" },
      { "$ref" => "##{PARAMETERS_PATH}/QueryFilter" }
    ],
    "responses"   => {
      "200" => {
        "description" => "#{klass_name.pluralize} collection",
        "content"     => {
          "application/json" => {
            "schema" => { "$ref" => build_collection_schema(klass_name) }
          }
        }
      }
    }
  }.tap do |h|
    h["parameters"] << { "$ref" => build_parameter("ID") } if sub_collection

    next unless sub_collection

    h["responses"]["404"] = {
      "description" => "Not found",
      "content"     => {
        "application/json" => {
          "schema"         => { "$ref" => build_schema_error_not_found }
        }
      }
    }
  end
end

#openapi_schema(klass_name) ⇒ Object



180
181
182
183
184
185
186
# File 'lib/manageiq/api/common/open_api/generator.rb', line 180

def openapi_schema(klass_name)
  {
    "type"                 => "object",
    "properties"           => openapi_schema_properties(klass_name),
    "additionalProperties" => false
  }
end

#openapi_schema_properties(klass_name) ⇒ Object



410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/manageiq/api/common/open_api/generator.rb', line 410

def openapi_schema_properties(klass_name)
  model = klass_name.constantize
  model.columns_hash.map do |key, value|
    unless (generator_blacklist_allowed_attributes[key.to_sym] || []).include?(klass_name)
      next if generator_blacklist_attributes.include?(key.to_sym)
    end

    if generator_blacklist_substitute_attributes.include?(key.to_sym)
      generator_blacklist_substitute_attributes[key.to_sym]
    else
      [key, openapi_schema_properties_value(klass_name, model, key, value)]
    end
  end.compact.sort.to_h
end

#openapi_schema_properties_value(klass_name, model, key, value) ⇒ Object



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/manageiq/api/common/open_api/generator.rb', line 349

def openapi_schema_properties_value(klass_name, model, key, value)
  if key == model.primary_key
    {
      "$ref" => "##{SCHEMAS_PATH}/ID"
    }
  elsif key.ends_with?("_id")
    properties_value = {}
    properties_value["$ref"] = if generator_read_only_definitions.include?(klass_name)
                                 # Everything under providers data is read only for now
                                 "##{SCHEMAS_PATH}/ID"
                               else
                                 openapi_contents.dig(*path_parts(SCHEMAS_PATH), klass_name, "properties", key, "$ref") || "##{SCHEMAS_PATH}/ID"
                               end
    properties_value
  else
    properties_value = {
      "type" => "string"
    }

    case value..type
    when :datetime
      properties_value["format"] = "date-time"
    when :integer
      properties_value["type"] = "integer"
    when :float
      properties_value["type"] = "number"
    when :boolean
      properties_value["type"] = "boolean"
    when :jsonb
      properties_value["type"] = "object"
      ['type', 'items', 'properties', 'additionalProperties'].each do |property_key|
        prop = openapi_contents.dig(*path_parts(SCHEMAS_PATH), klass_name, "properties", key, property_key)
        properties_value[property_key] = prop unless prop.nil?
      end
    end

    # Take existing attrs, that we won't generate
    ['example', 'format', 'readOnly', 'title', 'description'].each do |property_key|
      property_value                 = openapi_contents.dig(*path_parts(SCHEMAS_PATH), klass_name, "properties", key, property_key)
      properties_value[property_key] = property_value if property_value
    end

    if generator_read_only_definitions.include?(klass_name) || generator_read_only_attributes.include?(key.to_sym)
      # Everything under providers data is read only for now
      properties_value['readOnly'] = true
    end

    properties_value.sort.to_h
  end
end

#openapi_show_description(klass_name) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/manageiq/api/common/open_api/generator.rb', line 242

def openapi_show_description(klass_name)
  {
    "summary"     => "Show an existing #{klass_name}",
    "operationId" => "show#{klass_name}",
    "description" => "Returns a #{klass_name} object",
    "parameters"  => [{ "$ref" => build_parameter("ID") }],
    "responses"   => {
      "200" => {
        "description" => "#{klass_name} info",
        "content"     => {
          "application/json" => {
            "schema" => { "$ref" => build_schema(klass_name) }
          }
        }
      },
      "404" => {
        "description" => "Not found",
        "content"     => {
          "application/json" => {
            "schema"         => { "$ref" => build_schema_error_not_found }
          }
        }
      }
    }
  }
end

#openapi_update_description(klass_name, verb) ⇒ Object



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/manageiq/api/common/open_api/generator.rb', line 316

def openapi_update_description(klass_name, verb)
  action = verb == "patch" ? "Update" : "Replace"
  {
    "summary"     => "#{action} an existing #{klass_name}",
    "operationId" => "#{action.downcase}#{klass_name}",
    "description" => "#{action}s a #{klass_name} object",
    "parameters"  => [
      { "$ref" => build_parameter("ID") }
    ],
    "requestBody" => {
      "content"     => {
        "application/json" => {
          "schema" => { "$ref" => build_schema(klass_name) }
        }
      },
      "description" => "#{klass_name} attributes to update",
      "required"    => true
    },
    "responses"   => {
      "204" => { "description" => "Updated, no content" },
      "400" => { "description" => "Bad request"         },
      "404" => {
        "description" => "Not found",
        "content"     => {
          "application/json" => {
            "schema"         => { "$ref" => build_schema_error_not_found }
          }
        }
      }
    }
  }
end

#parametersObject



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
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/manageiq/api/common/open_api/generator.rb', line 136

def parameters
  @parameters ||= {
    "QueryFilter" => {
      "in"          => "query",
      "name"        => "filter",
      "description" => "Filter for querying collections.",
      "required"    => false,
      "style"       => "deepObject",
      "explode"     => true,
      "schema"      => {
        "type" => "object"
      }
    },
    "QueryLimit"  => {
      "in"          => "query",
      "name"        => "limit",
      "description" => "The numbers of items to return per page.",
      "required"    => false,
      "schema"      => {
        "type"    => "integer",
        "minimum" => 1,
        "maximum" => 1000,
        "default" => 100
      }
    },
    "QueryOffset" => {
      "in"          => "query",
      "name"        => "offset",
      "description" => "The number of items to skip before starting to collect the result set.",
      "required"    => false,
      "schema"      => {
        "type"    => "integer",
        "minimum" => 0,
        "default" => 0
      }
    },
  }
end

#path_parts(openapi_path) ⇒ Object



12
13
14
# File 'lib/manageiq/api/common/open_api/generator.rb', line 12

def path_parts(openapi_path)
  openapi_path.split("/")[1..-1]
end

#rails_routesObject



26
27
28
29
30
31
32
33
34
# File 'lib/manageiq/api/common/open_api/generator.rb', line 26

def rails_routes
  Rails.application.routes.routes.each_with_object([]) do |route, array|
    r = ActionDispatch::Routing::RouteWrapper.new(route)
    next if r.internal? # Don't display rails routes
    next if r.engine? # Don't care right now...

    array << r
  end
end

#run(graphql = false) ⇒ Object



400
401
402
403
404
405
406
407
408
# File 'lib/manageiq/api/common/open_api/generator.rb', line 400

def run(graphql = false)
  new_content = openapi_contents.dup
  new_content["paths"] = build_paths.sort.to_h
  new_content["components"] ||= {}
  new_content["components"]["schemas"]    = schemas.sort.each_with_object({})    { |(name, val), h| h[name] = val || openapi_contents["components"]["schemas"][name]    || {} }
  new_content["components"]["parameters"] = parameters.sort.each_with_object({}) { |(name, val), h| h[name] = val || openapi_contents["components"]["parameters"][name] || {} }
  File.write(openapi_file, JSON.pretty_generate(new_content) + "\n")
  ManageIQ::API::Common::GraphQL::Generator.generate(api_version, new_content) if graphql
end

#schemasObject



61
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
97
98
99
100
101
# File 'lib/manageiq/api/common/open_api/generator.rb', line 61

def schemas
  @schemas ||= {
    "CollectionLinks"    => {
      "type"       => "object",
      "properties" => {
        "first" => {
          "type" => "string"
        },
        "last"  => {
          "type" => "string"
        },
        "next"  => {
          "type" => "string"
        },
        "prev"  => {
          "type" => "string"
        },
      }
    },
    "CollectionMetadata" => {
      "type"       => "object",
      "properties" => {
        "count"  => {
          "type" => "integer"
        },
        "limit"  => {
          "type" => "integer"
        },
        "offset" => {
          "type" => "integer"
        }
      }
    },
    "ID"                 => {
      "type"        => "string",
      "description" => "ID of the resource",
      "pattern"     => "^\\d+$",
      "readOnly"    => true,
    },
  }
end