-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathODataPathProvider.cs
More file actions
1219 lines (1044 loc) · 57.8 KB
/
ODataPathProvider.cs
File metadata and controls
1219 lines (1044 loc) · 57.8 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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Vocabularies;
using Microsoft.OpenApi.OData.Common;
using Microsoft.OpenApi.OData.Vocabulary.Capabilities;
namespace Microsoft.OpenApi.OData.Edm
{
/// <summary>
/// Provide class for <see cref="ODataPath"/> generating.
/// </summary>
public class ODataPathProvider : IODataPathProvider
{
private Dictionary<IEdmEntityType, IList<IEdmNavigationSource>>? _allNavigationSources;
private readonly IDictionary<IEdmEntityType, IList<ODataPath>> _allNavigationSourcePaths =
new Dictionary<IEdmEntityType, IList<ODataPath>>();
private readonly IDictionary<IEdmEntityType, IList<ODataPath>> _allNavigationPropertyPaths =
new Dictionary<IEdmEntityType, IList<ODataPath>>();
private readonly List<ODataPath> _allOperationPaths = [];
private IEdmModel? _model;
private readonly IDictionary<IEdmEntityType, IList<ODataPath>> _dollarCountPaths =
new Dictionary<IEdmEntityType, IList<ODataPath>>();
/// <summary>
/// Can filter the <see cref="IEdmElement"/> or not.
/// </summary>
/// <param name="element">The Edm element.</param>
/// <returns>True/false.</returns>
public virtual bool CanFilter(IEdmElement element) => true;
/// <summary>
/// Generate the list of <see cref="ODataPath"/> based on the given <see cref="IEdmModel"/>.
/// </summary>
/// <param name="model">The Edm model.</param>
/// <param name="settings">The conversion settings.</param>
/// <returns>The collection of built <see cref="ODataPath"/>.</returns>
public virtual IEnumerable<ODataPath> GetPaths(IEdmModel model, OpenApiConvertSettings settings)
{
if (model == null || model.EntityContainer == null)
{
return [];
}
Initialize(model);
if (_model is not null)
{
// entity set
foreach (var entitySet in _model.EntityContainer.EntitySets())
{
if (CanFilter(entitySet))
{
RetrieveNavigationSourcePaths(entitySet, settings);
}
}
// singleton
foreach (var singleton in _model.EntityContainer.Singletons())
{
if (CanFilter(singleton))
{
RetrieveNavigationSourcePaths(singleton, settings);
}
}
}
// bound operations
RetrieveBoundOperationPaths(settings);
if (_model is not null)
{
// unbound operations
foreach (IEdmOperationImport import in _model.EntityContainer.OperationImports())
{
if (CanFilter(import))
{
AppendPath(new ODataPath(new ODataOperationImportSegment(import)));
}
}
}
return MergePaths();
}
/// <summary>
/// Initialize the provider.
/// </summary>
/// <param name="model">The Edm model.</param>
protected virtual void Initialize(IEdmModel model)
{
Utils.CheckArgumentNull(model, nameof(model));
_model = model;
_allNavigationSources = model.LoadAllNavigationSources();
_allNavigationSourcePaths.Clear();
_allNavigationPropertyPaths.Clear();
_allOperationPaths.Clear();
_dollarCountPaths.Clear();
}
private IEnumerable<ODataPath> MergePaths()
{
List<ODataPath> allODataPaths = new();
foreach (var item in _allNavigationSourcePaths.Values)
{
allODataPaths.AddRange(item);
}
foreach (var item in _allNavigationPropertyPaths.Values)
{
allODataPaths.AddRange(item);
}
allODataPaths.AddRange(_allOperationPaths);
allODataPaths.Sort();
return allODataPaths;
}
private void AppendPath(ODataPath path)
{
Utils.CheckArgumentNull(path, nameof(path));
ODataPathKind kind = path.Kind;
switch(kind)
{
case ODataPathKind.ComplexProperty:
case ODataPathKind.TypeCast:
case ODataPathKind.DollarCount:
case ODataPathKind.Entity:
case ODataPathKind.EntitySet:
case ODataPathKind.Singleton:
case ODataPathKind.MediaEntity:
if (path.FirstSegment is ODataNavigationSourceSegment navigationSourceSegment)
{
if(!_allNavigationSourcePaths.TryGetValue(navigationSourceSegment.EntityType, out var nsList))
{
nsList = [];
_allNavigationSourcePaths[navigationSourceSegment.EntityType] = nsList;
}
if (kind == ODataPathKind.DollarCount)
{
if (_allOperationPaths.FirstOrDefault(p => DollarCountAndOperationPathsSimilar(p, path)) is not null)
{
// Don't add a path for $count if a similar count() function path already exists.
return;
}
else
{
if (!_dollarCountPaths.TryGetValue(navigationSourceSegment.EntityType, out var dollarPathList))
{
dollarPathList = [];
_dollarCountPaths[navigationSourceSegment.EntityType] = dollarPathList;
}
dollarPathList.Add(path);
}
}
nsList.Add(path);
}
break;
case ODataPathKind.NavigationProperty:
case ODataPathKind.Ref:
ODataNavigationPropertySegment navigationPropertySegment = path.OfType<ODataNavigationPropertySegment>().Last();
if (!_allNavigationPropertyPaths.TryGetValue(navigationPropertySegment.EntityType, out var npList))
{
npList = [];
_allNavigationPropertyPaths[navigationPropertySegment.EntityType] = npList;
}
npList.Add(path);
break;
case ODataPathKind.Operation:
case ODataPathKind.OperationImport:
if (kind == ODataPathKind.Operation)
{
foreach (var kvp in _dollarCountPaths)
{
if (kvp.Value.FirstOrDefault(p => DollarCountAndOperationPathsSimilar(p, path)) is ODataPath dollarCountPath &&
_allNavigationSourcePaths.TryGetValue(kvp.Key, out var dollarPathList))
{
dollarPathList.Remove(dollarCountPath);
break;
}
}
}
_allOperationPaths.Add(path);
break;
default:
return;
}
bool DollarCountAndOperationPathsSimilar(ODataPath path1, ODataPath path2)
{
if ((path1.Kind == ODataPathKind.DollarCount &&
path2.Kind == ODataPathKind.Operation && Constants.CountSegmentIdentifier.Equals(path2.LastSegment?.Identifier, StringComparison.OrdinalIgnoreCase)) ||
(path2.Kind == ODataPathKind.DollarCount &&
path1.Kind == ODataPathKind.Operation && Constants.CountSegmentIdentifier.Equals(path1.LastSegment?.Identifier, StringComparison.OrdinalIgnoreCase)))
{
return GetModifiedPathItemName(path1)?.Equals(GetModifiedPathItemName(path2), StringComparison.OrdinalIgnoreCase) ?? false;
}
return false;
}
string? GetModifiedPathItemName(ODataPath path)
{
if (path.Count == 0) return null;
IEnumerable<ODataSegment> modifiedSegments = path.Take(path.Count - 1);
ODataPath modifiedPath = new(modifiedSegments);
return modifiedPath.GetPathItemName();
}
}
/// <summary>
/// Retrieve the paths for <see cref="IEdmNavigationSource"/>.
/// </summary>
/// <param name="navigationSource">The navigation source.</param>
/// <param name="convertSettings">The settings for the current conversion.</param>
private void RetrieveNavigationSourcePaths(IEdmNavigationSource navigationSource, OpenApiConvertSettings convertSettings)
{
Utils.CheckArgumentNull(navigationSource, nameof(navigationSource));
Utils.CheckArgumentNull(convertSettings, nameof(convertSettings));
// navigation source itself
ODataPath path = new(new ODataNavigationSourceSegment(navigationSource));
AppendPath(path.Clone());
IEdmEntityType entityType = navigationSource.EntityType;
CountRestrictionsType? count = null;
bool? indexableByKey = false;
var entitySetIsNull = true;
// for entity set, create a path with key and a $count path
if (navigationSource is IEdmEntitySet entitySet && _model is not null)
{
entitySetIsNull = false;
string targetPath = path.GetTargetPath(_model);
count = _model.GetRecord<CountRestrictionsType>(targetPath, CapabilitiesConstants.CountRestrictions)
?? _model.GetRecord<CountRestrictionsType>(entitySet, CapabilitiesConstants.CountRestrictions);
if(count?.Countable ?? true) // ~/entitySet/$count
CreateCountPath(path, convertSettings);
CreateTypeCastPaths(path, convertSettings, entityType, entitySet, true); // ~/entitySet/subType
if (convertSettings.AddAlternateKeyPaths)
CreateAlternateKeyPath(path, entityType); //~/entitySet/{alternateKeyId}
indexableByKey = _model.GetBoolean(targetPath, CapabilitiesConstants.IndexableByKey)
?? _model.GetBoolean(entitySet, CapabilitiesConstants.IndexableByKey);
if (indexableByKey ?? true)
{
path.Push(new ODataKeySegment(entityType)); // ~/entitySet/{id}
AppendPath(path.Clone());
CreateTypeCastPaths(path, convertSettings, entityType, entitySet, false); // ~/entitySet/{id}/subType
}
}
else if (navigationSource is IEdmSingleton singleton)
{ // ~/singleton/subType
CreateTypeCastPaths(path, convertSettings, entityType, singleton, false);
}
// media entity
RetrieveMediaEntityStreamPaths(entityType, path);
// properties of type complex
RetrieveComplexPropertyPaths(entityType, path, convertSettings);
// navigation property
foreach (IEdmNavigationProperty np in entityType.NavigationProperties())
{
if (CanFilter(np))
{
RetrieveNavigationPropertyPaths(np, count, path, convertSettings);
}
}
if (!entitySetIsNull && (indexableByKey ?? true))
{
path.Pop(); // end of entity
}
path.Pop(); // end of navigation source.
Debug.Assert(path.Count == 0);
}
/// <summary>
/// Retrieves the paths for properties of type complex type from entities
/// </summary>
/// <param name="entityType">The entity type.</param>
/// <param name="currentPath">The current path.</param>
/// <param name="convertSettings">The settings for the current conversion.</param>
private void RetrieveComplexPropertyPaths(IEdmEntityType entityType, ODataPath currentPath, OpenApiConvertSettings convertSettings)
{
Utils.CheckArgumentNull(entityType, nameof(entityType));
Utils.CheckArgumentNull(currentPath, nameof(currentPath));
Utils.CheckArgumentNull(convertSettings, nameof(convertSettings));
if (!convertSettings.EnableNavigationPropertyPath || _model is null) return;
foreach (IEdmStructuralProperty sp in entityType.StructuralProperties()
.Where(x => x.Type.IsComplex() ||
x.Type.IsCollection() && x.Type.Definition.AsElementType() is IEdmComplexType))
{
currentPath.Push(new ODataComplexPropertySegment(sp));
var targetPath = currentPath.GetTargetPath(_model);
if (!ShouldCreateComplexPropertyPaths(sp, targetPath, convertSettings))
{
currentPath.Pop();
continue;
}
AppendPath(currentPath.Clone());
if (sp.Type.IsCollection() && sp.Type.Definition.AsElementType() is IEdmComplexType elemType)
{
CreateTypeCastPaths(currentPath, convertSettings, elemType, sp, true);
var isCountable = _model.GetRecord<CountRestrictionsType>(targetPath, CapabilitiesConstants.CountRestrictions)?.IsCountable
?? _model.GetRecord<CountRestrictionsType>(sp, CapabilitiesConstants.CountRestrictions)?.IsCountable
?? true;
if (isCountable)
CreateCountPath(currentPath, convertSettings);
}
else
{
var complexType = sp.Type.AsComplex().ComplexDefinition();
CreateTypeCastPaths(currentPath, convertSettings, complexType, sp, false);
// Append navigation property paths for this complex property
RetrieveComplexTypeNavigationPropertyPaths(complexType, currentPath, convertSettings);
// Traverse this complex property to retrieve nested navigation property paths
TraverseComplexProperty(sp, currentPath, convertSettings);
}
currentPath.Pop();
}
}
/// <summary>
/// Retrieves navigation property paths for complex types.
/// </summary>
/// <param name="complexType">The target complex type.</param>
/// <param name="currentPath">The current path.</param>
/// <param name="convertSettings">The convert settings.</param>
private bool RetrieveComplexTypeNavigationPropertyPaths(IEdmComplexType complexType, ODataPath currentPath, OpenApiConvertSettings convertSettings)
{
Utils.CheckArgumentNull(complexType, nameof(complexType));
Utils.CheckArgumentNull(currentPath, nameof(currentPath));
Utils.CheckArgumentNull(convertSettings, nameof(convertSettings));
var navigationProperties = complexType
.DeclaredNavigationProperties()
.Union(complexType
.FindAllBaseTypes()
.SelectMany(x => x.DeclaredNavigationProperties()))
.Distinct()
.Where(CanFilter);
if (!navigationProperties.Any() || _model is null) return false;
foreach (var np in navigationProperties)
{
var targetPath = currentPath.GetTargetPath(_model);
var count = _model.GetRecord<CountRestrictionsType>(targetPath, CapabilitiesConstants.CountRestrictions)
?? _model.GetRecord<CountRestrictionsType>(np, CapabilitiesConstants.CountRestrictions);
RetrieveNavigationPropertyPaths(np, count, currentPath, convertSettings);
}
return true;
}
/// <summary>
/// Traverses a complex property to generate navigation property paths within nested complex properties.
/// </summary>
/// <param name="structuralProperty">The target complex property.</param>
/// <param name="currentPath">The current path.</param>
/// <param name="convertSettings">The convert settings.</param>
private void TraverseComplexProperty(IEdmStructuralProperty structuralProperty, ODataPath currentPath, OpenApiConvertSettings convertSettings)
{
Utils.CheckArgumentNull(structuralProperty, nameof(structuralProperty));
Utils.CheckArgumentNull(currentPath, nameof(currentPath));
Utils.CheckArgumentNull(convertSettings, nameof(convertSettings));
var complexType = structuralProperty.Type.AsComplex().ComplexDefinition();
Debug.Assert(complexType != null);
foreach (IEdmStructuralProperty sp in complexType.DeclaredStructuralProperties()
.Where(x => x.Type.IsComplex() ||
x.Type.IsCollection() && x.Type.Definition.AsElementType() is IEdmComplexType))
{
currentPath.Push(new ODataComplexPropertySegment(sp));
var spComplexType = sp.Type.AsComplex().ComplexDefinition();
if (!RetrieveComplexTypeNavigationPropertyPaths(spComplexType, currentPath, convertSettings))
{
TraverseComplexProperty(sp, currentPath, convertSettings);
}
currentPath.Pop();
}
}
/// <summary>
/// Evaluates whether or not to create paths for complex properties.
/// </summary>
/// <param name="complexProperty">The target complex property.</param>
/// <param name="targetPath">The annotation target path for the complex property.</param>
/// <param name="convertSettings">The settings for the current conversion.</param>
/// <returns>true or false.</returns>
private bool ShouldCreateComplexPropertyPaths(IEdmStructuralProperty complexProperty, string targetPath, OpenApiConvertSettings convertSettings)
{
Utils.CheckArgumentNull(complexProperty, nameof(complexProperty));
Utils.CheckArgumentNull(convertSettings, nameof(convertSettings));
if (!convertSettings.RequireRestrictionAnnotationsToGenerateComplexPropertyPaths)
return true;
bool isReadable = _model?.GetRecord<ReadRestrictionsType>(targetPath, CapabilitiesConstants.ReadRestrictions)?.Readable
?? _model?.GetRecord<ReadRestrictionsType>(complexProperty, CapabilitiesConstants.ReadRestrictions)?.Readable
?? false;
bool isUpdatable = _model?.GetRecord<UpdateRestrictionsType>(targetPath, CapabilitiesConstants.UpdateRestrictions)?.Updatable
??_model?.GetRecord<UpdateRestrictionsType>(complexProperty, CapabilitiesConstants.UpdateRestrictions)?.Updatable
?? false;
bool isInsertable = _model?.GetRecord<InsertRestrictionsType>(targetPath, CapabilitiesConstants.InsertRestrictions)?.Insertable
?? _model?.GetRecord<InsertRestrictionsType>(complexProperty, CapabilitiesConstants.InsertRestrictions)?.Insertable
?? false;
return isReadable || isUpdatable || isInsertable;
}
/// <summary>
/// Retrieves the paths for a media entity stream.
/// </summary>
/// <param name="entityType">The entity type.</param>
/// <param name="currentPath">The current OData path.</param>
private void RetrieveMediaEntityStreamPaths(IEdmEntityType entityType, ODataPath currentPath)
{
Utils.CheckArgumentNull(entityType, nameof(entityType));
Utils.CheckArgumentNull(currentPath, nameof(currentPath));
bool createValuePath = true;
foreach (IEdmStructuralProperty sp in entityType.StructuralProperties())
{
if (sp.Type.AsPrimitive().IsStream())
{
currentPath.Push(new ODataStreamPropertySegment(sp.Name));
AppendPath(currentPath.Clone());
currentPath.Pop();
}
if (sp.Name.Equals(Constants.Content, StringComparison.OrdinalIgnoreCase))
{
createValuePath = false;
}
}
/* Append a $value segment only if entity (or base type) has stream and
* does not contain a structural property named Content
*/
if (createValuePath && (entityType.HasStream || ((entityType.BaseType as IEdmEntityType)?.HasStream ?? false)))
{
currentPath.Push(new ODataStreamContentSegment());
AppendPath(currentPath.Clone());
currentPath.Pop();
}
}
/// <summary>
/// Retrieve the path for <see cref="IEdmNavigationProperty"/>.
/// </summary>
/// <param name="navigationProperty">The navigation property.</param>
/// <param name="count">The count restrictions.</param>
/// <param name="currentPath">The current OData path.</param>
/// <param name="convertSettings">The settings for the current conversion.</param>
/// <param name="visitedNavigationProperties">A stack that holds the visited navigation properties in the <paramref name="currentPath"/>.</param>
private void RetrieveNavigationPropertyPaths(
IEdmNavigationProperty navigationProperty,
CountRestrictionsType? count,
ODataPath currentPath,
OpenApiConvertSettings convertSettings,
Stack<string>? visitedNavigationProperties = null)
{
Utils.CheckArgumentNull(navigationProperty, nameof(navigationProperty));
Utils.CheckArgumentNull(currentPath, nameof(currentPath));
Utils.CheckArgumentNull(convertSettings, nameof(convertSettings));
if (visitedNavigationProperties == null)
{
visitedNavigationProperties = new();
}
string navPropFullyQualifiedName = $"{navigationProperty.DeclaringType.FullTypeName()}/{navigationProperty.Name}";
// Check whether the navigation property has already been navigated in the path.
if (visitedNavigationProperties.Contains(navPropFullyQualifiedName))
{
return;
}
// Get the annotatable navigation source for this navigation property.
NavigationRestrictionsType? navSourceRestrictionType = null;
NavigationRestrictionsType? navPropRestrictionType = null;
// Get the NavigationRestrictions referenced by this navigation property: Can be defined in the navigation source or in-lined in the navigation property.
if (currentPath.FirstSegment is ODataNavigationSourceSegment { NavigationSource: IEdmVocabularyAnnotatable annotatableNavigationSource } && _model is not null)
{
navSourceRestrictionType = _model.GetRecord<NavigationRestrictionsType>(annotatableNavigationSource, CapabilitiesConstants.NavigationRestrictions);
navPropRestrictionType = _model.GetRecord<NavigationRestrictionsType>(navigationProperty, CapabilitiesConstants.NavigationRestrictions);
}
NavigationPropertyRestriction? restriction = navSourceRestrictionType?.RestrictedProperties?
.FirstOrDefault(r => r.NavigationProperty == currentPath.NavigationPropertyPath(navigationProperty.Name))
?? navPropRestrictionType?.RestrictedProperties?.FirstOrDefault();
// Check whether the navigation property should be part of the path
if (!EdmModelHelper.NavigationRestrictionsAllowsNavigability(navSourceRestrictionType, restriction) ||
!EdmModelHelper.NavigationRestrictionsAllowsNavigability(navPropRestrictionType, restriction))
{
return;
}
// Whether to expand the navigation property.
bool shouldExpand = navigationProperty.ContainsTarget;
// Append a navigation property.
currentPath.Push(new ODataNavigationPropertySegment(navigationProperty));
AppendPath(currentPath.Clone());
visitedNavigationProperties.Push(navPropFullyQualifiedName);
// For fetching annotations
var targetPath = _model is null ? null : currentPath.GetTargetPath(_model);
// Check whether a collection-valued navigation property should be indexed by key value(s).
// Find indexability annotation annotated directly via NavigationPropertyRestriction.
bool? annotatedIndexability = (string.IsNullOrEmpty(targetPath) ? null : _model?.GetBoolean(targetPath, CapabilitiesConstants.IndexableByKey))
?? _model?.GetBoolean(navigationProperty, CapabilitiesConstants.IndexableByKey);
bool indexableByKey = restriction?.IndexableByKey ?? annotatedIndexability ?? true;
if (indexableByKey)
{
IEdmEntityType navEntityType = navigationProperty.ToEntityType();
var targetsMany = navigationProperty.TargetMultiplicity() == EdmMultiplicity.Many;
if (targetsMany)
{
bool? createCountPath = null;
if (count == null)
{
// First, get the directly annotated restriction annotation of the navigation property
count = (string.IsNullOrEmpty(targetPath) ? null : _model?.GetRecord<CountRestrictionsType>(targetPath, CapabilitiesConstants.CountRestrictions))
?? _model?.GetRecord<CountRestrictionsType>(navigationProperty, CapabilitiesConstants.CountRestrictions);
createCountPath = count?.Countable;
}
var propertyPath = navigationProperty.GetPartnerPath()?.Path;
createCountPath ??= string.IsNullOrEmpty(propertyPath)
|| (count?.IsNonCountableNavigationProperty(propertyPath) ?? true);
if (createCountPath.Value)
{
// ~/entityset/{key}/collection-valued-Nav/$count
CreateCountPath(currentPath, convertSettings);
}
}
// ~/entityset/{key}/collection-valued-Nav/subtype
// ~/entityset/{key}/single-valued-Nav/subtype
CreateTypeCastPaths(currentPath, convertSettings, navEntityType, navigationProperty, targetsMany);
if ((navSourceRestrictionType?.Referenceable ?? false) ||
(navPropRestrictionType?.Referenceable ?? false))
{
// Referenceable navigation properties
// Single-Valued: ~/entityset/{key}/single-valued-Nav/$ref
// Collection-valued: ~/entityset/{key}/collection-valued-Nav/$ref?$id='{navKey}'
CreateRefPath(currentPath);
if (targetsMany)
{
// Collection-valued: DELETE ~/entityset/{key}/collection-valued-Nav/{key}/$ref
currentPath.Push(new ODataKeySegment(navEntityType));
CreateRefPath(currentPath);
CreateTypeCastPaths(currentPath, convertSettings, navEntityType, navigationProperty, false); // ~/entityset/{key}/collection-valued-Nav/{id}/subtype
}
// Get possible stream paths for the navigation entity type
RetrieveMediaEntityStreamPaths(navEntityType, currentPath);
// Get the paths for the navigation property entity type properties of type complex
RetrieveComplexPropertyPaths(navEntityType, currentPath, convertSettings);
}
else
{
// append a navigation property key.
if (targetsMany)
{
CreateAlternateKeyPath(currentPath, navEntityType);
currentPath.Push(new ODataKeySegment(navEntityType));
AppendPath(currentPath.Clone());
CreateTypeCastPaths(currentPath, convertSettings, navEntityType, navigationProperty, false); // ~/entityset/{key}/collection-valued-Nav/{id}/subtype
}
// Get possible stream paths for the navigation entity type
RetrieveMediaEntityStreamPaths(navEntityType, currentPath);
// Get the paths for the navigation property entity type properties of type complex
RetrieveComplexPropertyPaths(navEntityType, currentPath, convertSettings);
if (shouldExpand)
{
// expand to sub navigation properties
foreach (IEdmNavigationProperty subNavProperty in navEntityType.NavigationProperties())
{
if (CanFilter(subNavProperty))
{
RetrieveNavigationPropertyPaths(subNavProperty, count, currentPath, convertSettings, visitedNavigationProperties);
}
}
}
}
if (targetsMany)
{
currentPath.Pop();
}
}
currentPath.Pop();
visitedNavigationProperties.Pop();
}
/// <summary>
/// Create $ref paths.
/// </summary>
/// <param name="currentPath">The current OData path.</param>
private void CreateRefPath(ODataPath currentPath)
{
Utils.CheckArgumentNull(currentPath, nameof(currentPath));
ODataPath newPath = currentPath.Clone();
newPath.Push(ODataRefSegment.Instance); // $ref
AppendPath(newPath);
}
/// <summary>
/// Create $count paths.
/// </summary>
/// <param name="currentPath">The current OData path.</param>
/// <param name="convertSettings">The settings for the current conversion.</param>
private void CreateCountPath(ODataPath currentPath, OpenApiConvertSettings convertSettings)
{
Utils.CheckArgumentNull(currentPath, nameof(currentPath));
Utils.CheckArgumentNull(convertSettings, nameof(convertSettings));
if(!convertSettings.EnableDollarCountPath)
return;
var countPath = currentPath.Clone();
countPath.Push(ODataDollarCountSegment.Instance);
AppendPath(countPath);
}
/// <summary>
/// Create path with alternate key
/// </summary>
/// <param name="currentPath">The current OData path.</param>
/// <param name="entityType">The entityType with alternate keys</param>
private void CreateAlternateKeyPath(ODataPath currentPath, IEdmEntityType entityType)
{
Utils.CheckArgumentNull(currentPath, nameof(currentPath));
Utils.CheckArgumentNull(entityType, nameof(entityType));
IEnumerable<IDictionary<string, IEdmProperty>> alternateKeys = _model.GetAlternateKeysAnnotation(entityType);
foreach (var keyDict in alternateKeys)
{
if (keyDict.Where(static x => x.Value is not null).ToDictionary(static k => k.Key, static v => v.Value.Name) is not { Count: > 0 } keyMappings)
continue;
ODataPath keyPath = currentPath.Clone();
ODataKeySegment keySegment = new(entityType, keyMappings)
{
IsAlternateKey = true
};
keyPath.Push(keySegment);
AppendPath(keyPath);
}
}
/// <summary>
/// Create OData type cast paths.
/// </summary>
/// <param name="currentPath">The current OData path.</param>
/// <param name="convertSettings">The settings for the current conversion.</param>
/// <param name="structuredType">The type that is being inherited from to which this method will add downcast path segments.</param>
/// <param name="annotable">The annotable navigation source to read cast annotations from.</param>
/// <param name="targetsMany">Whether the annotable navigation source targets many entities.</param>
private void CreateTypeCastPaths(ODataPath currentPath, OpenApiConvertSettings convertSettings, IEdmStructuredType structuredType, IEdmVocabularyAnnotatable annotable, bool targetsMany)
{
Utils.CheckArgumentNull(currentPath, nameof(currentPath));
Utils.CheckArgumentNull(convertSettings, nameof(convertSettings));
Utils.CheckArgumentNull(structuredType, nameof(structuredType));
Utils.CheckArgumentNull(annotable, nameof(annotable));
if(!convertSettings.EnableODataTypeCast)
return;
var annotedTypeNames = GetDerivedTypeConstraintTypeNames(annotable);
if(!annotedTypeNames.Any() && convertSettings.RequireDerivedTypesConstraintForODataTypeCastSegments)
return; // we don't want to generate any downcast path item if there is no type cast annotation.
bool filter(IEdmStructuredType x) =>
convertSettings.RequireDerivedTypesConstraintForODataTypeCastSegments && annotedTypeNames.Contains(x.FullTypeName()) ||
!convertSettings.RequireDerivedTypesConstraintForODataTypeCastSegments && (
!annotedTypeNames.Any() ||
annotedTypeNames.Contains(x.FullTypeName())
);
var targetTypes = _model
?.FindAllDerivedTypes(structuredType)
.Where(x => (x.TypeKind == EdmTypeKind.Entity || x.TypeKind == EdmTypeKind.Complex) && filter(x))
.OfType<IEdmStructuredType>()
.ToArray();
if (targetTypes is not { Length: > 0} || _model is null) return;
foreach (var targetType in targetTypes)
{
var targetTypeSegment = new ODataTypeCastSegment(targetType, _model);
if (currentPath.Segments.Any(x => x.Identifier?.Equals(targetTypeSegment.Identifier) ?? false))
{
// In case we have expanded a derived type's navigation property
// and we are in a cyclic loop where the expanded navigation property
// has a derived type that has already been added to the path.
continue;
}
var castPath = currentPath.Clone();
castPath.Push(targetTypeSegment);
AppendPath(castPath);
if (targetsMany)
{
CreateCountPath(castPath, convertSettings);
}
else
{
if (convertSettings.GenerateDerivedTypesProperties)
{
if (annotable is IEdmNavigationProperty navigationProperty && !navigationProperty.ContainsTarget)
{
continue;
}
foreach (var declaredNavigationProperty in targetType.NavigationProperties())
{
RetrieveNavigationPropertyPaths(declaredNavigationProperty, null, castPath, convertSettings);
}
if (targetType is IEdmEntityType entityType)
{
RetrieveComplexPropertyPaths(entityType, castPath, convertSettings);
}
}
}
}
}
/// <summary>
/// Retrieve all bounding <see cref="IEdmOperation"/>.
/// </summary>
private void RetrieveBoundOperationPaths(OpenApiConvertSettings convertSettings)
{
var edmOperations = _model?.GetAllElements().OfType<IEdmOperation>().Where(x => x.IsBound).ToArray() ?? [];
foreach (var edmOperation in edmOperations)
{
if (!CanFilter(edmOperation))
{
continue;
}
IEdmOperationParameter bindingParameter = edmOperation.Parameters.First();
IEdmTypeReference bindingType = bindingParameter.Type;
bool isCollection = bindingType.IsCollection();
if (isCollection)
{
bindingType = bindingType.AsCollection().ElementType();
}
if (!bindingType.IsEntity())
{
continue;
}
var allEntitiesForOperation = GetAllEntitiesForOperation(bindingType);
foreach (var bindingEntityType in allEntitiesForOperation)
{
// 1. Search for corresponding navigation source path
AppendBoundOperationOnNavigationSourcePath(edmOperation, isCollection, bindingEntityType, convertSettings);
// 2. Search for generated navigation property
AppendBoundOperationOnNavigationPropertyPath(edmOperation, isCollection, bindingEntityType);
// 3. Search for derived
AppendBoundOperationOnDerived(edmOperation, isCollection, bindingEntityType, convertSettings);
// 4. Search for derived generated navigation property
AppendBoundOperationOnDerivedNavigationPropertyPath(edmOperation, isCollection, bindingEntityType, convertSettings);
}
}
// all operations appended to properties
// append bound operations to functions
foreach (var edmOperation in edmOperations)
{
if (!CanFilter(edmOperation))
{
continue;
}
IEdmOperationParameter bindingParameter = edmOperation.Parameters.First();
IEdmTypeReference bindingType = bindingParameter.Type;
bool isCollection = bindingType.IsCollection();
if (isCollection)
{
bindingType = bindingType.AsCollection().ElementType();
}
if (!bindingType.IsEntity())
{
continue;
}
var allEntitiesForOperation = GetAllEntitiesForOperation(bindingType);
foreach (var bindingEntityType in allEntitiesForOperation)
{
AppendBoundOperationOnOperationPath(edmOperation, isCollection, bindingEntityType);
}
}
// append navigation properties to functions with return type
var functionPaths = _allOperationPaths.Where(x => x.LastSegment is ODataOperationSegment operationSegment
&& operationSegment.Operation is IEdmFunction edmFunction
&& edmFunction.IsComposable
&& edmFunction.GetReturn()?.Type is { } retType
&& retType.Definition is IEdmEntityType);
foreach( var functionPath in functionPaths)
{
if (functionPath.LastSegment is not ODataOperationSegment operationSegment
|| operationSegment.Operation is not IEdmFunction edmFunction
|| !edmFunction.IsComposable
|| edmFunction.GetReturn()?.Type is not { } retType
|| retType.Definition is not IEdmEntityType returnBindingEntityType)
{
continue;
}
ODataSegment secondLastSeg = functionPath.ElementAt(functionPath.Count - 2);
if (convertSettings.ComposableFunctionsExpansionDepth < 2 &&
functionPath.LastSegment is ODataOperationSegment &&
secondLastSeg is ODataOperationSegment)
{
// Only one level of composable functions expansion allowed
continue;
}
foreach (var navProperty in returnBindingEntityType.NavigationProperties())
{
/* Get number of segments already appended after the first composable function segment
*/
int composableFuncSegIndex = functionPath
.Segments
.OfType<ODataOperationSegment>()
.FirstOrDefault(x => x.Operation is IEdmFunction {IsComposable: true}) is {} firstOperationSegment ?
functionPath.Segments.IndexOf(firstOperationSegment) : -1;
int currentDepth = functionPath.Count - composableFuncSegIndex - 1;
if (currentDepth < convertSettings.ComposableFunctionsExpansionDepth)
{
ODataPath newNavigationPath = functionPath.Clone();
newNavigationPath.Push(new ODataNavigationPropertySegment(navProperty));
AppendPath(newNavigationPath);
}
}
}
}
private List<IEdmEntityType> GetAllEntitiesForOperation(IEdmTypeReference bindingType)
{
var firstEntityType = bindingType.AsEntity().EntityDefinition();
bool filter(IEdmNavigationSource z) =>
z.EntityType != firstEntityType &&
z.EntityType.FindAllBaseTypes().Contains(firstEntityType);
return new IEdmEntityType[] { firstEntityType }
.Union(_model?.EntityContainer.EntitySets()
.Where(filter).Select(x => x.EntityType) ?? []) //Search all EntitySets
.Union(_model?.EntityContainer.Singletons()
.Where(filter).Select(x => x.EntityType) ?? []) //Search all singletons
.Distinct()
.ToList();
}
private static readonly HashSet<ODataPathKind> _oDataPathKindsToSkipForOperationsWhenSingle = new() {
ODataPathKind.EntitySet,
ODataPathKind.MediaEntity,
ODataPathKind.DollarCount,
ODataPathKind.ComplexProperty,
};
private void AppendBoundOperationOnNavigationSourcePath(IEdmOperation edmOperation, bool isCollection, IEdmEntityType bindingEntityType, OpenApiConvertSettings convertSettings)
{
if (_allNavigationSourcePaths.TryGetValue(bindingEntityType, out var value))
{
bool isEscapedFunction = _model?.IsUrlEscapeFunction(edmOperation) ?? false;
foreach (var subPath in value)
{
var lastPathSegment = subPath.LastOrDefault();
var secondLastPathSegment = subPath.Count > 1 ? subPath.ElementAt(subPath.Count - 2) : null;
if (subPath.Kind == ODataPathKind.TypeCast &&
!isCollection &&
secondLastPathSegment != null &&
secondLastPathSegment is not ODataKeySegment &&
(secondLastPathSegment is not ODataNavigationSourceSegment navSource || navSource.NavigationSource is not IEdmSingleton) &&
(secondLastPathSegment is not ODataNavigationPropertySegment navProp || navProp.NavigationProperty.Type.IsCollection()))
{// we don't want to add operations bound to single elements on type cast segments under collections, only under the key segment, singletons and nav props bound to singles.
continue;
}
else if ((lastPathSegment is not ODataTypeCastSegment castSegment ||
castSegment.StructuredType == bindingEntityType ||
bindingEntityType.InheritsFrom(castSegment.StructuredType)) && // we don't want to add operations from the parent types under type cast segments because they already are present without the cast
((isCollection && subPath.Kind == ODataPathKind.EntitySet) ||
(!isCollection && !_oDataPathKindsToSkipForOperationsWhenSingle.Contains(subPath.Kind))))
{
if (lastPathSegment is ODataTypeCastSegment && !convertSettings.AppendBoundOperationsOnDerivedTypeCastSegments) continue;
if (lastPathSegment is ODataKeySegment segment && segment.IsAlternateKey) continue;
var annotatable = (lastPathSegment as ODataNavigationSourceSegment)?.NavigationSource as IEdmVocabularyAnnotatable;
annotatable ??= (lastPathSegment as ODataKeySegment)?.EntityType;
if (annotatable != null && _model is not null && !EdmModelHelper.IsOperationAllowed(_model, edmOperation, annotatable))
{
// Check whether the navigation source is allowed to have an operation on the entity type
annotatable = (secondLastPathSegment as ODataNavigationSourceSegment)?.NavigationSource as IEdmVocabularyAnnotatable;
if (annotatable != null && !EdmModelHelper.IsOperationAllowed(_model, edmOperation, annotatable))
{
continue;
}
}
if (_model is not null)
{
ODataPath newPath = subPath.Clone();
newPath.Push(new ODataOperationSegment(edmOperation, isEscapedFunction, _model));
AppendPath(newPath);
}
}
}
}
}
private static readonly HashSet<ODataPathKind> _pathKindToSkipForNavigationProperties = new () {
ODataPathKind.Ref,
};
private void AppendBoundOperationOnNavigationPropertyPath(IEdmOperation edmOperation, bool isCollection, IEdmEntityType bindingEntityType)
{
bool isEscapedFunction = _model?.IsUrlEscapeFunction(edmOperation) ?? false;
if (_allNavigationPropertyPaths.TryGetValue(bindingEntityType, out var value))