-
-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathJsonApiActionDescriptorCollectionProvider.cs
More file actions
509 lines (420 loc) · 22.1 KB
/
JsonApiActionDescriptorCollectionProvider.cs
File metadata and controls
509 lines (420 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
102
103
104
105
106
107
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
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
315
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
348
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
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
441
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
using System.Collections.Concurrent;
using System.Net;
using System.Reflection;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Controllers;
using JsonApiDotNetCore.Errors;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.OpenApi.Swashbuckle.JsonApiMetadata;
using JsonApiDotNetCore.OpenApi.Swashbuckle.JsonApiMetadata.ActionMethods;
using JsonApiDotNetCore.OpenApi.Swashbuckle.JsonApiMetadata.Documents;
using JsonApiDotNetCore.OpenApi.Swashbuckle.JsonApiObjects.Documents;
using JsonApiDotNetCore.Resources.Annotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
namespace JsonApiDotNetCore.OpenApi.Swashbuckle;
/// <summary>
/// Adds OpenAPI metadata (consumes, produces) to <see cref="ActionDescriptor" />s and performs endpoint expansion for secondary and relationship
/// endpoints. For example: <code><![CDATA[
/// /article/{id}/{relationshipName} -> /article/{id}/author, /article/{id}/revisions, etc.
/// ]]></code>
/// </summary>
internal sealed class JsonApiActionDescriptorCollectionProvider : IActionDescriptorCollectionProvider
{
private const int FilterScope = 10;
private static readonly Type ErrorDocumentType = typeof(ErrorResponseDocument);
private static readonly ConsumesMediaTypeCollection RegularMediaTypes = new([
JsonApiMediaType.Default,
OpenApiMediaTypes.OpenApi,
#pragma warning disable CS0618 // Type or member is obsolete
OpenApiMediaTypes.RelaxedOpenApi
#pragma warning restore CS0618 // Type or member is obsolete
]);
private static readonly ConsumesMediaTypeCollection OperationsMediaTypes = new([
JsonApiMediaType.AtomicOperations,
OpenApiMediaTypes.AtomicOperationsWithOpenApi,
#pragma warning disable CS0618 // Type or member is obsolete
JsonApiMediaType.RelaxedAtomicOperations,
OpenApiMediaTypes.RelaxedAtomicOperationsWithRelaxedOpenApi
#pragma warning restore CS0618 // Type or member is obsolete
]);
private readonly IActionDescriptorCollectionProvider _defaultProvider;
private readonly IControllerResourceMapping _controllerResourceMapping;
private readonly JsonApiEndpointMetadataProvider _jsonApiEndpointMetadataProvider;
private readonly ConcurrentDictionary<int, Lazy<ActionDescriptorCollection>> _versionedActionDescriptorCache = new();
public ActionDescriptorCollection ActionDescriptors =>
_versionedActionDescriptorCache.GetOrAdd(_defaultProvider.ActionDescriptors.Version, LazyGetActionDescriptors).Value;
public JsonApiActionDescriptorCollectionProvider(IActionDescriptorCollectionProvider defaultProvider, IControllerResourceMapping controllerResourceMapping,
JsonApiEndpointMetadataProvider jsonApiEndpointMetadataProvider)
{
ArgumentNullException.ThrowIfNull(defaultProvider);
ArgumentNullException.ThrowIfNull(controllerResourceMapping);
ArgumentNullException.ThrowIfNull(jsonApiEndpointMetadataProvider);
_defaultProvider = defaultProvider;
_controllerResourceMapping = controllerResourceMapping;
_jsonApiEndpointMetadataProvider = jsonApiEndpointMetadataProvider;
}
private Lazy<ActionDescriptorCollection> LazyGetActionDescriptors(int version)
{
// https://andrewlock.net/making-getoradd-on-concurrentdictionary-thread-safe-using-lazy/
return new Lazy<ActionDescriptorCollection>(() => GetActionDescriptors(version), LazyThreadSafetyMode.ExecutionAndPublication);
}
private ActionDescriptorCollection GetActionDescriptors(int version)
{
List<ActionDescriptor> descriptors = [];
foreach (ActionDescriptor descriptor in _defaultProvider.ActionDescriptors.Items)
{
if (!descriptor.EndpointMetadata.OfType<IHttpMethodMetadata>().SelectMany(metadata => metadata.HttpMethods).Any())
{
// Technically incorrect: when no verbs, the endpoint is exposed on all verbs. But Swashbuckle hides it anyway.
continue;
}
var actionMethod = JsonApiActionMethod.TryCreate(descriptor);
if (actionMethod != null)
{
if (!IsVisibleEndpoint(descriptor))
{
continue;
}
ResourceType? resourceType = _controllerResourceMapping.GetResourceTypeForController(actionMethod.ControllerType);
if (actionMethod is BuiltinResourceActionMethod builtinResourceActionMethod)
{
ConsistencyGuard.ThrowIf(resourceType == null);
if (ShouldSuppressEndpoint(builtinResourceActionMethod.Endpoint, resourceType))
{
continue;
}
}
ActionDescriptor[] replacementDescriptors = SetEndpointMetadata(descriptor);
descriptors.AddRange(replacementDescriptors);
continue;
}
descriptors.Add(descriptor);
}
return new ActionDescriptorCollection(descriptors.AsReadOnly(), version);
}
internal static bool IsVisibleEndpoint(ActionDescriptor descriptor)
{
// Only if in a convention ApiExplorer.IsVisible was set to false, the ApiDescriptionActionData will not be present.
return descriptor is ControllerActionDescriptor controllerDescriptor && controllerDescriptor.Properties.ContainsKey(typeof(ApiDescriptionActionData));
}
private static bool ShouldSuppressEndpoint(JsonApiEndpoints endpoint, ResourceType resourceType)
{
if (!IsEndpointAvailable(endpoint, resourceType))
{
return true;
}
if (IsSecondaryOrRelationshipEndpoint(endpoint))
{
if (resourceType.Relationships.Count == 0)
{
return true;
}
if (endpoint is JsonApiEndpoints.DeleteRelationship or JsonApiEndpoints.PostRelationship)
{
return !resourceType.Relationships.OfType<HasManyAttribute>().Any();
}
}
return false;
}
private static bool IsEndpointAvailable(JsonApiEndpoints endpoint, ResourceType resourceType)
{
JsonApiEndpoints availableEndpoints = GetGeneratedControllerEndpoints(resourceType);
if (availableEndpoints == JsonApiEndpoints.None)
{
// Auto-generated controllers are disabled, so we can't know what to hide.
// It is assumed that a handwritten JSON:API controller only provides action methods for what it supports.
// To accomplish that, derive from BaseJsonApiController instead of JsonApiController.
return true;
}
// For an overridden JSON:API action method in a partial class to show up, it's flag must be turned on in [Resource].
// Otherwise, it is considered to be an action method that throws because the endpoint is unavailable.
return IncludesEndpoint(endpoint, availableEndpoints);
}
private static JsonApiEndpoints GetGeneratedControllerEndpoints(ResourceType resourceType)
{
var resourceAttribute = resourceType.ClrType.GetCustomAttribute<ResourceAttribute>();
return resourceAttribute?.GenerateControllerEndpoints ?? JsonApiEndpoints.None;
}
private static bool IncludesEndpoint(JsonApiEndpoints endpoint, JsonApiEndpoints availableEndpoints)
{
bool? isIncluded = null;
if (endpoint == JsonApiEndpoints.GetCollection)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.GetCollection);
}
else if (endpoint == JsonApiEndpoints.GetSingle)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.GetSingle);
}
else if (endpoint == JsonApiEndpoints.GetSecondary)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.GetSecondary);
}
else if (endpoint == JsonApiEndpoints.GetRelationship)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.GetRelationship);
}
else if (endpoint == JsonApiEndpoints.Post)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.Post);
}
else if (endpoint == JsonApiEndpoints.PostRelationship)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.PostRelationship);
}
else if (endpoint == JsonApiEndpoints.Patch)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.Patch);
}
else if (endpoint == JsonApiEndpoints.PatchRelationship)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.PatchRelationship);
}
else if (endpoint == JsonApiEndpoints.Delete)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.Delete);
}
else if (endpoint == JsonApiEndpoints.DeleteRelationship)
{
isIncluded = availableEndpoints.HasFlag(JsonApiEndpoints.DeleteRelationship);
}
ConsistencyGuard.ThrowIf(isIncluded == null);
return isIncluded.Value;
}
private static bool IsSecondaryOrRelationshipEndpoint(JsonApiEndpoints endpoint)
{
return endpoint is JsonApiEndpoints.GetSecondary or JsonApiEndpoints.GetRelationship or JsonApiEndpoints.PostRelationship or
JsonApiEndpoints.PatchRelationship or JsonApiEndpoints.DeleteRelationship;
}
private ActionDescriptor[] SetEndpointMetadata(ActionDescriptor descriptor)
{
Dictionary<RelationshipAttribute, ActionDescriptor> descriptorsByRelationship = [];
bool isNonPrimaryEndpoint = false;
JsonApiEndpointMetadata endpointMetadata = _jsonApiEndpointMetadataProvider.Get(descriptor);
switch (endpointMetadata.RequestMetadata)
{
case AtomicOperationsRequestMetadata atomicOperationsRequestMetadata:
{
SetConsumes(descriptor, atomicOperationsRequestMetadata.DocumentType, OperationsMediaTypes);
UpdateRequestBodyParameterDescriptor(descriptor, atomicOperationsRequestMetadata.DocumentType, null);
break;
}
case PrimaryRequestMetadata primaryRequestMetadata:
{
SetConsumes(descriptor, primaryRequestMetadata.DocumentType, RegularMediaTypes);
UpdateRequestBodyParameterDescriptor(descriptor, primaryRequestMetadata.DocumentType, null);
break;
}
case RelationshipRequestMetadata relationshipRequestMetadata:
{
ConsistencyGuard.ThrowIf(descriptor.AttributeRouteInfo == null);
isNonPrimaryEndpoint = true;
foreach ((RelationshipAttribute relationship, Type documentType) in relationshipRequestMetadata.DocumentTypesByRelationship)
{
ActionDescriptor relationshipDescriptor = Clone(descriptor);
RemovePathParameter(relationshipDescriptor.Parameters, "relationshipName");
ExpandTemplate(relationshipDescriptor.AttributeRouteInfo!, relationship.PublicName);
SetConsumes(descriptor, documentType, RegularMediaTypes);
UpdateRequestBodyParameterDescriptor(relationshipDescriptor, documentType, relationship.PublicName);
descriptorsByRelationship[relationship] = relationshipDescriptor;
}
break;
}
}
switch (endpointMetadata.ResponseMetadata)
{
case AtomicOperationsResponseMetadata atomicOperationsResponseMetadata:
{
SetProduces(descriptor, atomicOperationsResponseMetadata.DocumentType);
SetProducesResponseTypes(descriptor, atomicOperationsResponseMetadata.DocumentType, atomicOperationsResponseMetadata.SuccessStatusCodes,
atomicOperationsResponseMetadata.ErrorStatusCodes);
break;
}
case PrimaryResponseMetadata primaryResponseMetadata:
{
SetProduces(descriptor, primaryResponseMetadata.DocumentType);
SetProducesResponseTypes(descriptor, primaryResponseMetadata.DocumentType, primaryResponseMetadata.SuccessStatusCodes,
primaryResponseMetadata.ErrorStatusCodes);
break;
}
case NonPrimaryResponseMetadata nonPrimaryResponseMetadata:
{
isNonPrimaryEndpoint = true;
foreach ((RelationshipAttribute relationship, Type documentType) in nonPrimaryResponseMetadata.DocumentTypesByRelationship)
{
SetNonPrimaryResponseMetadata(descriptor, descriptorsByRelationship, relationship, documentType,
nonPrimaryResponseMetadata.SuccessStatusCodes, nonPrimaryResponseMetadata.ErrorStatusCodes);
}
break;
}
case EmptyRelationshipResponseMetadata emptyRelationshipResponseMetadata:
{
isNonPrimaryEndpoint = true;
foreach (RelationshipAttribute relationship in emptyRelationshipResponseMetadata.Relationships)
{
SetNonPrimaryResponseMetadata(descriptor, descriptorsByRelationship, relationship, null,
emptyRelationshipResponseMetadata.SuccessStatusCodes, emptyRelationshipResponseMetadata.ErrorStatusCodes);
}
break;
}
}
return isNonPrimaryEndpoint ? descriptorsByRelationship.Values.ToArray() : [descriptor];
}
private static void SetConsumes(ActionDescriptor descriptor, Type requestType, ConsumesMediaTypeCollection mediaTypes)
{
RemoveFiltersForRequestBody(descriptor);
if (descriptor is ControllerActionDescriptor controllerActionDescriptor &&
controllerActionDescriptor.MethodInfo.GetCustomAttributes<ConsumesAttribute>().Any())
{
// A custom JSON:API action method with [Consumes] on it. Hide the attribute from Swashbuckle, so it uses our data in API Explorer.
controllerActionDescriptor.MethodInfo = new MethodInfoWrapper(controllerActionDescriptor.MethodInfo, [typeof(ConsumesAttribute)]);
}
// These media types don't actually appear in the OpenAPI document, but are used to invoke
// JsonApiRequestFormatMetadataProvider.GetSupportedContentTypes(), which determines the actual request content type.
// We need to pass all possible media types, otherwise ASP.NET Core's content negotiation returns HTTP 415.
var consumesAttribute = new ConsumesAttribute(requestType, mediaTypes.ContentType, mediaTypes.OtherContentTypes);
descriptor.FilterDescriptors.Add(new FilterDescriptor(consumesAttribute, FilterScope));
}
private static void RemoveFiltersForRequestBody(ActionDescriptor descriptor)
{
// Custom action methods that take a request body are expected to be annotated with [Consumes].
// We add the CLR type, so that an IIdentifiable type is lifted to a JSON:API type, which is why the existing annotation must be replaced.
foreach (FilterDescriptor filterDescriptor in descriptor.FilterDescriptors.ToArray())
{
if (filterDescriptor.Filter is ConsumesAttribute)
{
descriptor.FilterDescriptors.Remove(filterDescriptor);
}
}
}
private static void UpdateRequestBodyParameterDescriptor(ActionDescriptor descriptor, Type documentType, string? parameterName)
{
ControllerParameterDescriptor? requestBodyDescriptor = descriptor.GetBodyParameterDescriptor();
if (requestBodyDescriptor == null)
{
MethodInfo? actionMethod = descriptor.TryGetActionMethod();
ConsistencyGuard.ThrowIf(actionMethod == null);
throw new InvalidConfigurationException(
$"The action method '{actionMethod}' on type '{actionMethod.ReflectedType?.FullName}' contains no parameter with a [FromBody] attribute.");
}
descriptor.EndpointMetadata.Add(new ConsumesAttribute(JsonApiMediaType.Default.ToString()));
requestBodyDescriptor.ParameterType = documentType;
requestBodyDescriptor.ParameterInfo = new ParameterInfoWrapper(requestBodyDescriptor.ParameterInfo, documentType, parameterName);
}
private static ActionDescriptor Clone(ActionDescriptor descriptor)
{
ActionDescriptor clone = descriptor.MemberwiseClone();
clone.AttributeRouteInfo = descriptor.AttributeRouteInfo!.MemberwiseClone();
clone.FilterDescriptors = descriptor.FilterDescriptors.Select(Clone).ToList();
clone.Parameters = descriptor.Parameters.Select(parameter => parameter.MemberwiseClone()).ToList();
return clone;
}
private static FilterDescriptor Clone(FilterDescriptor descriptor)
{
IFilterMetadata clone = descriptor.Filter.MemberwiseClone();
return new FilterDescriptor(clone, descriptor.Scope)
{
Order = descriptor.Order
};
}
private static void RemovePathParameter(ICollection<ParameterDescriptor> parameters, string parameterName)
{
ParameterDescriptor descriptor = parameters.Single(parameterDescriptor => parameterDescriptor.Name == parameterName);
parameters.Remove(descriptor);
}
private static void ExpandTemplate(AttributeRouteInfo route, string parameterName)
{
route.Template = route.Template!.Replace("{relationshipName}", parameterName);
}
private static void SetProduces(ActionDescriptor descriptor, Type? documentType)
{
IReadOnlyList<string> contentTypes = OpenApiContentTypeProvider.Instance.GetResponseContentTypes(documentType);
if (contentTypes.Count > 0)
{
descriptor.FilterDescriptors.Add(new FilterDescriptor(new ProducesAttribute(contentTypes[0]), FilterScope));
}
}
private static void SetProducesResponseTypes(ActionDescriptor descriptor, Type? documentType, IReadOnlyCollection<HttpStatusCode> successStatusCodes,
IReadOnlyCollection<HttpStatusCode> errorStatusCodes)
{
foreach (HttpStatusCode statusCode in successStatusCodes.Order())
{
RemoveFiltersForStatusCode(descriptor, statusCode);
descriptor.FilterDescriptors.Add(documentType == null || StatusCodeHasNoResponseBody(statusCode)
? new FilterDescriptor(new ProducesResponseTypeAttribute(typeof(void), (int)statusCode), FilterScope)
: new FilterDescriptor(new ProducesResponseTypeAttribute(documentType, (int)statusCode), FilterScope));
}
string? errorContentType = null;
if (documentType == null)
{
IReadOnlyList<string> errorContentTypes = OpenApiContentTypeProvider.Instance.GetResponseContentTypes(ErrorDocumentType);
ConsistencyGuard.ThrowIf(errorContentTypes.Count == 0);
errorContentType = errorContentTypes[0];
}
foreach (HttpStatusCode statusCode in errorStatusCodes.Order())
{
RemoveFiltersForStatusCode(descriptor, statusCode);
descriptor.FilterDescriptors.Add(errorContentType != null
? new FilterDescriptor(new ProducesResponseTypeAttribute(ErrorDocumentType, (int)statusCode, errorContentType), FilterScope)
: new FilterDescriptor(new ProducesResponseTypeAttribute(ErrorDocumentType, (int)statusCode), FilterScope));
}
}
private static void RemoveFiltersForStatusCode(ActionDescriptor descriptor, HttpStatusCode statusCode)
{
// Custom action methods are expected to be annotated with [ProducesResponseType] to express (1) the return type(s) on success and
// (2) possible error status codes. We add the CLR types, so that IIdentifiable types are lifted to JSON:API types, which is why
// the existing annotations must be replaced.
foreach (FilterDescriptor filterDescriptor in descriptor.FilterDescriptors.ToArray())
{
if (filterDescriptor.Filter is ProducesResponseTypeAttribute produces && produces.StatusCode == (int)statusCode)
{
descriptor.FilterDescriptors.Remove(filterDescriptor);
}
}
}
private static bool StatusCodeHasNoResponseBody(HttpStatusCode statusCode)
{
int value = (int)statusCode;
if (value < 200)
{
return true;
}
if (value is >= 300 and < 400)
{
return true;
}
return statusCode is HttpStatusCode.NoContent or HttpStatusCode.ResetContent;
}
private static void SetNonPrimaryResponseMetadata(ActionDescriptor descriptor,
Dictionary<RelationshipAttribute, ActionDescriptor> descriptorsByRelationship, RelationshipAttribute relationship, Type? documentType,
IReadOnlyCollection<HttpStatusCode> successStatusCodes, IReadOnlyCollection<HttpStatusCode> errorStatusCodes)
{
ConsistencyGuard.ThrowIf(descriptor.AttributeRouteInfo == null);
if (!descriptorsByRelationship.TryGetValue(relationship, out ActionDescriptor? relationshipDescriptor))
{
relationshipDescriptor = Clone(descriptor);
RemovePathParameter(relationshipDescriptor.Parameters, "relationshipName");
}
ExpandTemplate(relationshipDescriptor.AttributeRouteInfo!, relationship.PublicName);
SetProduces(relationshipDescriptor, documentType);
SetProducesResponseTypes(relationshipDescriptor, documentType, successStatusCodes, errorStatusCodes);
descriptorsByRelationship[relationship] = relationshipDescriptor;
}
private sealed class ConsumesMediaTypeCollection
{
public string ContentType { get; }
public string[] OtherContentTypes { get; }
public ConsumesMediaTypeCollection(JsonApiMediaType[] mediaTypes)
{
ArgumentGuard.NotNullNorEmpty(mediaTypes);
ContentType = mediaTypes[0].ToString();
OtherContentTypes = mediaTypes.Skip(1).Select(mediaType => mediaType.ToString()).ToArray();
}
}
}