-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathApiSpecification.cs
More file actions
711 lines (607 loc) · 34 KB
/
Copy pathApiSpecification.cs
File metadata and controls
711 lines (607 loc) · 34 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
using Azure.Core;
using Azure.Core.Pipeline;
using Flurl;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi;
using Microsoft.OpenApi.Reader;
using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
namespace common;
public delegate ValueTask<Option<(ApiSpecification Specification, BinaryData Contents)>> GetApiSpecificationFromApim(ResourceKey resourceKey, JsonObject dto, CancellationToken cancellationToken);
public delegate ValueTask<Option<(ApiSpecification Specification, BinaryData Contents)>> GetApiSpecificationFromFile(ResourceKey resourceKey, ReadFile readFile, CancellationToken cancellationToken);
public delegate ValueTask WriteApiSpecificationFile(ResourceKey resourceKey, ApiSpecification specification, BinaryData contents, CancellationToken cancellationToken);
public delegate ValueTask PutApiSpecificationInApim(ResourceKey resourceKey, JsonObject baseDto, ApiSpecification specification, BinaryData contents, CancellationToken cancellationToken);
public abstract record ApiSpecification
{
public sealed record GraphQl : ApiSpecification
{
private GraphQl() { }
public static GraphQl Instance { get; } = new();
}
public sealed record Wadl : ApiSpecification
{
private Wadl() { }
public static Wadl Instance { get; } = new();
}
public sealed record Wsdl : ApiSpecification
{
private Wsdl() { }
public static Wsdl Instance { get; } = new();
}
public sealed record OpenApi : ApiSpecification
{
public required OpenApiFormat Format { get; init; }
public required OpenApiVersion Version { get; init; }
}
}
public abstract record OpenApiFormat
{
public sealed record Json : OpenApiFormat
{
private Json() { }
public static Json Instance { get; } = new();
}
public sealed record Yaml : OpenApiFormat
{
private Yaml() { }
public static Yaml Instance { get; } = new();
}
}
public abstract record OpenApiVersion
{
public sealed record V2 : OpenApiVersion
{
private V2() { }
public static V2 Instance { get; } = new();
}
public sealed record V3 : OpenApiVersion
{
private V3() { }
public static V3 Instance { get; } = new();
}
}
public static partial class ResourceModule
{
private static readonly ImmutableArray<ApiSpecification> specifications = [
ApiSpecification.GraphQl.Instance,
ApiSpecification.Wsdl.Instance,
ApiSpecification.Wadl.Instance,
new ApiSpecification.OpenApi { Format = OpenApiFormat.Json.Instance, Version = OpenApiVersion.V2.Instance },
new ApiSpecification.OpenApi { Format = OpenApiFormat.Yaml.Instance, Version = OpenApiVersion.V2.Instance },
new ApiSpecification.OpenApi { Format = OpenApiFormat.Json.Instance, Version = OpenApiVersion.V3.Instance },
new ApiSpecification.OpenApi { Format = OpenApiFormat.Yaml.Instance, Version = OpenApiVersion.V3.Instance }
];
public static void ConfigureGetApiSpecificationFromApim(IHostApplicationBuilder builder)
{
ManagementServiceModule.ConfigureServiceUri(builder);
AzureModule.ConfigureHttpPipeline(builder);
ConfigureGetOptionalResourceDtoFromApim(builder);
builder.TryAddSingleton(ResolveGetApiSpecificationFromApim);
}
private static GetApiSpecificationFromApim ResolveGetApiSpecificationFromApim(IServiceProvider provider)
{
var serviceUri = provider.GetRequiredService<ServiceUri>();
var getOptionalDto = provider.GetRequiredService<GetOptionalResourceDtoFromApim>();
var pipeline = provider.GetRequiredService<HttpPipeline>();
var configuration = provider.GetRequiredService<IConfiguration>();
var throttler = new ConcurrentDictionary<string, SemaphoreSlim>();
return async (resourceKey, dto, cancellationToken) =>
{
var (resource, name, parents) = (resourceKey.Resource, resourceKey.Name, resourceKey.Parents);
if (resource is not ApiResource and not WorkspaceApiResource)
{
return Option.None;
}
var specificationOption = getSpecification(resource, dto);
return await specificationOption.BindTask(async specification =>
{
// APIM has an issue where concurrent requests with the same version set always return the same specification.
// If apiA and apiB share a version set, and we request their specification simultaneously, the same specification
// file is returned (even if they have different specifications).
// We throttle concurrent requests with the same version set ID to avoid this issue.
var versionSetIdOption =
dto.GetJsonObjectProperty("properties")
.Bind(properties => properties.GetStringProperty("apiVersionSetId"))
.Map(ResourceModule.SetAbsoluteToRelativeId)
.ToOption();
var throttlerKeyOption = versionSetIdOption;
// APIM has an issue where concurrent requests with the same root API always return the current revision's specification.
// If we request the specification for apiA (current) and apiA;rev=3 (non-current) simultaneously, apiA's specification
// is returned in both instances. We throttle concurrent requests with the same root name to avoid this issue.
var throttlerKey = throttlerKeyOption.IfNone(() => ApiRevisionModule.GetRootName(name).ToString());
var semaphore = throttler.GetOrAdd(throttlerKey, _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync(cancellationToken);
try
{
return from contents in await getSpecificationContents(resourceKey, specification, cancellationToken)
select (specification, contents);
}
finally
{
semaphore.Release();
}
});
};
Option<ApiSpecification> getSpecification(IResource resource, JsonObject dtoJson)
{
var apiType = string.Empty;
var serializerOptions = ((IResourceWithDto)resource).SerializerOptions;
switch (resource)
{
case ApiResource:
apiType = JsonNodeModule.To<ApiDto>(dtoJson, serializerOptions)
.IfErrorThrow()
.Properties.Type;
break;
case WorkspaceApiResource:
apiType = JsonNodeModule.To<WorkspaceApiDto>(dtoJson, serializerOptions)
.IfErrorThrow()
.Properties.Type;
break;
}
return apiType switch
{
null => Option.Some(getDefaultSpecification()),
var value when "http".Equals(value, StringComparison.OrdinalIgnoreCase) => Option.Some(getDefaultSpecification()),
var value when "graphql".Equals(value, StringComparison.OrdinalIgnoreCase) => Option<ApiSpecification>.Some(ApiSpecification.GraphQl.Instance),
var value when "soap".Equals(value, StringComparison.OrdinalIgnoreCase) => Option<ApiSpecification>.Some(ApiSpecification.Wsdl.Instance),
_ => Option.None
};
}
ApiSpecification getDefaultSpecification() =>
configuration.GetValue("API_SPECIFICATION_FORMAT")
.IfNone(() => configuration.GetValue("apiSpecificationFormat"))
.Map(format => format switch
{
var value when "Wadl".Equals(value, StringComparison.OrdinalIgnoreCase) =>
ApiSpecification.Wadl.Instance as ApiSpecification,
var value when "JSON".Equals(value, StringComparison.OrdinalIgnoreCase) =>
new ApiSpecification.OpenApi
{
Format = OpenApiFormat.Json.Instance,
Version = OpenApiVersion.V3.Instance
},
var value when "YAML".Equals(value, StringComparison.OrdinalIgnoreCase) =>
new ApiSpecification.OpenApi
{
Format = OpenApiFormat.Yaml.Instance,
Version = OpenApiVersion.V3.Instance
},
var value when "OpenApiV2Json".Equals(value, StringComparison.OrdinalIgnoreCase) =>
new ApiSpecification.OpenApi
{
Format = OpenApiFormat.Json.Instance,
Version = OpenApiVersion.V2.Instance
},
var value when "OpenApiV2Yaml".Equals(value, StringComparison.OrdinalIgnoreCase) =>
new ApiSpecification.OpenApi
{
Format = OpenApiFormat.Yaml.Instance,
Version = OpenApiVersion.V2.Instance
},
var value when "OpenApiV3Json".Equals(value, StringComparison.OrdinalIgnoreCase) =>
new ApiSpecification.OpenApi
{
Format = OpenApiFormat.Json.Instance,
Version = OpenApiVersion.V3.Instance
},
var value when "OpenApiV3Yaml".Equals(value, StringComparison.OrdinalIgnoreCase) =>
new ApiSpecification.OpenApi
{
Format = OpenApiFormat.Yaml.Instance,
Version = OpenApiVersion.V3.Instance
},
var value =>
throw new NotSupportedException($"API specification format '{value}' defined in configuration is not supported.")
})
.IfNone(() => new ApiSpecification.OpenApi
{
Format = OpenApiFormat.Yaml.Instance,
Version = OpenApiVersion.V3.Instance
});
async ValueTask<Option<BinaryData>> getSpecificationContents(ResourceKey resourceKey, ApiSpecification specification, CancellationToken cancellationToken)
{
var (resource, name, parents) = (resourceKey.Resource, resourceKey.Name, resourceKey.Parents);
switch (specification)
{
case ApiSpecification.GraphQl:
return await getGraphQlSpecificationContents(resourceKey, cancellationToken);
default:
// Get a link to download the specification
var exportUri = resource.GetUri(name, parents, serviceUri)
.SetQueryParam("format", specification switch
{
ApiSpecification.Wsdl => "wsdl-link",
ApiSpecification.Wadl => "wadl-link",
ApiSpecification.OpenApi openApi when openApi.Version is OpenApiVersion.V2 => "swagger-link",
ApiSpecification.OpenApi openApi when openApi.Format is OpenApiFormat.Json => "openapi+json-link",
ApiSpecification.OpenApi openApi when openApi.Format is OpenApiFormat.Yaml => "openapi-link",
_ => throw new InvalidOperationException($"Specification {specification} is not supported.")
})
.SetQueryParam("export", true)
.ToUri();
var downloadUriResult = from exportResult in await pipeline.GetContent(exportUri, cancellationToken)
from exportJson in JsonObjectModule.From(exportResult)
from value in resource switch
{
ApiResource => exportJson.GetJsonObjectProperty("value"),
WorkspaceApiResource => from properties in exportJson.GetJsonObjectProperty("properties")
from value in properties.GetJsonObjectProperty("value")
select value,
_ => throw new InvalidOperationException($"Resource '{resourceKey.Resource}' does not support API specifications.")
}
from link in value.GetStringProperty("link")
select new Uri(link);
var downloadUri = downloadUriResult.IfErrorThrow();
// The link does not support authentication, so use an unauthenticated pipeline.
var unauthenticatedPipeline = HttpPipelineBuilder.Build(ClientOptions.Default);
var contentResult = await unauthenticatedPipeline.GetContent(downloadUri, cancellationToken);
var content = contentResult.IfErrorThrow();
// APIM always exports Open API v2 to JSON. Convert to YAML if needed.
if (specification is ApiSpecification.OpenApi openApi2
&& openApi2.Version is OpenApiVersion.V2
&& openApi2.Format is not OpenApiFormat.Json)
{
content = await convertOpenApiContent(content, openApi2.Format, openApi2.Version, cancellationToken);
}
return content;
}
}
async ValueTask<Option<BinaryData>> getGraphQlSpecificationContents(ResourceKey resourceKey, CancellationToken cancellationToken)
{
var (resource, name, parents) = (resourceKey.Resource, resourceKey.Name, resourceKey.Parents);
var schemaName = ResourceName.From("graphql").IfErrorThrow();
IResourceWithDto schemaResource = resource switch
{
ApiResource => ApiSchemaResource.Instance,
WorkspaceApiResource => WorkspaceApiSchemaResource.Instance,
_ => throw new InvalidOperationException($"Getting schema for {resourceKey} is not supported.")
};
var serializerOptions = schemaResource.SerializerOptions;
var schemaAncestors = parents.Append(resource, name);
return from dto in await getOptionalDto(schemaResource, schemaName, schemaAncestors, cancellationToken)
let result = from dtoObject in JsonNodeModule.To<ApiSchemaDto>(dto, serializerOptions)
select dtoObject.Properties.Document?.Value
from contents in result.ToOption()
where string.IsNullOrWhiteSpace(contents) is false
select BinaryData.FromString(contents);
}
static async ValueTask<BinaryData> convertOpenApiContent(BinaryData content, OpenApiFormat targetFormat, OpenApiVersion targetVersion, CancellationToken cancellationToken)
{
using var stream = content.ToStream();
var settings = GetOpenApiReaderSettings();
var (document, diagnostic) = await OpenApiDocument.LoadAsync(stream, settings: settings, cancellationToken: cancellationToken);
if (document is null || diagnostic is null || diagnostic.Errors.Count > 0)
{
throw new InvalidOperationException($"Downloaded Open API specification is invalid: {string.Join(", ", diagnostic?.Errors.Select(e => e.Message) ?? [])}");
}
switch (targetFormat, targetVersion)
{
case (OpenApiFormat.Json, OpenApiVersion.V2) when diagnostic.Format is "json" && diagnostic.SpecificationVersion is OpenApiSpecVersion.OpenApi2_0:
{
return content;
}
case (OpenApiFormat.Json, OpenApiVersion.V2):
{
var newContentString = await document.SerializeAsJsonAsync(OpenApiSpecVersion.OpenApi2_0, cancellationToken);
return BinaryData.FromString(newContentString);
}
case (OpenApiFormat.Json, OpenApiVersion.V3) when diagnostic.Format is "json" && (diagnostic.SpecificationVersion is OpenApiSpecVersion.OpenApi3_0 or OpenApiSpecVersion.OpenApi3_1):
{
return content;
}
case (OpenApiFormat.Json, OpenApiVersion.V3):
{
var newContentString = await document.SerializeAsJsonAsync(OpenApiSpecVersion.OpenApi3_1, cancellationToken);
return BinaryData.FromString(newContentString);
}
case (OpenApiFormat.Yaml, OpenApiVersion.V2) when diagnostic.Format is "yaml" && diagnostic.SpecificationVersion is OpenApiSpecVersion.OpenApi2_0:
{
return content;
}
case (OpenApiFormat.Yaml, OpenApiVersion.V2):
{
var newContentString = await document.SerializeAsYamlAsync(OpenApiSpecVersion.OpenApi2_0, cancellationToken);
return BinaryData.FromString(newContentString);
}
case (OpenApiFormat.Yaml, OpenApiVersion.V3) when diagnostic.Format is "yaml" && (diagnostic.SpecificationVersion is OpenApiSpecVersion.OpenApi3_0 or OpenApiSpecVersion.OpenApi3_1):
{
return content;
}
case (OpenApiFormat.Yaml, OpenApiVersion.V3):
{
var newContentString = await document.SerializeAsYamlAsync(OpenApiSpecVersion.OpenApi3_1, cancellationToken);
return BinaryData.FromString(newContentString);
}
default:
throw new InvalidOperationException($"Conversion to Open API specification {targetFormat} {targetVersion} is not supported.");
}
}
}
public static void ConfigureGetApiSpecificationFromFile(IHostApplicationBuilder builder)
{
ManagementServiceModule.ConfigureServiceDirectory(builder);
builder.TryAddSingleton(ResolveGetApiSpecificationFromFile);
}
private static GetApiSpecificationFromFile ResolveGetApiSpecificationFromFile(IServiceProvider provider)
{
var serviceDirectory = provider.GetRequiredService<ServiceDirectory>();
return async (resourceKey, readFile, cancellationToken) =>
await specifications.Choose(specification => GetSpecificationFile(resourceKey, specification, serviceDirectory))
.Choose(async file => await getSpecification(file, readFile, cancellationToken))
.Head(cancellationToken);
static async ValueTask<Option<(ApiSpecification Specification, BinaryData Contents)>> getSpecification(FileInfo file, ReadFile readFile, CancellationToken cancellationToken)
{
var contentsOption = await readFile(file, cancellationToken);
return await contentsOption.BindTask(async contents => Path.GetExtension(file.FullName)
.ToLowerInvariant() switch
{
".json" or ".yaml" or ".yml" => from specification in await GetOpenApiSpecification(contents, file, cancellationToken)
select ((ApiSpecification)specification, contents),
".graphql" => (ApiSpecification.GraphQl.Instance, contents),
".wadl" => (ApiSpecification.Wadl.Instance, contents),
".wsdl" => (ApiSpecification.Wsdl.Instance, contents),
_ => Option.None,
});
}
}
private static Option<FileInfo> GetSpecificationFile(ResourceKey resourceKey, ApiSpecification specification, ServiceDirectory serviceDirectory)
{
var (resource, name, parents) = (resourceKey.Resource, resourceKey.Name, resourceKey.Parents);
if (resource is not IResourceWithDirectory resourceWithDirectory)
{
return Option.None;
}
if (resource is not (ApiResource or WorkspaceApiResource))
{
return Option.None;
}
var specificationFileName = GetSpecificationFileName(specification);
return resourceWithDirectory.GetCollectionDirectoryInfo(parents, serviceDirectory)
.GetChildDirectory(name.ToString())
.GetChildFile(specificationFileName);
}
private static string GetSpecificationFileName(ApiSpecification specification) =>
$"specification.{specification switch
{
ApiSpecification.GraphQl => "graphql",
ApiSpecification.Wsdl => "wsdl",
ApiSpecification.Wadl => "wadl",
ApiSpecification.OpenApi openApi when openApi.Format is OpenApiFormat.Json => "json",
ApiSpecification.OpenApi openApi when openApi.Format is OpenApiFormat.Yaml => "yaml",
_ => throw new InvalidOperationException($"Specification {specification} is not supported.")
}}";
private static async ValueTask<Option<ApiSpecification.OpenApi>> GetOpenApiSpecification(BinaryData contents, FileInfo file, CancellationToken cancellationToken)
{
using var stream = contents.ToStream();
var settings = GetOpenApiReaderSettings();
OpenApiDiagnostic? diagnostic = null;
try
{
(_, diagnostic) = await OpenApiDocument.LoadAsync(stream, settings: settings, cancellationToken: cancellationToken);
}
catch (Exception exception) when (exception is InvalidOperationException or NotSupportedException)
{
throw new InvalidOperationException($"Loading specification file '{file.FullName}' failed with error '{exception.Message}'.", exception);
}
return diagnostic switch
{
null => Option.None,
{ Errors: [] } =>
from format in diagnostic.Format switch
{
"json" => Option<OpenApiFormat>.Some(OpenApiFormat.Json.Instance),
"yaml" => OpenApiFormat.Yaml.Instance,
_ => Option.None
}
from version in diagnostic.SpecificationVersion switch
{
OpenApiSpecVersion.OpenApi2_0 => Option<OpenApiVersion>.Some(OpenApiVersion.V2.Instance),
OpenApiSpecVersion.OpenApi3_1 => OpenApiVersion.V3.Instance,
OpenApiSpecVersion.OpenApi3_0 => OpenApiVersion.V3.Instance,
_ => Option.None
}
select new ApiSpecification.OpenApi
{
Format = format,
Version = version
},
{ Errors: var errors } =>
throw new InvalidOperationException($"Specification file '{file.FullName}' is not a valid OpenAPI document.",
errors switch
{
[var singleError] => openApiErrorToException(singleError),
var multipleErrors => new AggregateException(multipleErrors.Select(openApiErrorToException))
})
};
static InvalidOperationException openApiErrorToException(OpenApiError error) =>
string.IsNullOrWhiteSpace(error.Pointer)
? new InvalidOperationException(error.Message)
: new InvalidOperationException($"Pointer: '{error.Pointer}'. Message: '{error.Message}'");
}
private static OpenApiReaderSettings GetOpenApiReaderSettings()
{
var settings = new OpenApiReaderSettings
{
RuleSet = ValidationRuleSet.GetEmptyRuleSet()
};
settings.AddJsonReader();
settings.AddYamlReader();
return settings;
}
public static void ConfigureWriteApiSpecificationFile(IHostApplicationBuilder builder)
{
ManagementServiceModule.ConfigureServiceDirectory(builder);
builder.TryAddSingleton(ResolveWriteApiSpecificationFile);
}
private static WriteApiSpecificationFile ResolveWriteApiSpecificationFile(IServiceProvider provider)
{
var serviceDirectory = provider.GetRequiredService<ServiceDirectory>();
return async (resourceKey, specification, contents, cancellationToken) =>
{
var fileOption = GetSpecificationFile(resourceKey, specification, serviceDirectory);
await fileOption.IterTask(async file => await file.OverwriteWithBinaryData(contents, cancellationToken));
};
}
public static void ConfigurePutApiSpecificationInApim(IHostApplicationBuilder builder)
{
ManagementServiceModule.ConfigureServiceUri(builder);
AzureModule.ConfigureHttpPipeline(builder);
ConfigureGetResourceDtoFromApim(builder);
ConfigurePutResourceInApim(builder);
builder.TryAddSingleton(ResolvePutApiSpecificationInApim);
}
private static PutApiSpecificationInApim ResolvePutApiSpecificationInApim(IServiceProvider provider)
{
var serviceUri = provider.GetRequiredService<ServiceUri>();
var pipeline = provider.GetRequiredService<HttpPipeline>();
var getDto = provider.GetRequiredService<GetResourceDtoFromApim>();
var putResource = provider.GetRequiredService<PutResourceInApim>();
var resource = ApiResource.Instance;
var ancestors = ParentChain.Empty;
return async (resourceKey, baseDto, specification, contents, cancellationToken) =>
{
if (resourceKey.Resource is not ApiResource and not WorkspaceApiResource)
{
throw new InvalidOperationException($"Resource '{resourceKey.Resource}' does not support API specifications.");
}
await (specification switch
{
ApiSpecification.OpenApi openApiSpecification => putOpenApiSpecification(resourceKey, baseDto, openApiSpecification, contents, cancellationToken),
ApiSpecification.Wadl wadlSpecification => putWadlSpecification(resourceKey, wadlSpecification, contents, cancellationToken),
ApiSpecification.Wsdl wsdlSpecification => putWsdlSpecification(resourceKey, wsdlSpecification, contents, cancellationToken),
ApiSpecification.GraphQl graphQlSpecification => putGraphQlSpecification(resourceKey, graphQlSpecification, contents, cancellationToken),
_ => throw new InvalidOperationException($"Specification {specification} is not supported.")
});
};
async ValueTask putOpenApiSpecification(ResourceKey resourceKey, JsonObject baseDto, ApiSpecification.OpenApi specification, BinaryData contents, CancellationToken cancellationToken)
{
var dto = baseDto.DeepClone().AsObject();
dto = dto.MergeWith(new JsonObject
{
["properties"] = new JsonObject
{
["format"] = (specification.Format, specification.Version) switch
{
(OpenApiFormat.Json, OpenApiVersion.V2) => "swagger-json",
(OpenApiFormat.Yaml, OpenApiVersion.V2) => "openapi",
(OpenApiFormat.Json, OpenApiVersion.V3) => "openapi+json",
(OpenApiFormat.Yaml, OpenApiVersion.V3) => "openapi",
_ => throw new InvalidOperationException($"Specification {specification} is not supported.")
},
["value"] = contents.ToString()
}
}, mutateOriginal: true);
await putSpecificationDto(resourceKey, dto, useImportQueryParameter: false, cancellationToken);
}
async ValueTask putSpecificationDto(ResourceKey resourceKey, JsonObject dto, bool useImportQueryParameter, CancellationToken cancellationToken)
{
var (resource, name, parents) = (resourceKey.Resource, resourceKey.Name, resourceKey.Parents);
var uri = resource.GetUri(name, parents, serviceUri);
if (useImportQueryParameter)
{
uri = uri.AppendQueryParam("import", true)
.ToUri();
}
var result = await pipeline.PutJson(uri, dto, cancellationToken);
result.IfErrorThrow();
}
async ValueTask putWadlSpecification(ResourceKey resourceKey, ApiSpecification.Wadl specification, BinaryData contents, CancellationToken cancellationToken)
{
var dto = new JsonObject
{
["properties"] = new JsonObject
{
["format"] = "wadl-xml",
["value"] = contents.ToString()
}
};
await putSpecificationDto(resourceKey, dto, useImportQueryParameter: true, cancellationToken);
}
async ValueTask putWsdlSpecification(ResourceKey resourceKey, ApiSpecification.Wsdl specification, BinaryData contents, CancellationToken cancellationToken)
{
// WSDL specification import removes the original description. Save the description.
var resource = (IResourceWithDto)resourceKey.Resource;
var originalDto = await getDto(resource, resourceKey.Name, resourceKey.Parents, cancellationToken);
var descriptionResult = from properties in originalDto.GetJsonObjectProperty("properties")
from description in properties.GetStringProperty("description")
select description;
// Import the specification
var dto = new JsonObject
{
["properties"] = new JsonObject
{
["format"] = "wsdl",
["value"] = contents.ToString(),
["apiType"] = "soap"
}
};
await putSpecificationDto(resourceKey, dto, useImportQueryParameter: true, cancellationToken);
// Re-apply the original description
await descriptionResult.IterTask(async description =>
{
if (ApiRevisionModule.IsRootName(resourceKey.Name) is false)
{
return;
}
var newDto = await getDto(resource, resourceKey.Name, resourceKey.Parents, cancellationToken);
newDto.GetJsonObjectProperty("properties")
.Iter(propertiesJson => propertiesJson["description"] = description);
await putResource(resource, resourceKey.Name, newDto, resourceKey.Parents, cancellationToken);
});
}
async ValueTask putGraphQlSpecification(ResourceKey resourceKey, ApiSpecification.GraphQl specification, BinaryData contents, CancellationToken cancellationToken)
{
IResourceWithDto schemaResource;
ParentChain schemaAncestors;
if (resourceKey.Resource is ApiResource apiResource)
{
schemaResource = ApiSchemaResource.Instance;
schemaAncestors = ParentChain.From([(apiResource, resourceKey.Name)]);
}
else if (resourceKey.Resource is WorkspaceApiResource workspaceApiResource)
{
schemaResource = WorkspaceApiSchemaResource.Instance;
schemaAncestors = ParentChain.From([(workspaceApiResource, resourceKey.Name)]);
}
else
{
throw new InvalidOperationException($"Resource '{resourceKey.Resource}' does not support GraphQL specifications.");
}
var schemaName = ResourceName.From("graphql").IfErrorThrow();
var schemaDto = new JsonObject
{
["properties"] = new JsonObject
{
["contentType"] = "application/vnd.ms-azure-apim.graphql.schema",
["document"] = new JsonObject
{
["value"] = contents.ToString()
}
}
};
await putResource(schemaResource, schemaName, schemaDto, schemaAncestors, cancellationToken);
}
}
private static Option<(ResourceName Name, ParentChain Ancestors)> ParseSpecificationFile(this ApiResource resource, FileInfo? file, ServiceDirectory serviceDirectory)
{
if (file is null)
{
return Option.None;
}
var specificationFileNames = specifications.Select(GetSpecificationFileName);
if (specificationFileNames.Contains(file.Name) is false)
{
return Option.None;
}
return resource.ParseDirectory(file.Directory, serviceDirectory);
}
}