gitlab-grape-openapi 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 10a34008541dedbab4063d199bbdb94f2d669d94101be45af1023e362bf8c72f
4
- data.tar.gz: ba640eb0b0553149b7776bd53afef9eee0c2cc5316dbb4917c44c2099b138d0e
3
+ metadata.gz: 1a821f273e073b35414be3f6c2c7f34e517288e2adb77c7eb55c3076b095b464
4
+ data.tar.gz: 46cdf4d7cbef2541b3b5b4a56402dfb96d1f9d3740a6fcba9122d6b32b7112cf
5
5
  SHA512:
6
- metadata.gz: fd55dfbd2de53ec38abfd182f89d2dcbf2f03b916fbde38525dd8566c5984d134b21a9ff112123a7d2d9dbec0fc8077c8bf4a04d40117c902215e4a4cb6eb52b
7
- data.tar.gz: 4ece03be3b48a4f4082539446d72ab4ac68b8cd0a022ee125f777c7196dd2aac73b154bc98f1518ac078da6b13b26a80c0a0a4dfabada8f220d461b507202e2c
6
+ metadata.gz: 6bf28a6d866c98071dca44a278e52b575c66481a9acefae7c658a9206a8d678f992777bd682b0782fd30f7206de634a2f58f7f5fea45bdc2d72039cba1263422
7
+ data.tar.gz: bcf139d99fcefaeb2a51af83251b431ba5b7bad9eac4df549f7e160e418144dbc6f06dbf4fbe8285c1fa0acd058dbcb1b7d510180cc589d80c71a276bbea59c1
data/README.md CHANGED
@@ -17,6 +17,30 @@
17
17
 
18
18
  Internal gem for generating [OpenAPI 3.0](https://spec.openapis.org/oas/v3.0.0) specifications from [Grape](https://github.com/ruby-grape/grape) API definitions, used by [`gitlab-org/gitlab`](https://gitlab.com/gitlab-org/gitlab) to publish its REST API reference.
19
19
 
20
+ ## Table of contents
21
+
22
+ - [Installation](#installation)
23
+ - [Configuration](#configuration)
24
+ - [Configuration Options](#configuration-options)
25
+ - [Annotations](#annotations)
26
+ - [Usage](#usage)
27
+ - [Generating an OpenAPI Specification](#generating-an-openapi-specification)
28
+ - [Usage with `gitlab-org/gitlab`](#usage-with-gitlab-orggitlab)
29
+ - [Architecture](#architecture)
30
+ - [Parameter constraints](#parameter-constraints)
31
+ - [Registries](#registries)
32
+ - [Response media types](#response-media-types)
33
+ - [Schema-file responses](#schema-file-responses)
34
+ - [Optional path segments](#optional-path-segments)
35
+ - [Operation IDs and request body schemas](#operation-ids-and-request-body-schemas)
36
+ - [Development](#development)
37
+ - [Running Tests](#running-tests)
38
+ - [Linting](#linting)
39
+ - [Specifications](#specifications)
40
+ - [Releasing](#releasing)
41
+ - [Contributing](#contributing)
42
+ - [License](#license)
43
+
20
44
  ## Installation
21
45
 
22
46
  Add to your Gemfile:
@@ -44,6 +68,8 @@ Gitlab::GrapeOpenapi.configure do |config|
44
68
  version: 'v1',
45
69
  terms_of_service: 'https://example.com/terms'
46
70
  )
71
+ # A plain Hash (symbol or string keys) is also accepted and wrapped in Models::Info:
72
+ # config.info = { title: 'My API', version: 'v1' }
47
73
 
48
74
  # API path configuration
49
75
  config.api_prefix = "api" # Default: "api"
@@ -103,7 +129,7 @@ end
103
129
 
104
130
  | Option | Type | Default | Description |
105
131
  | ---------------------- | ------------------------------- | ------- | ---------------------------------------------------------------- |
106
- | `info` | `Models::Info` | `nil` | API metadata (title, description, version, terms of service) |
132
+ | `info` | `Models::Info` or `Hash` | `nil` | **Required.** API metadata (title, description, version, terms of service). `title` and `version` must be present and non-blank (not empty or whitespace-only), otherwise generation raises `Gitlab::GrapeOpenapi::ConfigurationError`. A `Hash` is wrapped in `Models::Info`; any other type also raises `ConfigurationError`. |
107
133
  | `api_prefix` | `String` | `"api"` | URL prefix for API routes |
108
134
  | `api_version` | `String` | `"v1"` | API version string |
109
135
  | `servers` | `Array<Models::Server>` | `[]` | Server definitions for the API |
@@ -114,6 +140,7 @@ end
114
140
  | `warnings` | `Boolean` | `false` | Emit stderr warnings for synthesized params, skipped constraints |
115
141
  | `cross_field_group_limit` | `Integer` | `30` | Cross-field groups larger than this are summarised on the endpoint |
116
142
  | `cross_field_messages` | `Hash` | `{}` | Endpoint wording for summarised groups, keyed by `"METHOD /path"` |
143
+ | `schema_paths` | `Array<String>` | `[]` | Directories searched for the JSON schema files named by `success schema:` |
117
144
 
118
145
  ### Annotations
119
146
 
@@ -123,6 +150,7 @@ The `annotations` configuration maps Grape route settings to OpenAPI vendor exte
123
150
  config.annotations = {
124
151
  lifecycle: 'x-gitlab-lifecycle'
125
152
  }
153
+ ```
126
154
 
127
155
  When a Grape endpoint has:
128
156
 
@@ -205,13 +233,15 @@ Generator
205
233
  The gem documents Grape's cross-field param constraints by appending a note to
206
234
  each affected parameter's (or request-body property's) `description` — for both
207
235
  query/path params (`GET`/`DELETE`) and request-body params
208
- (`POST`/`PUT`/`PATCH`). Three constraints are supported:
236
+ (`POST`/`PUT`/`PATCH`). All four of Grape's cross-field constraints are
237
+ supported:
209
238
 
210
239
  | Grape declaration | Note appended to every member |
211
240
  |-------------------|-------------------------------|
212
241
  | `mutually_exclusive :author_id, :author_username` | ``Mutually exclusive with `author_username`.`` |
213
242
  | `exactly_one_of :project_id, :project_path` | ``Exactly one of `project_id`, `project_path` must be provided.`` |
214
243
  | `at_least_one_of :assignee_id, :reviewer_id` | ``At least one of `assignee_id`, `reviewer_id` must be provided.`` |
244
+ | `all_or_none_of :extern_uid, :provider` | ``All or none of `extern_uid`, `provider` must be provided.`` |
215
245
 
216
246
  OpenAPI 3.0 has no cross-parameter constraint keyword, and the target renderer
217
247
  (Scalar) does not render JSON Schema `not`/`allOf`, so the constraint is stated
@@ -241,8 +271,7 @@ param into the route's query params, a constraint nested inside a `Hash` *query*
241
271
  filter is documented the same as a top-level one. A constraint nested inside a
242
272
  request-body object property has no top-level property to attach to and is
243
273
  skipped; when `warnings` is enabled the gem logs one line per skipped group so it
244
- is visible in source. The remaining sibling constraint (`all_or_none_of`) is not
245
- yet supported.
274
+ is visible in source.
246
275
 
247
276
  ### Registries
248
277
 
@@ -313,6 +342,29 @@ A route that declares `success File` (with no `produces`) is treated as
313
342
  `application/octet-stream`, matching `grape-swagger`. An explicit `produces`
314
343
  takes precedence, so it can override that inference.
315
344
 
345
+ ### Schema-file responses
346
+
347
+ A response that no entity builds (for example one assembled by a proxy) can be
348
+ described by a JSON schema file instead:
349
+
350
+ ```ruby
351
+ desc 'Run a query' do
352
+ success code: 200, schema: 'orbit/query_response'
353
+ end
354
+ ```
355
+
356
+ The name is looked up as `<name>.json` in each directory of `config.schema_paths`
357
+ (first match wins). It may contain lowercase letters, digits, `_` and `/`. The
358
+ file is emitted once under `components/schemas`, named by capitalizing each
359
+ `/`- and `_`-separated part (`orbit/query_response` becomes `OrbitQueryResponse`),
360
+ and referenced from the response. `is_array`, `example`, `examples` and `message`
361
+ work as with `model:`, and `model:` wins when both are given. A missing or
362
+ invalid file, or a component name that is already taken, raises
363
+ `Gitlab::GrapeOpenapi::SchemaFileError`.
364
+
365
+ The file must be an OpenAPI 3.0 Schema Object that JSON Schema validators also
366
+ understand: no `$schema`, `$defs`, type arrays or `nullable`.
367
+
316
368
  ### Optional path segments
317
369
 
318
370
  Grape lets a route mark a path segment as optional with parentheses, e.g.
@@ -336,6 +388,17 @@ Generating the combinatorial set of paths for routes with more than one
336
388
  param-bearing optional segment is **not** supported: such a route raises
337
389
  `Gitlab::GrapeOpenapi::MultipleOptionalSegmentsError`.
338
390
 
391
+ ### Operation IDs and request body schemas
392
+
393
+ Operation IDs are derived from the HTTP method and normalized route path. If
394
+ two routes produce the same ID, the later operation receives a numeric suffix
395
+ such as `_2`, keeping IDs unique without renaming unaffected operations.
396
+
397
+ Inline request bodies are emitted as component schemas named
398
+ `<operationId>Request`. The name is independent of the body shape, so adding or
399
+ changing a field does not rename the generated schema; identical bodies on
400
+ different operations retain their own operation-specific names.
401
+
339
402
  ## Development
340
403
 
341
404
  ```bash
@@ -355,6 +418,18 @@ bundle exec rspec
355
418
  bundle exec rubocop
356
419
  ```
357
420
 
421
+ ### Specifications
422
+
423
+ The gem's behaviour is specified with [OpenSpec](https://github.com/Fission-AI/OpenSpec)
424
+ in [`openspec/specs/`](openspec/specs), one capability per directory. Changes to
425
+ generated output start as an OpenSpec change proposal; see `CLAUDE.md` for the
426
+ workflow.
427
+
428
+ ```bash
429
+ npx -y @fission-ai/openspec@1.13.2 list --specs
430
+ npx -y @fission-ai/openspec@1.13.2 validate --all --strict
431
+ ```
432
+
358
433
  ### Releasing
359
434
 
360
435
  Releases are driven by the
@@ -5,7 +5,7 @@ module Gitlab
5
5
  class Configuration
6
6
  attr_accessor :api_version, :api_prefix, :excluded_api_classes, :servers, :security_schemes, :info,
7
7
  :tag_overrides, :annotations, :coercer_mappings, :warnings,
8
- :cross_field_group_limit, :cross_field_messages
8
+ :cross_field_group_limit, :cross_field_messages, :schema_paths
9
9
 
10
10
  def initialize
11
11
  @api_prefix = "api"
@@ -20,6 +20,7 @@ module Gitlab
20
20
  @annotations = {}
21
21
  @coercer_mappings = {}
22
22
  @warnings = false
23
+ @schema_paths = []
23
24
 
24
25
  # Cross field validations
25
26
  # Allow custom descriptions for endpoints whose groups of cross-validated
@@ -69,7 +69,15 @@ module Gitlab
69
69
  notes: GROUP_SENTENCE.call('At least one of')
70
70
  }.freeze
71
71
 
72
- CONSTRAINTS = [MUTUALLY_EXCLUSIVE, EXACTLY_ONE_OF, AT_LEAST_ONE_OF].freeze
72
+ ALL_OR_NONE_OF = {
73
+ classes: [
74
+ 'Grape::Validations::Validators::AllOrNoneOfValidator' # Grape all versions
75
+ ].freeze,
76
+ summary_format: '%d related parameters must be provided together, or not at all.',
77
+ notes: GROUP_SENTENCE.call('All or none of')
78
+ }.freeze
79
+
80
+ CONSTRAINTS = [MUTUALLY_EXCLUSIVE, EXACTLY_ONE_OF, AT_LEAST_ONE_OF, ALL_OR_NONE_OF].freeze
73
81
 
74
82
  # For callers that need notes alone, which is every caller that has no
75
83
  # nested scope to skip - see `#notes`.
@@ -10,23 +10,25 @@ module Gitlab
10
10
 
11
11
  def self.convert(
12
12
  route, schema_registry, request_body_registry, inherited_path_params: {},
13
- path_override: nil, removed_params: [])
13
+ path_override: nil, removed_params: [], operation_id_registry: nil)
14
14
  new(
15
15
  route,
16
16
  schema_registry,
17
17
  request_body_registry,
18
18
  inherited_path_params: inherited_path_params,
19
19
  path_override: path_override,
20
- removed_params: removed_params
20
+ removed_params: removed_params,
21
+ operation_id_registry: operation_id_registry
21
22
  ).convert
22
23
  end
23
24
 
24
25
  def initialize(
25
26
  route, schema_registry, request_body_registry, inherited_path_params: {},
26
- path_override: nil, removed_params: [])
27
+ path_override: nil, removed_params: [], operation_id_registry: nil)
27
28
  @route = route
28
29
  @schema_registry = schema_registry
29
30
  @request_body_registry = request_body_registry
31
+ @operation_id_registry = operation_id_registry
30
32
  @inherited_path_params = inherited_path_params
31
33
  # @path_override and @removed_params are set together when optional-path-segment variants exist
32
34
  @path_override = path_override
@@ -38,8 +40,10 @@ module Gitlab
38
40
  end
39
41
 
40
42
  def convert
43
+ id = operation_id_registry ? operation_id_registry.register(operation_id) : operation_id
44
+
41
45
  Models::Operation.new.tap do |operation|
42
- operation.operation_id = operation_id
46
+ operation.operation_id = id
43
47
  operation.summary = extract_description
44
48
  operation.description = annotate_oversized_constraints(extract_detail)
45
49
  operation.tags = extract_tags
@@ -47,7 +51,7 @@ module Gitlab
47
51
  operation.hidden = extract_hidden
48
52
  operation.parameters = extract_parameters
49
53
  operation.responses = ResponseConverter.new(@route, @schema_registry).convert
50
- operation.request_body = extract_request_body || {}
54
+ operation.request_body = extract_request_body(id) || {}
51
55
  operation.annotations = extract_annotations
52
56
  end
53
57
  end
@@ -55,7 +59,7 @@ module Gitlab
55
59
  private
56
60
 
57
61
  attr_reader :config, :route, :options, :pattern, :endpoint, :schema_registry, :request_body_registry,
58
- :inherited_path_params, :path_override, :removed_params
62
+ :inherited_path_params, :path_override, :removed_params, :operation_id_registry
59
63
 
60
64
  def route_method
61
65
  @route.request_method
@@ -301,12 +305,13 @@ module Gitlab
301
305
  GrapeCompat.validations_for(route, attribute)
302
306
  end
303
307
 
304
- def extract_request_body
308
+ def extract_request_body(id)
305
309
  RequestBodyConverter.convert(
306
310
  route: route,
307
311
  options: options,
308
312
  params: options[:params],
309
- request_body_registry: request_body_registry
313
+ request_body_registry: request_body_registry,
314
+ operation_id: id
310
315
  )
311
316
  end
312
317
  end
@@ -31,6 +31,7 @@ module Gitlab
31
31
  @routes = routes
32
32
  @schema_registry = schema_registry
33
33
  @request_body_registry = request_body_registry
34
+ @operation_id_registry = OperationIdRegistry.new
34
35
  @config = Gitlab::GrapeOpenapi.configuration
35
36
  @inherited_path_params = {}
36
37
  end
@@ -80,6 +81,17 @@ module Gitlab
80
81
  next unless definition
81
82
 
82
83
  EntityConverter.register(definition, @schema_registry)
84
+ register_schema_files(definition)
85
+ end
86
+ end
87
+
88
+ def register_schema_files(definition)
89
+ case definition
90
+ when Hash
91
+ return if EntityConverter.grape_entity?(definition[:model])
92
+
93
+ @schema_registry.register_file(definition[:schema]) if definition[:schema]
94
+ when Array then definition.each { |item| register_schema_files(item) }
83
95
  end
84
96
  end
85
97
 
@@ -116,15 +128,18 @@ module Gitlab
116
128
 
117
129
  def build_path_item(routes_for_path, variant)
118
130
  path_item = Models::PathItem.new
131
+ routes_by_method = routes_for_path.group_by { |route| extract_method(route) }
132
+ .transform_values(&:last)
119
133
 
120
- routes_for_path.each do |route|
134
+ routes_by_method.each_value do |route|
121
135
  operation = OperationConverter.convert(
122
136
  route,
123
137
  schema_registry,
124
138
  request_body_registry,
125
139
  inherited_path_params: inherited_path_params,
126
140
  path_override: variant.path_override,
127
- removed_params: variant.removed_params
141
+ removed_params: variant.removed_params,
142
+ operation_id_registry: @operation_id_registry
128
143
  )
129
144
  method = extract_method(route)
130
145
  path_item.add_operation(method, operation)
@@ -9,17 +9,19 @@ module Gitlab
9
9
  GET_METHOD = 'GET'
10
10
  DELETE_METHOD = 'DELETE'
11
11
 
12
- attr_reader :route, :options, :params, :request_body_registry
12
+ attr_reader :route, :options, :params, :request_body_registry, :operation_id
13
13
 
14
- def self.convert(route:, options:, params:, request_body_registry:)
15
- new(route: route, options: options, params: params, request_body_registry: request_body_registry).convert
14
+ def self.convert(route:, options:, params:, request_body_registry:, operation_id:)
15
+ new(route: route, options: options, params: params, request_body_registry: request_body_registry,
16
+ operation_id: operation_id).convert
16
17
  end
17
18
 
18
- def initialize(route:, options:, params:, request_body_registry:)
19
+ def initialize(route:, options:, params:, request_body_registry:, operation_id:)
19
20
  @route = route
20
21
  @options = options
21
22
  @params = params
22
23
  @request_body_registry = request_body_registry
24
+ @operation_id = operation_id
23
25
  end
24
26
 
25
27
  def convert
@@ -58,7 +60,7 @@ module Gitlab
58
60
  }
59
61
  schema[:required] = required_params unless required_params.empty?
60
62
 
61
- schema_ref = request_body_registry.register(schema)
63
+ schema_ref = request_body_registry.register(schema, name: "#{operation_id}Request")
62
64
 
63
65
  {
64
66
  required: required_params.any?,
@@ -63,14 +63,14 @@ module Gitlab
63
63
 
64
64
  def process_hash_entity(entity_hash)
65
65
  if entity_hash[:model] && EntityConverter.grape_entity?(entity_hash[:model])
66
- status_code = entity_hash[:code] || infer_success_code(with_body: true)
67
66
  add_response_with_entity(
68
- status_code: status_code,
69
- description: entity_hash[:message] || http_status_text(status_code),
70
- entity_class: entity_hash[:model],
71
- example: entity_hash[:example],
72
- examples: entity_hash[:examples],
73
- is_array: entity_hash.fetch(:is_array, declared_is_array?)
67
+ **hash_response(entity_hash),
68
+ entity_class: entity_hash[:model]
69
+ )
70
+ elsif entity_hash[:schema]
71
+ add_response_with_entity(
72
+ **hash_response(entity_hash),
73
+ schema_name: SchemaRegistry.file_component_name(entity_hash[:schema])
74
74
  )
75
75
  else
76
76
  status_code = entity_hash[:code] || infer_success_code(with_body: declared_body?)
@@ -82,38 +82,28 @@ module Gitlab
82
82
  end
83
83
  end
84
84
 
85
+ def hash_response(entity_hash)
86
+ status_code = entity_hash[:code] || infer_success_code(with_body: true)
87
+ {
88
+ status_code: status_code,
89
+ description: entity_hash[:message] || http_status_text(status_code),
90
+ example: entity_hash[:example],
91
+ examples: entity_hash[:examples],
92
+ is_array: entity_hash.fetch(:is_array, declared_is_array?)
93
+ }
94
+ end
95
+
85
96
  def process_array_entities(entity_array)
86
97
  entity_array.each do |definition|
87
98
  case definition
88
99
  when Hash
89
- process_array_hash_item(definition)
100
+ process_hash_entity(definition)
90
101
  when Class
91
102
  process_class_entity(definition)
92
103
  end
93
104
  end
94
105
  end
95
106
 
96
- def process_array_hash_item(definition)
97
- if definition[:model] && EntityConverter.grape_entity?(definition[:model])
98
- status_code = definition[:code] || infer_success_code(with_body: true)
99
- add_response_with_entity(
100
- status_code: status_code,
101
- description: definition[:message] || http_status_text(status_code),
102
- entity_class: definition[:model],
103
- example: definition[:example],
104
- examples: definition[:examples],
105
- is_array: definition.fetch(:is_array, declared_is_array?)
106
- )
107
- else
108
- status_code = definition[:code] || infer_success_code(with_body: declared_body?)
109
- add_simple_response(
110
- status_code: status_code,
111
- description: definition[:message] || http_status_text(status_code),
112
- content: declared_content
113
- )
114
- end
115
- end
116
-
117
107
  def extract_failure_responses
118
108
  explicit_codes = Array(@route.http_codes)
119
109
  defined_status_codes = explicit_codes.filter_map { |c| (c.is_a?(Hash) ? c[:code] : c[0])&.to_i }
@@ -136,11 +126,13 @@ module Gitlab
136
126
  end
137
127
 
138
128
  def add_response_with_entity(
139
- status_code:, description:, entity_class:, example: nil, examples: nil, is_array: false)
129
+ status_code:, description:, entity_class: nil, schema_name: nil, example: nil, examples: nil,
130
+ is_array: false)
140
131
  response = Models::Response.new(
141
132
  status_code: status_code,
142
133
  description: description,
143
134
  entity_class: entity_class,
135
+ schema_name: schema_name,
144
136
  example: example,
145
137
  examples: examples,
146
138
  is_array: is_array
@@ -15,11 +15,13 @@ module Gitlab
15
15
  end
16
16
 
17
17
  def generate
18
+ # Resolved before initialize_tags so an invalid config.info fails before any conversion runs.
19
+ info = openapi_info
18
20
  initialize_tags
19
21
 
20
22
  {
21
23
  openapi: '3.0.0',
22
- info: Gitlab::GrapeOpenapi.configuration.info.to_h,
24
+ info: info,
23
25
  tags: tag_registry.tags.sort_by { |t| t.fetch(:name, '') },
24
26
  servers: Gitlab::GrapeOpenapi.configuration.servers.map(&:to_h),
25
27
  paths: paths,
@@ -50,9 +52,37 @@ module Gitlab
50
52
 
51
53
  private
52
54
 
55
+ def openapi_info
56
+ hash = configured_info.to_h
57
+ return hash unless blank?(hash[:title]) || blank?(hash[:version])
58
+
59
+ raise ConfigurationError, "config.info must be set with at least a title and version"
60
+ end
61
+
62
+ def configured_info
63
+ info = Gitlab::GrapeOpenapi.configuration.info
64
+
65
+ case info
66
+ when Models::Info then info
67
+ when Hash then Models::Info.new(**info.transform_keys(&:to_sym))
68
+ when nil then Models::Info.new
69
+ else
70
+ raise ConfigurationError,
71
+ "config.info must be a Gitlab::GrapeOpenapi::Models::Info or Hash, got #{info.class}"
72
+ end
73
+ end
74
+
75
+ def blank?(value)
76
+ value.to_s.strip.empty?
77
+ end
78
+
53
79
  def schemas
54
80
  entity_schemas = @schema_registry.schemas.transform_values(&:to_h)
55
81
  request_body_schemas = @request_body_registry.schemas
82
+
83
+ collisions = entity_schemas.keys & request_body_schemas.keys
84
+ raise ArgumentError, "Schema component name collision: #{collisions.join(', ')}" unless collisions.empty?
85
+
56
86
  entity_schemas.merge(request_body_schemas)
57
87
  end
58
88
  end
@@ -7,18 +7,21 @@ module Gitlab
7
7
  class Response
8
8
  attr_reader :status_code, :description, :entity_class, :headers, :content_type
9
9
 
10
+ # rubocop:disable Metrics/ParameterLists -- keyword arguments of a value object
10
11
  def initialize(
11
- status_code:, description:, entity_class:, headers: {}, content_type: 'application/json',
12
- example: nil, examples: nil, is_array: false)
12
+ status_code:, description:, entity_class: nil, schema_name: nil, headers: {},
13
+ content_type: 'application/json', example: nil, examples: nil, is_array: false)
13
14
  @status_code = status_code.to_s
14
15
  @description = description
15
16
  @entity_class = entity_class
17
+ @schema_name = schema_name
16
18
  @headers = headers
17
19
  @content_type = content_type
18
20
  @example = example
19
21
  @examples = examples
20
22
  @is_array = is_array
21
23
  end
24
+ # rubocop:enable Metrics/ParameterLists
22
25
 
23
26
  def to_h(schema_registry)
24
27
  response = {
@@ -49,7 +52,7 @@ module Gitlab
49
52
  end
50
53
 
51
54
  def schema_ref(schema_registry)
52
- normalized_name = schema_registry.register(entity_class, nil)
55
+ normalized_name = @schema_name || schema_registry.register(entity_class, nil)
53
56
  "#/components/schemas/#{normalized_name}"
54
57
  end
55
58
  end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gitlab
4
+ module GrapeOpenapi
5
+ class OperationIdRegistry
6
+ def initialize
7
+ @operation_ids = {}
8
+ end
9
+
10
+ def register(candidate)
11
+ operation_id = candidate
12
+ suffix = 2
13
+
14
+ while @operation_ids.key?(operation_id)
15
+ operation_id = "#{candidate}_#{suffix}"
16
+ suffix += 1
17
+ end
18
+
19
+ @operation_ids[operation_id] = true
20
+ operation_id
21
+ end
22
+ end
23
+ end
24
+ end
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'openssl'
4
-
5
3
  module Gitlab
6
4
  module GrapeOpenapi
7
5
  class RequestBodyRegistry
@@ -11,47 +9,19 @@ module Gitlab
11
9
 
12
10
  def initialize
13
11
  @schemas = {}
14
- @schema_hashes = {}
15
12
  end
16
13
 
17
- def register(schema)
14
+ def register(schema, name:)
18
15
  return nil if schema.blank?
19
16
 
20
- schema_hash = compute_hash(schema)
21
-
22
- if @schema_hashes.key?(schema_hash)
23
- existing_name = @schema_hashes[schema_hash]
24
- return { '$ref' => "#{SCHEMA_PATH_PREFIX}#{existing_name}" }
17
+ if @schemas.key?(name) && @schemas[name] != schema
18
+ raise ArgumentError, "Request body schema name '#{name}' is already registered"
25
19
  end
26
20
 
27
- name = "RequestBody_#{short_hash(schema_hash)}"
28
21
  @schemas[name] = schema
29
- @schema_hashes[schema_hash] = name
30
22
 
31
23
  { '$ref' => "#{SCHEMA_PATH_PREFIX}#{name}" }
32
24
  end
33
-
34
- private
35
-
36
- def compute_hash(schema)
37
- normalized = normalize_for_hash(schema)
38
- OpenSSL::Digest::SHA256.hexdigest(normalized.to_s)
39
- end
40
-
41
- def short_hash(full_hash)
42
- full_hash[0, 12]
43
- end
44
-
45
- def normalize_for_hash(obj)
46
- case obj
47
- when Hash
48
- obj.sort.map { |k, v| [k.to_s, normalize_for_hash(v)] }
49
- when Array
50
- obj.map { |v| normalize_for_hash(v) }
51
- else
52
- obj
53
- end
54
- end
55
25
  end
56
26
  end
57
27
  end
@@ -5,12 +5,42 @@ module Gitlab
5
5
  class SchemaRegistry
6
6
  attr_reader :schemas
7
7
 
8
+ SCHEMA_FILE_NAME = %r{\A[a-z0-9_]+(/[a-z0-9_]+)*\z}
9
+
10
+ def self.file_component_name(name)
11
+ name.to_s.split(%r{[/_]}).map(&:capitalize).join
12
+ end
13
+
8
14
  def initialize
9
15
  @schemas = {}
16
+ @file_paths = {}
17
+ end
18
+
19
+ # Registers the `<name>.json` schema found in `config.schema_paths` and
20
+ # returns its component name.
21
+ def register_file(name)
22
+ unless SCHEMA_FILE_NAME.match?(name.to_s)
23
+ raise SchemaFileError, "Invalid schema name #{name.inspect}: " \
24
+ "use lowercase letters, digits and underscores, with '/' between segments"
25
+ end
26
+
27
+ path = find_schema_file(name)
28
+ component = self.class.file_component_name(name)
29
+ return component if @file_paths[component] == path
30
+
31
+ raise SchemaFileError, "Schema #{name.inspect} collides with component #{component}" if @schemas.key?(component)
32
+
33
+ @schemas[component] = deep_freeze(parse_schema_file(path))
34
+ @file_paths[component] = path
35
+ component
10
36
  end
11
37
 
12
38
  def register(entity_class, schema)
13
39
  normalized_name = normalize_entity_class(entity_class)
40
+ if @file_paths.key?(normalized_name)
41
+ raise SchemaFileError, "Entity #{entity_class.name} collides with schema file component #{normalized_name}"
42
+ end
43
+
14
44
  return normalized_name if @schemas.key?(normalized_name)
15
45
  return normalized_name unless schema.is_a?(Models::Schema)
16
46
 
@@ -21,6 +51,34 @@ module Gitlab
21
51
  def normalize_entity_class(entity_class)
22
52
  entity_class.name.delete(':')
23
53
  end
54
+
55
+ private
56
+
57
+ def find_schema_file(name)
58
+ dirs = Gitlab::GrapeOpenapi.configuration.schema_paths
59
+ path = dirs.map { |dir| File.join(dir, "#{name}.json") }.find { |candidate| File.file?(candidate) }
60
+ return path if path
61
+
62
+ searched = dirs.empty? ? 'config.schema_paths is empty' : "searched #{dirs.join(', ')}"
63
+ raise SchemaFileError, "Schema file #{name.inspect} not found: #{searched}"
64
+ end
65
+
66
+ def parse_schema_file(path)
67
+ schema = JSON.parse(File.read(path))
68
+ return schema if schema.is_a?(Hash)
69
+
70
+ raise SchemaFileError, "Schema file #{path} must contain a JSON object"
71
+ rescue JSON::ParserError => e
72
+ raise SchemaFileError, "Schema file #{path} is not valid JSON: #{e.message}"
73
+ end
74
+
75
+ def deep_freeze(value)
76
+ case value
77
+ when Hash then value.each_value { |item| deep_freeze(item) }
78
+ when Array then value.each { |item| deep_freeze(item) }
79
+ end
80
+ value.freeze
81
+ end
24
82
  end
25
83
  end
26
84
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Gitlab
4
4
  module GrapeOpenapi
5
- VERSION = "0.6.0"
5
+ VERSION = "0.8.0"
6
6
  end
7
7
  end
@@ -1,11 +1,14 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "json"
4
+
3
5
  require_relative "gitlab/grape_openapi/version"
4
6
  require_relative "gitlab/grape_openapi/grape_compat"
5
7
  require_relative "gitlab/grape_openapi/configuration"
6
8
  require_relative "gitlab/grape_openapi/generator"
7
9
  require_relative "gitlab/grape_openapi/schema_registry"
8
10
  require_relative "gitlab/grape_openapi/request_body_registry"
11
+ require_relative "gitlab/grape_openapi/operation_id_registry"
9
12
  require_relative "gitlab/grape_openapi/tag_registry"
10
13
  require_relative "gitlab/grape_openapi/normalized_path"
11
14
 
@@ -51,10 +54,17 @@ module Gitlab
51
54
  module GrapeOpenapi
52
55
  GenerationError = Class.new(StandardError)
53
56
 
57
+ # Raised when `config.info` is missing a title or version.
58
+ ConfigurationError = Class.new(GenerationError)
59
+
54
60
  # Raised when a route declares more than one optional path segment
55
61
  # containing a named parameter (e.g. `/foo(/:a)/bar(/:b)`).
56
62
  MultipleOptionalSegmentsError = Class.new(GenerationError)
57
63
 
64
+ # Raised when a schema file named by a `success` declaration cannot be
65
+ # found, parsed or registered.
66
+ SchemaFileError = Class.new(GenerationError)
67
+
58
68
  class << self
59
69
  attr_writer :configuration
60
70
 
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gitlab-grape-openapi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.0
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - group::api
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-09-30 00:00:00.000000000 Z
11
+ date: 2026-10-02 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: grape
@@ -172,6 +172,7 @@ files:
172
172
  - lib/gitlab/grape_openapi/models/server_variable.rb
173
173
  - lib/gitlab/grape_openapi/models/tag.rb
174
174
  - lib/gitlab/grape_openapi/normalized_path.rb
175
+ - lib/gitlab/grape_openapi/operation_id_registry.rb
175
176
  - lib/gitlab/grape_openapi/request_body_registry.rb
176
177
  - lib/gitlab/grape_openapi/schema_registry.rb
177
178
  - lib/gitlab/grape_openapi/serializers/time.rb