gitlab-grape-openapi 0.7.0 → 0.9.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: b864030f21b5380efa37ccb02b953f5c8d07b2f4d2fe90eb66334e155674e2bc
4
- data.tar.gz: 37b0f04c277c0b1f1027bdb5f0839f06641a3c6e11fd2e9498cb9a192899914b
3
+ metadata.gz: a9e63791bdf9de237dc4f38df23bb3cc877fa66e23f6a62cc877504937bb6253
4
+ data.tar.gz: d4ab0c3f65fde3c4ee4ade74f93155f0bdc920110b804721049306963c82fda8
5
5
  SHA512:
6
- metadata.gz: d7e270e89449c2f1dbdfa2f6acb4bb841abf7bbb25adf064a3f41fbf2a61eb8e9f86f698d8c826cdb111cf19aa6f21269984453913fc53554ce6f7f8eb502ba8
7
- data.tar.gz: a6e772a0f79d6d1e010ddddf7a6504a96da9d94c2ad34db08bbf58d80e7bffd8df0364dc09b361c0da5cce3d2b163a2dc24cb5d57604a543926a2c1ddc4ed5fa
6
+ metadata.gz: 0a381afb3ce0bdc4fedcba33a68d631c9d00103afc124e0f67d66d4e2ae51f6c9450529eae54e0b501a62c826ad5d47fae3b8738712c2923db27cfc700dcacf6
7
+ data.tar.gz: b6fc6c04f49e0afbd19812b2fc7ef2b07ef11091d147655501acbf545cf0a0339922bdd9d7bbbc85305f90b41d84ae15fa84c228b75933413ca230fa0e59329f
data/README.md CHANGED
@@ -30,6 +30,7 @@ Internal gem for generating [OpenAPI 3.0](https://spec.openapis.org/oas/v3.0.0)
30
30
  - [Parameter constraints](#parameter-constraints)
31
31
  - [Registries](#registries)
32
32
  - [Response media types](#response-media-types)
33
+ - [Schema-file responses](#schema-file-responses)
33
34
  - [Optional path segments](#optional-path-segments)
34
35
  - [Operation IDs and request body schemas](#operation-ids-and-request-body-schemas)
35
36
  - [Development](#development)
@@ -138,6 +139,7 @@ end
138
139
  | `warnings` | `Boolean` | `false` | Emit stderr warnings for synthesized params, skipped constraints |
139
140
  | `cross_field_group_limit` | `Integer` | `30` | Cross-field groups larger than this are summarised on the endpoint |
140
141
  | `cross_field_messages` | `Hash` | `{}` | Endpoint wording for summarised groups, keyed by `"METHOD /path"` |
142
+ | `schema_paths` | `Array<String>` | `[]` | Directories searched for the JSON schema files named by `success schema:` |
141
143
 
142
144
  ### Annotations
143
145
 
@@ -261,8 +263,7 @@ the same `"METHOD /path"` string the warnings print. Without an entry the gem us
261
263
  a generic sentence and, with `warnings` enabled, names the endpoint so wording can
262
264
  be added.
263
265
 
264
- The gem reads the validation stack through `grape_compat`, so this works on both
265
- Grape 2.4 and 3.2. Each group is keyed by the full bracketed param path
266
+ The gem reads the validation stack through `grape_compat`. Each group is keyed by the full bracketed param path
266
267
  (`not[author_id]`) rather than the bare name. Because Grape flattens every nested
267
268
  param into the route's query params, a constraint nested inside a `Hash` *query*
268
269
  filter is documented the same as a top-level one. A constraint nested inside a
@@ -339,6 +340,50 @@ A route that declares `success File` (with no `produces`) is treated as
339
340
  `application/octet-stream`, matching `grape-swagger`. An explicit `produces`
340
341
  takes precedence, so it can override that inference.
341
342
 
343
+ A `failure` entry given as an Array can name, as its third element, the
344
+ entity Grape presents its error body with:
345
+
346
+ ```ruby
347
+ desc 'Create a tag' do
348
+ success Entities::Tag
349
+ failure [[400, 'Bad request', Entities::ApiError]]
350
+ end
351
+ ```
352
+
353
+ The `400` response then carries the entity's `$ref` as its `application/json`
354
+ content, and the entity is emitted under `components/schemas` like a success
355
+ entity. The standalone `is_array` applies to the `success` declaration only.
356
+ An entry whose code a success response already describes with content keeps
357
+ that content, and an entry for a 204 or 304 adds no content, since those
358
+ responses have no body. A model that is not a `Grape::Entity` class, a String
359
+ class name included, leaves the response with its description only, and so
360
+ does the `model:` of a Hash entry such as
361
+ `{ code: 409, message: 'Conflict', model: Entities::ApiError }`: Grape builds
362
+ an error body with the model of an Array entry only.
363
+
364
+ ### Schema-file responses
365
+
366
+ A response that no entity builds (for example one assembled by a proxy) can be
367
+ described by a JSON schema file instead:
368
+
369
+ ```ruby
370
+ desc 'Run a query' do
371
+ success code: 200, schema: 'orbit/query_response'
372
+ end
373
+ ```
374
+
375
+ The name is looked up as `<name>.json` in each directory of `config.schema_paths`
376
+ (first match wins). It may contain lowercase letters, digits, `_` and `/`. The
377
+ file is emitted once under `components/schemas`, named by capitalizing each
378
+ `/`- and `_`-separated part (`orbit/query_response` becomes `OrbitQueryResponse`),
379
+ and referenced from the response. `is_array`, `example`, `examples` and `message`
380
+ work as with `model:`, and `model:` wins when both are given. A missing or
381
+ invalid file, or a component name that is already taken, raises
382
+ `Gitlab::GrapeOpenapi::SchemaFileError`.
383
+
384
+ The file must be an OpenAPI 3.0 Schema Object that JSON Schema validators also
385
+ understand: no `$schema`, `$defs`, type arrays or `nullable`.
386
+
342
387
  ### Optional path segments
343
388
 
344
389
  Grape lets a route mark a path segment as optional with parentheses, e.g.
@@ -9,7 +9,7 @@ module Gitlab
9
9
  private
10
10
 
11
11
  def fail_fast_in_validations?(validations)
12
- validations&.any? { |v| v.dig(:opts, :fail_fast) }
12
+ validations&.any?(&:fail_fast?)
13
13
  end
14
14
 
15
15
  def annotate_fail_fast(desc)
@@ -12,11 +12,12 @@ module Gitlab
12
12
 
13
13
  def limit_for(validations)
14
14
  validation = validations&.find do |v|
15
- v[:validator_class].name == 'API::Validations::Validators::Limit'
16
- rescue NoMethodError
17
- false
15
+ # rubocop:disable Style/ClassEqualityComparison -- naming the constant
16
+ # would raise NameError where the validator is not defined
17
+ v.class.name == 'API::Validations::Validators::Limit'
18
+ # rubocop:enable Style/ClassEqualityComparison
18
19
  end
19
- validation && validation[:options]
20
+ validation && GrapeCompat.options_for(validation)
20
21
  end
21
22
 
22
23
  def apply_limit!(schema, validations)
@@ -2,17 +2,17 @@
2
2
 
3
3
  # Determines whether a param is nullable.
4
4
  #
5
- # Grape default behaviour sets nullability true for plain params.
6
- # Two declarations remove it: a `default:`, which Grape's
7
- # DefaultValidator substitutes for the null before the endpoint runs, and a path
8
- # parameter, which is a required URL segment.
5
+ # Grape default behaviour sets nullability true for plain params, and only a path
6
+ # parameter, which is a required URL segment, removes it. A `default:` does not:
7
+ # Grape's DefaultValidator replaces an explicit null with the default, so clients may
8
+ # still send null.
9
9
  #
10
10
  # The `minLength: 1` branch is mutually exclusive with nullability and stays coupled
11
11
  # here deliberately: applying the two independently would mark every required enum
12
12
  # nullable.
13
13
  #
14
- # NOTE: `param_options[:allow_blank]` is always nil. Grape omits allow_blank from
15
- # route.params, so that clause is dead and only `required && values` fires.
14
+ # `allow_blank: false` is read from the param's validators, not `param_options`:
15
+ # Grape omits allow_blank from route.params.
16
16
 
17
17
  module Gitlab
18
18
  module GrapeOpenapi
@@ -20,27 +20,19 @@ module Gitlab
20
20
  module Nullability
21
21
  private
22
22
 
23
- def apply_nullability!(schema, param_options, in_value: nil)
24
- if blank_rejected?(param_options)
23
+ def apply_nullability!(schema, param_options, validations: nil, in_value: nil)
24
+ if blank_rejected?(param_options, validations)
25
25
  schema[:minLength] = 1 if schema[:type] == 'string'
26
- elsif nullable?(param_options, in_value)
26
+ elsif in_value != 'path'
27
27
  mark_nullable!(schema)
28
28
  end
29
29
  end
30
30
 
31
- def blank_rejected?(param_options)
32
- param_options[:allow_blank] == false ||
31
+ def blank_rejected?(param_options, validations)
32
+ GrapeCompat.blank_disallowed?(validations) ||
33
33
  (param_options[:required] && param_options[:values])
34
34
  end
35
35
 
36
- def nullable?(param_options, in_value)
37
- return false if in_value == 'path'
38
-
39
- param_options[:default].nil?
40
- end
41
-
42
- # Grape substitutes the default regardless of which union member matched, so
43
- # nullability applies to every member or none.
44
36
  def mark_nullable!(schema)
45
37
  members = schema[:oneOf] || schema[:anyOf]
46
38
  return members.each { |member| member[:nullable] = true } if members
@@ -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
@@ -36,11 +36,11 @@ module Gitlab
36
36
  return unless validations
37
37
 
38
38
  coerce_validation = validations.find do |v|
39
- v[:validator_class] == Grape::Validations::Validators::CoerceValidator
39
+ v.instance_of?(Grape::Validations::Validators::CoerceValidator)
40
40
  end
41
41
  return unless coerce_validation
42
42
 
43
- coerce_validation.dig(:options, :method)
43
+ GrapeCompat.options_for(coerce_validation)&.dig(:method)
44
44
  end
45
45
 
46
46
  def inline_proc?(coercer_method)
@@ -8,13 +8,11 @@
8
8
  # Grape enforces them at runtime (HTTP 400).
9
9
  #
10
10
  # Each cross-field validator is a CONSTRAINTS entry pairing the validator class
11
- # names it carries across supported Grape versions (Grape 3.2 renamed one)
12
- # with a note strategy. A strategy receives every group of its kind found on the
11
+ # name with a note strategy. A strategy receives every group of its kind found on the
13
12
  # route (each group an array of top-level attribute-name strings) and returns
14
13
  # `{ param => note }`.
15
14
  #
16
- # The validations read and the Grape 2.x/3.2 shape difference are isolated in
17
- # GrapeCompat.
15
+ # The Grape internals read are isolated in GrapeCompat.
18
16
 
19
17
  module Gitlab
20
18
  module GrapeOpenapi
@@ -32,8 +30,7 @@ module Gitlab
32
30
 
33
31
  MUTUALLY_EXCLUSIVE = {
34
32
  classes: [
35
- 'Grape::Validations::Validators::MutualExclusionValidator', # Grape < 3.2
36
- 'Grape::Validations::Validators::MutuallyExclusiveValidator' # Grape >= 3.2
33
+ 'Grape::Validations::Validators::MutuallyExclusiveValidator'
37
34
  ].freeze,
38
35
  summary_format: 'At most one of %d related parameters may be provided.',
39
36
  notes: lambda do |groups|
@@ -55,7 +52,7 @@ module Gitlab
55
52
 
56
53
  EXACTLY_ONE_OF = {
57
54
  classes: [
58
- 'Grape::Validations::Validators::ExactlyOneOfValidator' # Grape all versions
55
+ 'Grape::Validations::Validators::ExactlyOneOfValidator'
59
56
  ].freeze,
60
57
  summary_format: 'Exactly one of %d related parameters must be provided.',
61
58
  notes: GROUP_SENTENCE.call('Exactly one of')
@@ -63,7 +60,7 @@ module Gitlab
63
60
 
64
61
  AT_LEAST_ONE_OF = {
65
62
  classes: [
66
- 'Grape::Validations::Validators::AtLeastOneOfValidator' # Grape all versions
63
+ 'Grape::Validations::Validators::AtLeastOneOfValidator'
67
64
  ].freeze,
68
65
  summary_format: 'At least one of %d related parameters must be provided.',
69
66
  notes: GROUP_SENTENCE.call('At least one of')
@@ -71,7 +68,7 @@ module Gitlab
71
68
 
72
69
  ALL_OR_NONE_OF = {
73
70
  classes: [
74
- 'Grape::Validations::Validators::AllOrNoneOfValidator' # Grape all versions
71
+ 'Grape::Validations::Validators::AllOrNoneOfValidator'
75
72
  ].freeze,
76
73
  summary_format: '%d related parameters must be provided together, or not at all.',
77
74
  notes: GROUP_SENTENCE.call('All or none of')
@@ -148,13 +145,10 @@ module Gitlab
148
145
 
149
146
  # Groups all validations on the route
150
147
  # Returns only validations with classes in CONSTRAINTS:
151
- # [[MUTUALLY_EXCLUSIVE, [
152
- # { validator_class: Grape::Validations::Validators::MutualExclusionValidator,
153
- # full_names: ["content", "files"] }
154
- # ]]]
148
+ # [[MUTUALLY_EXCLUSIVE, [#<Grape::Validations::Validators::MutuallyExclusiveValidator>]]]
155
149
  def matched_entries
156
150
  @matched_entries ||= begin
157
- by_validator = GrapeCompat.all_validations(route).group_by { |entry| validator_name(entry) }
151
+ by_validator = GrapeCompat.all_validations(route).group_by { |validator| validator.class.name }
158
152
 
159
153
  CONSTRAINTS.map do |constraint|
160
154
  [constraint, by_validator.values_at(*constraint[:classes]).compact.flatten]
@@ -195,16 +189,11 @@ module Gitlab
195
189
  (group - known_names).empty?
196
190
  end
197
191
 
198
- # eg. => 'Grape::Validations::Validators::MutuallyExclusiveValidator'
199
- def validator_name(entry)
200
- entry[:validator_class]&.name
201
- end
202
-
203
192
  # Full bracketed paths
204
193
  # top level eg. ["author_id", "author_username"]
205
194
  # nested(nested under `not:`) eg. ["not[author_id]", "not[author_username]"]
206
195
  def group_members(entry)
207
- Array(entry[:full_names]).map(&:to_s)
196
+ GrapeCompat.full_names_for(entry)
208
197
  end
209
198
  end
210
199
  end
@@ -295,12 +295,7 @@ module Gitlab
295
295
  @route.request_method
296
296
  end
297
297
 
298
- # Get all validations for a single attribute
299
- # Looks something like:
300
- # [{:attributes=>[:version_prefix],
301
- # :options=>/^[\d+.]+/,
302
- # :opts=>{:fail_fast=>false},
303
- # :validator_class=>Grape::Validations::Validators::RegexpValidator}]
298
+ # Get all validators declared for a single attribute
304
299
  def validations_for(attribute)
305
300
  GrapeCompat.validations_for(route, attribute)
306
301
  end
@@ -58,7 +58,7 @@ module Gitlab
58
58
  build_basic_schema(object_type, object_format)
59
59
  end
60
60
 
61
- apply_nullability!(built_schema, options, in_value: in_value)
61
+ apply_nullability!(built_schema, options, validations: validations, in_value: in_value)
62
62
  apply_limit!(built_schema, validations)
63
63
  apply_array_enum!(built_schema, options[:values])
64
64
  apply_default!(built_schema, options[:default], example: example)
@@ -120,10 +120,10 @@ module Gitlab
120
120
  return unless validations
121
121
 
122
122
  # Only support one Regex validation per attribute
123
- validation = validations&.find { |v| v[:validator_class] == Grape::Validations::Validators::RegexpValidator }
123
+ validation = validations&.find { |v| v.instance_of?(Grape::Validations::Validators::RegexpValidator) }
124
124
  return unless validation
125
125
 
126
- pattern = regexp_to_pattern(validation[:options])
126
+ pattern = regexp_to_pattern(GrapeCompat.options_for(validation))
127
127
  schema[:pattern] = pattern if pattern
128
128
  end
129
129
 
@@ -70,17 +70,30 @@ module Gitlab
70
70
  groups.transform_keys { |key| normalize_path(groups[key].first) }
71
71
  end
72
72
 
73
- # Register entities declared on the route's response so they appear in
74
- # `components.schemas` only for routes that are actually emitted.
75
- # Running this after `skip_route?` keeps registration in sync with the
76
- # final spec and avoids `no-unused-components` orphans for entities
77
- # that belong only to hidden routes or wildcard catch-alls.
73
+ # Register the entities of the route's success declaration so they
74
+ # appear in `components.schemas` only for routes that are actually
75
+ # emitted. Running this after `skip_route?` keeps registration in sync
76
+ # with the final spec and avoids `no-unused-components` orphans for
77
+ # entities that belong only to hidden routes or wildcard catch-alls.
78
+ # An entity named in a failure entry is registered by ResponseConverter
79
+ # instead, once it knows the response takes that entity as content.
78
80
  def register_route_entities(route)
79
81
  RESPONSE_DECLARATIONS.each do |key|
80
82
  definition = route.options[key]
81
83
  next unless definition
82
84
 
83
85
  EntityConverter.register(definition, @schema_registry)
86
+ register_schema_files(definition)
87
+ end
88
+ end
89
+
90
+ def register_schema_files(definition)
91
+ case definition
92
+ when Hash
93
+ return if EntityConverter.grape_entity?(definition[:model])
94
+
95
+ @schema_registry.register_file(definition[:schema]) if definition[:schema]
96
+ when Array then definition.each { |item| register_schema_files(item) }
84
97
  end
85
98
  end
86
99
 
@@ -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,65 +82,85 @@ 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
+ def extract_failure_responses
108
+ explicit_entries = Array(@route.http_codes).filter_map { |entry| failure_entry(entry) }
109
+ defined_status_codes = explicit_entries.filter_map { |entry| entry[:code]&.to_i }
110
+ inferred_entries = infer_failure_codes.reject { |entry| defined_status_codes.include?(entry[:code]) }
111
+
112
+ (explicit_entries + inferred_entries).each { |entry| add_failure_response(entry) }
113
+ end
114
+
115
+ # The entity is registered here, not with the success entities in
116
+ # PathConverter, because only here is it known whether a response
117
+ # references it: registering it otherwise would leave an unused
118
+ # component.
119
+ def add_failure_response(entry)
120
+ status_code = entry[:code]
121
+ description = entry[:message] || http_status_text(status_code)
122
+ model = entry[:model]
123
+
124
+ if entity_content?(status_code, model)
125
+ EntityConverter.register(model, @schema_registry)
126
+ add_response_with_entity(status_code: status_code, description: description, entity_class: model)
107
127
  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
- )
128
+ add_simple_response(status_code: status_code, description: description)
114
129
  end
115
130
  end
116
131
 
117
- def extract_failure_responses
118
- explicit_codes = Array(@route.http_codes)
119
- defined_status_codes = explicit_codes.filter_map { |c| (c.is_a?(Hash) ? c[:code] : c[0])&.to_i }
120
- http_codes = explicit_codes + infer_failure_codes.reject { |c| defined_status_codes.include?(c[:code]) }
132
+ # Whether a failure entry's entity becomes its response's content. Not
133
+ # when the code's response already has content: a success response's,
134
+ # or that of an earlier Array entry for the same code, which is the one
135
+ # Grape presents the error body with. Nor for a 204 or 304, which have
136
+ # no body.
137
+ def entity_content?(status_code, model)
138
+ key = status_code.to_s
121
139
 
122
- http_codes.each do |failure_def|
123
- case failure_def
124
- when Hash
125
- add_simple_response(
126
- status_code: failure_def[:code],
127
- description: failure_def[:message] || http_status_text(failure_def[:code])
128
- )
129
- when Array
130
- add_simple_response(
131
- status_code: failure_def[0],
132
- description: failure_def[1] || http_status_text(failure_def[0])
133
- )
134
- end
140
+ EntityConverter.grape_entity?(model) && !@responses.dig(key, :content) && BODYLESS_STATUS_CODES.exclude?(key)
141
+ end
142
+
143
+ # A failure entry is `[code, message, model]`, the form Grape documents,
144
+ # or `{ code:, message: }`, the form grape-swagger also reads. Grape
145
+ # builds an error body with the model of an Array entry only (it reads
146
+ # `http_code[2]`), so a Hash entry's `model:` is dropped rather than
147
+ # documented as a body Grape does not send. Reading both into the Hash
148
+ # shape gives them one code path.
149
+ def failure_entry(entry)
150
+ case entry
151
+ when Hash then entry.except(:model)
152
+ when Array then { code: entry[0], message: entry[1], model: entry[2] }
135
153
  end
136
154
  end
137
155
 
138
156
  def add_response_with_entity(
139
- status_code:, description:, entity_class:, example: nil, examples: nil, is_array: false)
157
+ status_code:, description:, entity_class: nil, schema_name: nil, example: nil, examples: nil,
158
+ is_array: false)
140
159
  response = Models::Response.new(
141
160
  status_code: status_code,
142
161
  description: description,
143
162
  entity_class: entity_class,
163
+ schema_name: schema_name,
144
164
  example: example,
145
165
  examples: examples,
146
166
  is_array: is_array
@@ -2,33 +2,55 @@
2
2
 
3
3
  module Gitlab
4
4
  module GrapeOpenapi
5
- # Isolates the Grape internals this gem reads so version differences live in
6
- # one place.
7
- #
8
- # Grape < 3.2 stores each declared validation as a Hash; Grape >= 3.2 stores
9
- # a frozen validator instance instead (ruby-grape/grape#2657). Both shapes
10
- # are normalized to the Hash the converters expect.
5
+ # Isolates the Grape internals this gem reads so they live in one place.
11
6
  module GrapeCompat
12
7
  class << self
13
- # Declared validations for a single attribute, newest scope only.
8
+ # Validators declared for a single attribute, newest scope only.
14
9
  def validations_for(route, attribute)
15
- validations = declared_validations(route)
16
- return unless validations
10
+ all_validations(route).select { |validator| validator.attrs.include?(attribute) }
11
+ end
12
+
13
+ # Every validator declared on a route, newest scope only. Unlike
14
+ # `validations_for` this keeps group validators (mutually_exclusive and
15
+ # friends) whose `attrs` span several params.
16
+ def all_validations(route)
17
+ validators = declared_validations(route)
18
+ return [] unless validators
19
+
20
+ # ContractScopeValidator declares no attributes, so it maps to no parameter.
21
+ validators.select { |validator| validator.respond_to?(:attrs) }
22
+ end
17
23
 
18
- validations.filter_map do |validation|
19
- normalized = normalize(validation)
20
- normalized if normalized && normalized[:attributes].include?(attribute)
24
+ # Grape exposes no public reader for a validator's options, and they carry
25
+ # the regexp patterns and Limit maxima this gem needs. Switch to the reader
26
+ # if one is added upstream.
27
+ def options_for(validator)
28
+ validator.instance_variable_get(:@options)
29
+ end
30
+
31
+ # Whether the validators include `allow_blank: false`. Grape omits allow_blank
32
+ # from route.params and keeps it only as an AllowBlankValidator, whose options
33
+ # are either the bare value or a Hash with `:value` and `:message`.
34
+ def blank_disallowed?(validators)
35
+ validator = validators&.find do |candidate|
36
+ candidate.is_a?(Grape::Validations::Validators::AllowBlankValidator)
21
37
  end
38
+ return false unless validator
39
+
40
+ options = options_for(validator)
41
+ value = options.is_a?(Hash) && options.key?(:value) ? options[:value] : options
42
+ value == false
22
43
  end
23
44
 
24
- # Every declared validation for a route, normalized, newest scope only.
25
- # Unlike `validations_for` this keeps group validators (mutually_exclusive
26
- # and friends) whose `:attributes` span several params.
27
- def all_validations(route)
28
- validations = declared_validations(route)
29
- return [] unless validations
45
+ # Full bracketed paths (e.g. "filter[x]") for a validator's attributes, so
46
+ # cross-field constraints in nested scopes are named in full; equal to the
47
+ # bare name at the root. Grape has no public reader for the scope.
48
+ def full_names_for(validator)
49
+ scope = validator.instance_variable_get(:@scope)
30
50
 
31
- validations.filter_map { |validation| normalize(validation) }
51
+ validator.attrs.map do |attribute|
52
+ scope.respond_to?(:full_name) ? scope.full_name(attribute).to_s : attribute.to_s
53
+ end
32
54
  end
33
55
 
34
56
  # The `desc:` an author writes on `route_param`. Grape forwards only `type:` into
@@ -49,53 +71,12 @@ module Gitlab
49
71
 
50
72
  private
51
73
 
52
- # The route's raw, un-normalized validation stack, and the only place this
53
- # gem reaches into Grape for it.
54
- #
55
74
  # Reads `new_values` rather than `[]` or `route[:saved_validations]` on
56
- # purpose: those also include validations inherited from parent scopes,
75
+ # purpose: those also include validators inherited from parent scopes,
57
76
  # which would change the generated output.
58
77
  def declared_validations(route)
59
78
  route.app.inheritable_setting.namespace_stackable.new_values[:validations]
60
79
  end
61
-
62
- def normalize(validation)
63
- if validation.is_a?(Hash) # Grape < 3.2
64
- # Do not mutate the author's own Hash; add the derived key on a copy.
65
- return validation.merge(full_names: full_names_for(validation[:params_scope], validation[:attributes]))
66
- end
67
-
68
- # Grape 3.2's ContractScopeValidator declares no attributes, so it maps
69
- # to no parameter.
70
- return unless validation.respond_to?(:attrs)
71
-
72
- {
73
- attributes: validation.attrs,
74
- validator_class: validation.class,
75
- # Grape 3.2 exposes no public reader for the validator options, which
76
- # carry regexp patterns and limits. Switch to the reader if one is
77
- # added upstream.
78
- options: validation.instance_variable_get(:@options),
79
- opts: { fail_fast: validation.fail_fast? },
80
- # Full bracketed paths (e.g. "filter[x]") for cross-field constraints
81
- # in nested scopes; equal to the bare name at the root. No public
82
- # reader for the scope on 3.2, hence the ivar.
83
- full_names: full_names_for(validation.instance_variable_get(:@scope), validation.attrs)
84
- }
85
- end
86
-
87
- # Maps each attribute to its full bracketed path via the param scope, so a
88
- # nested `x` becomes "filter[x]" while a top-level `x` stays "x". Falls
89
- # back to the bare name if the scope cannot resolve it.
90
- def full_names_for(scope, attributes)
91
- Array(attributes).map do |attribute|
92
- if scope.respond_to?(:full_name)
93
- scope.full_name(attribute).to_s
94
- else
95
- attribute.to_s
96
- end
97
- end
98
- end
99
80
  end
100
81
  end
101
82
  end
@@ -30,7 +30,7 @@ module Gitlab
30
30
  built_schema = build_resolved_schema(object_type, object_format)
31
31
  end
32
32
 
33
- apply_nullability!(built_schema, param_options)
33
+ apply_nullability!(built_schema, param_options, validations: validations)
34
34
  apply_limit!(built_schema, validations)
35
35
  apply_array_enum!(built_schema, param_options[:values])
36
36
  apply_default!(built_schema, param_options[:default])
@@ -208,11 +208,11 @@ module Gitlab
208
208
 
209
209
  # Add regex validations
210
210
  validation = validations&.find do |v|
211
- v[:validator_class] == Grape::Validations::Validators::RegexpValidator
211
+ v.instance_of?(Grape::Validations::Validators::RegexpValidator)
212
212
  end
213
213
 
214
214
  if validation
215
- pattern = regexp_to_pattern(validation[:options])
215
+ pattern = regexp_to_pattern(GrapeCompat.options_for(validation))
216
216
  schema[:pattern] = pattern if pattern
217
217
  end
218
218
 
@@ -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
@@ -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.7.0"
5
+ VERSION = "0.9.0"
6
6
  end
7
7
  end
@@ -1,5 +1,7 @@
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"
@@ -59,6 +61,10 @@ module Gitlab
59
61
  # containing a named parameter (e.g. `/foo(/:a)/bar(/:b)`).
60
62
  MultipleOptionalSegmentsError = Class.new(GenerationError)
61
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
+
62
68
  class << self
63
69
  attr_writer :configuration
64
70
 
metadata CHANGED
@@ -1,35 +1,29 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gitlab-grape-openapi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.0
4
+ version: 0.9.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-10-02 00:00:00.000000000 Z
11
+ date: 2026-11-16 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: grape
15
15
  requirement: !ruby/object:Gem::Requirement
16
16
  requirements:
17
- - - ">="
18
- - !ruby/object:Gem::Version
19
- version: '2.4'
20
- - - "<"
17
+ - - "~>"
21
18
  - !ruby/object:Gem::Version
22
- version: '3.3'
19
+ version: 3.2.0
23
20
  type: :runtime
24
21
  prerelease: false
25
22
  version_requirements: !ruby/object:Gem::Requirement
26
23
  requirements:
27
- - - ">="
28
- - !ruby/object:Gem::Version
29
- version: '2.4'
30
- - - "<"
24
+ - - "~>"
31
25
  - !ruby/object:Gem::Version
32
- version: '3.3'
26
+ version: 3.2.0
33
27
  - !ruby/object:Gem::Dependency
34
28
  name: grape-entity
35
29
  requirement: !ruby/object:Gem::Requirement