-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathPackageLoader.cs
More file actions
1618 lines (1402 loc) · 61.7 KB
/
PackageLoader.cs
File metadata and controls
1618 lines (1402 loc) · 61.7 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 file="PackageLoader.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// </copyright>
using Hl7.Fhir.Language.Debugging;
using System.Diagnostics;
using System.Net;
using Hl7.Fhir.Model;
using Hl7.Fhir.Utility;
using Microsoft.Health.Fhir.CodeGen.Models;
using Microsoft.Health.Fhir.CodeGenCommon.Packaging;
using Hl7.Fhir.Serialization;
using System.Text.Json;
using Microsoft.Health.Fhir.CodeGen.FhirExtensions;
using Microsoft.Health.Fhir.CodeGenCommon.Models;
using Firely.Fhir.Packages;
using System.Text.RegularExpressions;
using System.Collections.Concurrent;
using System.Xml.Linq;
using Microsoft.Health.Fhir.CodeGen.Configuration;
using System.Linq;
using Microsoft.Health.Fhir.CodeGen._ForPackages;
using Microsoft.Health.Fhir.CodeGen.Utils;
namespace Microsoft.Health.Fhir.CodeGen.Loader;
/// <summary>A package loader.</summary>
public class PackageLoader : IDisposable
{
internal enum VersionHandlingTypes
{
/// <summary>Unprocessed / unknown / SemVer / ranges / etc (pass through).</summary>
Passthrough,
/// <summary>Latest release.</summary>
Latest,
/// <summary>Local build.</summary>
Local,
/// <summary>CI Build.</summary>
ContinuousIntegration,
}
/// <summary>(Immutable) The cache.</summary>
private readonly _ForPackages.DiskPackageCache _cache;
/// <summary>(Immutable) The package clients.</summary>
private readonly List<IPackageServer> _packageClients = [];
private bool _disposedValue = false;
/// <summary>(Immutable) The sorted order for definition types we want to load.</summary>
private static readonly string[] _sortedLoadOrder =
[
"CodeSystem",
"ValueSet",
"StructureDefinition",
"SearchParameter",
"OperationDefinition",
"CapabilityStatement",
"Conformance",
"ImplementationGuide",
"CompartmentDefinition",
];
private ConfigRoot _rootConfiguration;
private FhirReleases.FhirSequenceCodes _defaultFhirVersion;
/// <summary>The JSON model.</summary>
private LoaderOptions.JsonDeserializationModel _jsonModel;
/// <summary>Options for controlling the JSON.</summary>
private JsonSerializerOptions _jsonOptions;
/// <summary>The lenient JSON parser.</summary>
private FhirJsonPocoDeserializer _jsonParser;
#if !DISABLE_XML
/// <summary>The lenient XML parser.</summary>
private FhirXmlPocoDeserializer _xmlParser;
#endif
private Microsoft.Health.Fhir.CrossVersion.Converter_43_50? _converter_43_50 = null;
private Microsoft.Health.Fhir.CrossVersion.Converter_30_50? _converter_30_50 = null;
private Microsoft.Health.Fhir.CrossVersion.Converter_20_50? _converter_20_50 = null;
private object _convertLockObject = new();
/// <summary>Initializes a new instance of the <see cref="PackageLoader"/> class.</summary>
/// <param name="opts"> (Optional) Options for controlling the operation.</param>
public PackageLoader(ConfigRoot? config = null, LoaderOptions? opts = null)
{
// use defaults if nothing was specified
opts ??= new();
_rootConfiguration = config ?? new();
_cache = new(_rootConfiguration.FhirCacheDirectory);
// check if we are using the official registries
if (_rootConfiguration.UseOfficialRegistries == true)
{
_packageClients.Add(PackageClient.Create("https://packages.fhir.org"));
_packageClients.Add(PackageClient.Create("https://packages2.fhir.org/packages"));
_packageClients.Add(new _ForPackages.FhirCiClient(-1));
}
if (_rootConfiguration.AdditionalFhirRegistryUrls.Any())
{
foreach (string url in _rootConfiguration.AdditionalFhirRegistryUrls)
{
_packageClients.Add(PackageClient.Create(url, npm: false));
}
}
if (_rootConfiguration.AdditionalNpmRegistryUrls.Any())
{
foreach (string url in _rootConfiguration.AdditionalNpmRegistryUrls)
{
_packageClients.Add(PackageClient.Create(url, npm: true));
}
}
_defaultFhirVersion = FhirReleases.FhirVersionToSequence(_rootConfiguration.FhirVersion);
_jsonOptions = opts.FhirJsonOptions.UsingMode(DeserializerModes.Ostrich);
_jsonParser = new(opts.FhirJsonSettings);
#if !DISABLE_XML
_xmlParser = new(opts.FhirXmlSettings);
#endif
_jsonModel = opts.JsonModel;
}
/// <summary>Adds all interaction parameters to a core definition collection.</summary>
/// <param name="dc">The device-context.</param>
private void AddAllInteractionParameters(DefinitionCollection dc)
{
dc.AddHttpQueryParameter(new()
{
Name = "_format",
Url = "http://hl7.org/fhir/http.html#format",
Description = "Parameter to specify alternative response formats by their MIME-types.",
ParamType = SearchParamType.String,
});
dc.AddHttpQueryParameter(new()
{
Name = "_summary",
Url = "http://hl7.org/fhir/search.html#summary",
Description = "Request to return a portion of matching resources.",
ParamType = SearchParamType.Token,
AllowedValues = ["true", "false", "count", "data", "text",],
});
dc.AddHttpQueryParameter(new()
{
Name = "_elements",
Url = "http://hl7.org/fhir/search.html#elements",
Description = "Request to return specific elements from resources.",
ParamType = SearchParamType.Token,
});
// add parameters from R4 and later
if (dc.FhirSequence >= FhirReleases.FhirSequenceCodes.R4)
{
dc.AddHttpQueryParameter(new()
{
Name = "_pretty",
Url = "http://hl7.org/fhir/http.html#pretty",
Description = "Ask for a pretty printed response for human convenience.",
ParamType = SearchParamType.String,
AllowedValues = [ "true", "false", ],
});
}
}
/// <summary>Adds a search result parameters to a core definition collection.</summary>
/// <param name="dc">The device-context.</param>
private void AddSearchResultParameters(DefinitionCollection dc)
{
dc.AddSearchResultParameter(new()
{
Name = "_sort",
Url = "http://hl7.org/fhir/search.html#sort",
Description = "Used to indicate which order to return the results, which can have a value of one of the search parameters.",
ParamType = SearchParamType.String,
});
dc.AddSearchResultParameter(new()
{
Name = "_count",
Url = "http://hl7.org/fhir/search.html#count",
Description = "A hint to the server regarding how many resources should be returned in a single page. Servers SHALL NOT return more resources than requested but are allowed to return less than the client requested.",
ParamType = SearchParamType.Number,
});
dc.AddSearchResultParameter(new()
{
Name = "_include",
Url = "http://hl7.org/fhir/search.html#include",
Description = "Request to return resources related to the search results, by moving forward across references.",
ParamType = SearchParamType.String,
});
dc.AddSearchResultParameter(new()
{
Name = "_revinclude",
Url = "http://hl7.org/fhir/search.html#revinclude",
Description = "Request to return resources related to the search results, by moving backwards across references.",
ParamType = SearchParamType.String,
});
dc.AddSearchResultParameter(new()
{
Name = "_contained",
Url = "http://hl7.org/fhir/search.html#contained",
Description = "Request modification to handling of contained resource searching.",
ParamType = SearchParamType.Token,
AllowedValues = [ "true", "false", "both", ],
});
dc.AddSearchResultParameter(new()
{
Name = "_containedType",
Url = "http://hl7.org/fhir/search.html#containedType",
Description = "When contained resources are being returned, whether the server should return either the container or the contained resource.",
ParamType = SearchParamType.Token,
AllowedValues = [ "container", "contained", ],
});
// add parameters from R4 and later
if (dc.FhirSequence >= FhirReleases.FhirSequenceCodes.R4)
{
dc.AddSearchResultParameter(new()
{
Name = "_total",
Url = "http://hl7.org/fhir/search.html#total",
Description = "Optimization hint for servers indicating reliance on the Bundle.total element.",
ParamType = SearchParamType.Token,
AllowedValues = [ "none", "estimate", "accurate" ],
});
}
}
/// <summary>Adds a missing core search parameters to a core definition collection.</summary>
/// <param name="dc">The device-context.</param>
private void AddMissingCoreSearchParameters(DefinitionCollection dc, string packageId, string packageVersion)
{
dc.AddSearchParameter(new()
{
Id = "Resource-content",
Name = "_content",
Code = "_content",
Url = "http://hl7.org/fhir/SearchParameter/Resource-content",
Version = dc.FhirSequence.ToLongVersion(),
Title = "Resource content filter",
Status = PublicationStatus.Active,
Description = "Search on the entire content of the resource.",
Base = [ VersionIndependentResourceTypesAll.Resource ],
Type = SearchParamType.Special,
}, packageId, packageVersion, true);
dc.AddSearchParameter(new()
{
Id = "Resource-filter",
Name = "_filter",
Code = "_filter",
Url = "http://hl7.org/fhir/SearchParameter/Resource-filter",
Version = dc.FhirSequence.ToLongVersion(),
Title = "Advanced search filter",
Status = PublicationStatus.Active,
Description = "Filter search parameter which supports a more sophisticated grammar for searching.",
Base = [ VersionIndependentResourceTypesAll.Resource ],
Type = SearchParamType.Special,
}, packageId, packageVersion, true);
dc.AddSearchParameter(new()
{
Id = "Resource-text",
Name = "_text",
Code = "_text",
Url = "http://hl7.org/fhir/SearchParameter/Resource-text",
Version = dc.FhirSequence.ToLongVersion(),
Title = "Resource text filter",
Status = PublicationStatus.Active,
Description = "Search the narrative content of a resource.",
Base = [ VersionIndependentResourceTypesAll.Resource ],
Type = SearchParamType.String,
}, packageId, packageVersion, true);
dc.AddSearchParameter(new()
{
Id = "Resource-list",
Name = "_list",
Code = "_list",
Url = "http://hl7.org/fhir/SearchParameter/Resource-list",
Version = dc.FhirSequence.ToLongVersion(),
Title = "List reference filter",
Status = PublicationStatus.Active,
Description = "Filter based on resources referenced by a List resource.",
Base = [ VersionIndependentResourceTypesAll.Resource ],
Type = SearchParamType.Reference,
Target = [ VersionIndependentResourceTypesAll.List ],
}, packageId, packageVersion, true);
if (dc.FhirSequence >= FhirReleases.FhirSequenceCodes.R4)
{
dc.AddSearchParameter(new()
{
Id = "Resource-has",
Name = "_has",
Code = "_has",
Url = "http://hl7.org/fhir/SearchParameter/Resource-has",
Version = dc.FhirSequence.ToLongVersion(),
Title = "Limited support for reverse chaining",
Status = PublicationStatus.Active,
Description = "For selecting resources based on the properties of resources that refer to them.",
Base = [ VersionIndependentResourceTypesAll.Resource ],
Type = SearchParamType.Special,
}, packageId, packageVersion, true);
dc.AddSearchParameter(new()
{
Id = "Resource-type",
Name = "_type",
Code = "_type",
Url = "http://hl7.org/fhir/SearchParameter/Resource-type",
Version = dc.FhirSequence.ToLongVersion(),
Title = "Resource type filter",
Status = PublicationStatus.Active,
Description = "For filtering resources based on their type in searches across resource types.",
Base = [ VersionIndependentResourceTypesAll.Resource ],
Type = SearchParamType.Token,
}, packageId, packageVersion, true);
}
}
private VersionHandlingTypes GetVersionHandlingType(string? version)
{
// handle simple literals
switch (version)
{
case null:
case "":
case "latest":
return VersionHandlingTypes.Latest;
case "current":
return VersionHandlingTypes.ContinuousIntegration;
case "dev":
return VersionHandlingTypes.Local;
}
// check for local or current with branch names
if (version.StartsWith("current$", StringComparison.Ordinal))
{
return VersionHandlingTypes.ContinuousIntegration;
}
if (version.StartsWith("dev$", StringComparison.Ordinal))
{
return VersionHandlingTypes.Local;
}
return VersionHandlingTypes.Passthrough;
}
private async ValueTask<(PackageReference, IPackageServer?)> ResolveLatest(string name)
{
List<(PackageReference pr, IPackageServer server)> latestRecs = new();
foreach (IPackageServer server in _packageClients)
{
PackageReference pr = await server.GetLatest(name);
if (pr == PackageReference.None)
{
continue;
}
latestRecs.Add((pr, server));
}
if (latestRecs.Count == 0)
{
return (PackageReference.None, null);
}
return latestRecs.OrderByDescending(v => v.pr.Version).First();
}
/// <summary>
/// Installs a package with the specified package reference.
/// </summary>
/// <param name="packageReference">The package reference.</param>
/// <param name="retries">The number of retries.</param>
/// <returns><c>true</c> if the package is installed successfully; otherwise, <c>false</c>.</returns>
private async Task<bool> InstallPackage(PackageReference packageReference, int retries = 5)
{
Random r = new();
for (int i = 0; i < retries; i++)
{
foreach (IPackageServer pc in _packageClients)
{
try
{
if (packageReference.Scope == FhirCiClient.FhirCiScope)
{
if (pc is not FhirCiClient ciClient)
{
// cannot install CI packages from non-CI clients
continue;
}
await ciClient.InstallOrUpdate(packageReference, _cache);
return true;
}
// try to download this package
byte[] data = await pc.GetPackage(packageReference);
// try to install this package
await _cache.Install(packageReference, data);
// only need to install from first hit
return true;
}
catch (Exception)
{
// ignore
}
}
await System.Threading.Tasks.Task.Delay(500 + (int)(r.NextDouble() * 1000));
}
return false;
}
private void CreateConverterIfRequired(FhirReleases.FhirSequenceCodes fhirSequence)
{
// create the converter we need
switch (fhirSequence)
{
case FhirReleases.FhirSequenceCodes.DSTU2:
{
if (_converter_20_50 == null)
{
lock (_convertLockObject)
{
_converter_20_50 ??= new();
}
}
}
break;
case FhirReleases.FhirSequenceCodes.STU3:
{
if (_converter_30_50 == null)
{
lock (_convertLockObject)
{
_converter_30_50 ??= new();
}
}
}
break;
case FhirReleases.FhirSequenceCodes.R4:
case FhirReleases.FhirSequenceCodes.R4B:
{
if (_converter_43_50 == null)
{
lock (_convertLockObject)
{
_converter_43_50 ??= new();
}
}
}
break;
default:
case FhirReleases.FhirSequenceCodes.R5:
{
}
break;
}
}
private bool LoadFromDirectory(ref DefinitionCollection? definitions, string sourcePath, string? fhirVersion)
{
FhirReleases.FhirSequenceCodes fhirSequence = string.IsNullOrEmpty(fhirVersion)
? _defaultFhirVersion
: FhirReleases.FhirVersionToSequence(fhirVersion!);
if (fhirSequence == FhirReleases.FhirSequenceCodes.Unknown)
{
throw new Exception("Cannot load from a directory with an unknown FHIR version");
}
CreateConverterIfRequired(fhirSequence);
string? name = Path.GetFileName(sourcePath);
if (name == null)
{
throw new Exception($"Failed to get directory name from '{sourcePath}'");
}
string canonical = $"file://{sourcePath}";
definitions ??= new()
{
Name = name,
FhirSequence = fhirSequence,
FhirVersionLiteral = fhirSequence.ToLiteral(),
MainPackageId = name,
MainPackageVersion = "dev",
MainPackageCanonical = canonical,
};
// get files in the directory
string[] files = Directory.GetFiles(sourcePath, "*.json", SearchOption.TopDirectoryOnly);
foreach (string path in files)
{
string fileExtension = Path.GetExtension(path);
object? r;
switch (fhirSequence)
{
case FhirReleases.FhirSequenceCodes.DSTU2:
{
r = ParseContents20(fileExtension, path: path);
}
break;
case FhirReleases.FhirSequenceCodes.STU3:
{
r = ParseContents30(fileExtension, path: path);
}
break;
case FhirReleases.FhirSequenceCodes.R4:
case FhirReleases.FhirSequenceCodes.R4B:
{
r = ParseContents43(fileExtension, path: path);
}
break;
default:
case FhirReleases.FhirSequenceCodes.R5:
{
r = ParseContentsPoco(fileExtension, path);
}
break;
}
if (r == null)
{
throw new Exception($"Failed to parse '{path}'");
}
definitions.AddResource(r, _defaultFhirVersion, name, "dev", canonical);
}
return true;
}
/// <summary>Loads a package.</summary>
/// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
/// <param name="packages"> The cached package.</param>
/// <param name="definitions">(Optional) The definitions.</param>
/// <param name="fhirVersion">(Optional) The FHIR version.</param>
/// <returns>An asynchronous result that yields the package.</returns>
public async Task<DefinitionCollection?> LoadPackages(
IEnumerable<string> packages,
DefinitionCollection? definitions = null,
string? fhirVersion = null)
{
string? requestedFhirVersion = fhirVersion;
if (!packages.Any())
{
return null;
}
using InterProcessSync synchronizationObject = new();
// we need to filter structures post parsing if we are not loading all known types
bool filterStructureDefinitions = !_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.PrimitiveType) ||
!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.ComplexType) ||
!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Resource) ||
!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Extension) ||
!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Profile) ||
!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.LogicalModel) ||
!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Interface);
foreach (string inputDirective in packages)
{
if (string.IsNullOrEmpty(inputDirective))
{
continue;
}
// check to see if this is actually a directory
if ((inputDirective.IndexOfAny(Path.GetInvalidPathChars()) == -1) &&
Directory.Exists(inputDirective))
{
Console.WriteLine($"Processing directory {inputDirective}...");
if (!LoadFromDirectory(ref definitions, inputDirective, fhirVersion))
{
throw new Exception($"Failed to load package from directory: {inputDirective}");
}
// if we loaded from the directory, just continue
continue;
}
// TODO(ginoc): PR in to Parse FHIR-style directives, remove when added.
string directive = inputDirective.Contains('@')
? inputDirective
: inputDirective.Replace('#', '@');
PackageReference packageReference = PackageReference.Parse(directive);
if (packageReference.Name == null)
{
throw new Exception($"Failed to parse package reference: {directive}");
}
// check to see if this is a FHIR release that is no longer available
if (FhirPackageUtils.PackageIsFhirRelease(packageReference.Name) &&
FhirReleases.VersionIsUnavailable(packageReference.Version ?? string.Empty))
{
packageReference.Version = FhirReleases.GetCurrentPatch(packageReference.Version ?? string.Empty);
if (definitions?.Manifests.ContainsKey(packageReference.Moniker) == true)
{
// we have already loaded this package, just continue
continue;
}
}
// create our definition collection shell if we do not have one
if (definitions == null)
{
definitions = new()
{
Name = packageReference.Name,
};
if (!string.IsNullOrEmpty(fhirVersion))
{
definitions.FhirSequence = FhirReleases.FhirVersionToSequence(fhirVersion!);
}
}
Guid? syncHandle = null;
try
{
string sName = "fcg-" + packageReference.Moniker;
(syncHandle, bool _) = await synchronizationObject.TryGetLock(sName);
bool needsInstall = true;
VersionHandlingTypes vht = GetVersionHandlingType(packageReference.Version);
// do special handling for versions if necessary
switch (vht)
{
case VersionHandlingTypes.Latest:
{
// resolve the version via Firely Packages so that we have access to the actual version number
(PackageReference pr, IPackageServer? _) = await ResolveLatest(packageReference.Name);
if ((pr == PackageReference.None) || (pr.Name == null))
{
throw new Exception($"Failed to resolve latest version of {packageReference.Name} ({directive})");
}
packageReference = pr;
needsInstall = !(await _cache.IsInstalled(packageReference));
}
break;
case VersionHandlingTypes.Local:
// ensure there is a local build, there is no other source
{
if (!_cache.IsInstalled(packageReference).Result)
{
throw new Exception($"Local build of {packageReference.Name} is not installed ({directive})");
}
}
break;
case VersionHandlingTypes.ContinuousIntegration:
// always trigger install/update for CI builds
needsInstall = true;
break;
default:
needsInstall = !(await _cache.IsInstalled(packageReference));
break;
}
// check if we are flagged to load expansions and this is a core package
if (_rootConfiguration.AutoLoadExpansions && FhirPackageUtils.PackageIsFhirCore(packageReference.Name))
{
string expansionPackageName = packageReference.Name.Replace(".core", ".expansions");
string expansionDirective = expansionPackageName + "@" + packageReference.Version;
Console.WriteLine($"Auto-loading core expansions: {expansionDirective}...");
await LoadPackages([expansionDirective], definitions, requestedFhirVersion);
}
// skip if we have already loaded this package
if (definitions.Manifests.ContainsKey(packageReference.Moniker))
{
Console.WriteLine($"Skipping already loaded dependency: {packageReference.Moniker}");
continue;
}
Console.WriteLine($"Processing {packageReference.Moniker}...");
// check to see if this package needs to be installed
if (needsInstall &&
(await InstallPackage(packageReference) == false))
{
// failed to install
throw new Exception($"Failed to install package {packageReference.Moniker} as requested by {inputDirective}");
}
}
finally
{
if (syncHandle != null)
{
synchronizationObject.ReleaseLock(syncHandle.Value);
}
}
_ForPackages.PackageManifest manifest = await _cache.ReadManifestEx(packageReference) ?? throw new Exception("Failed to load package manifest");
// check to see if we have a restricted FHIR version and need to filter
if ((!string.IsNullOrEmpty(requestedFhirVersion)) &&
(definitions.FhirSequence != FhirReleases.FhirSequenceCodes.Unknown) &&
(manifest.AnyFhirVersions?.FirstOrDefault() is string manifestFhirVersion) &&
!string.IsNullOrEmpty(manifestFhirVersion) &&
(definitions.FhirSequence != FhirReleases.FhirVersionToSequence(manifestFhirVersion)))
{
Console.WriteLine($"Package {packageReference.Moniker} ({manifestFhirVersion}) does not match requested FHIR version {fhirVersion}!");
string packageIdSuffix = packageReference.Name.Split('.')[^1];
FhirReleases.FhirSequenceCodes packageIdSuffixCode = FhirReleases.FhirVersionToSequence(packageIdSuffix);
// check for NOT having a version already specified
if (packageIdSuffixCode == FhirReleases.FhirSequenceCodes.Unknown)
{
string requiredRLiteral = definitions.FhirSequence.ToRLiteral().ToLowerInvariant();
string desiredMoniker = $"{packageReference.Name}.{requiredRLiteral}@{packageReference.Version}";
await LoadPackages([desiredMoniker], definitions, requestedFhirVersion);
if (definitions.Manifests.ContainsKey(desiredMoniker))
{
Console.WriteLine($"Package {desiredMoniker} loaded in place of {packageReference.Moniker}!");
}
else
{
Console.WriteLine($"Could not find substitute for {packageReference.Moniker} - please specify manually if this is required!");
}
}
else
{
Console.WriteLine($"Package {packageReference.Moniker} specifies an incorrect FHIR version - please correct!");
}
// whether it loaded or not, we cannot do more this pass
continue;
}
//// check to see if this is a different FHIR version from what we expect
//if ((definitions.FhirSequence != FhirReleases.FhirSequenceCodes.Unknown) &&
// (manifest.GetFhirVersion() is string manifestFhirVersion) &&
// !string.IsNullOrEmpty(manifestFhirVersion) &&
// (definitions.FhirSequence != FhirReleases.FhirVersionToSequence(manifestFhirVersion)))
//{
// Console.WriteLine($"Package {packageReference.Moniker} FHIR version mismatch: {manifest?.GetFhirVersion()} != {fhirVersion}, attempting to resolve...");
// string requiredRLiteral = definitions.FhirSequence.ToRLiteral().ToLowerInvariant();
// string desiredMoniker = $"{packageReference.Name}.{requiredRLiteral}@{packageReference.Version}";
// await LoadPackages([desiredMoniker], definitions);
// if (!definitions.Manifests.ContainsKey(desiredMoniker))
// {
// throw new Exception($"Package {packageReference.Moniker} FHIR version mismatch: {manifest?.GetFhirVersion()} != {fhirVersion} and could not be resolved!");
// }
//}
// flag we are tracking this package
definitions.Manifests.Add(packageReference.Moniker, manifest);
if (string.IsNullOrEmpty(definitions.MainPackageId) || (definitions.Name == manifest.Name))
{
definitions.MainPackageId = manifest.Name;
definitions.MainPackageVersion = manifest.Version;
definitions.MainPackageCanonical = manifest.Canonical ?? throw new Exception($"Main package {packageReference.Moniker} manifest does not contain a canonical URL");
}
string? packageFhirVersionLiteral = manifest.AnyFhirVersions?.FirstOrDefault();
// update the collection FHIR version based on the first package we come across with one
if (string.IsNullOrEmpty(definitions.FhirVersionLiteral) && (!string.IsNullOrEmpty(packageFhirVersionLiteral)))
{
definitions.FhirVersionLiteral = packageFhirVersionLiteral!;
definitions.FhirSequence = FhirReleases.FhirVersionToSequence(packageFhirVersionLiteral!);
definitions.FhirVersion = definitions.FhirSequence switch
{
FhirReleases.FhirSequenceCodes.Unknown => null,
FhirReleases.FhirSequenceCodes.DSTU2 => FHIRVersion.N1_0,
FhirReleases.FhirSequenceCodes.STU3 => FHIRVersion.N3_0,
FhirReleases.FhirSequenceCodes.R4 => FHIRVersion.N4_0,
FhirReleases.FhirSequenceCodes.R4B => FHIRVersion.N4_3,
FhirReleases.FhirSequenceCodes.R5 => FHIRVersion.N5_0,
_ => null,
};
}
FhirReleases.FhirSequenceCodes packageFhirVersion = string.IsNullOrEmpty(packageFhirVersionLiteral)
? definitions.FhirSequence
: FhirReleases.FhirVersionToSequence(packageFhirVersionLiteral ?? string.Empty);
CreateConverterIfRequired(definitions.FhirSequence);
// if we are resolving dependencies, check them now
if (_rootConfiguration.ResolvePackageDependencies && (manifest.Dependencies?.Any() ?? false))
{
await LoadPackages(manifest.Dependencies.Select(kvp => $"{kvp.Key}@{kvp.Value}"), definitions, requestedFhirVersion);
Console.WriteLine($"Dependencies resolved - loading package {packageReference.Moniker}...");
}
else
{
Console.WriteLine($"Loading {packageReference.Moniker}...");
}
// grab the contents of our package
CanonicalIndex? packageIndex = await _cache.GetCanonicalIndex(packageReference) ?? throw new Exception("Failed to load package contents");
string packageDirectory = _cache.PackageContentFolder(packageReference);
if (!Directory.Exists(packageDirectory))
{
throw new Exception($"Package directory {packageDirectory} does not exist!");
}
if (string.IsNullOrEmpty(packageDirectory))
{
throw new Exception("Package directory is empty");
}
if (!(packageIndex.Files?.Any() ?? false))
{
throw new Exception("Package contents are empty");
}
string packageRootDirectory = Path.Combine(packageDirectory, "..");
definitions.ContentListings.Add(packageReference.Moniker, packageIndex);
// create an dictionary of indexes we are going to load - note that we are essentially traversing twice, but that is better than projecting each time
List<int>[] sortedFileIndexes = new List<int>[_sortedLoadOrder.Length];
for (int i = 0; i < sortedFileIndexes.Length; i++)
{
sortedFileIndexes[i] = [];
}
// traverse our files
int fileIndex = 0;
foreach (ResourceMetadata resourceListing in packageIndex.Files)
{
int loadIndex = Array.IndexOf(_sortedLoadOrder, resourceListing.ResourceType);
if (loadIndex < 0)
{
fileIndex++;
continue;
}
// add this index to the list of indexes for this type
sortedFileIndexes[loadIndex].Add(fileIndex++);
}
// iterate over our sorted list of indexes
for (int i = 0; i < _sortedLoadOrder.Length; i++)
{
string rt = _sortedLoadOrder[i];
Type? netType = Hl7.Fhir.Model.ModelInfo.GetTypeForFhirType(rt);
if (netType == null)
{
if (rt == "Conformance")
{
netType = typeof(CapabilityStatement);
}
else
{
throw new Exception($"Failed to find .NET type for FHIR type {rt}");
}
}
// check to see if we want to load this type
switch (rt)
{
case "CodeSystem":
if (!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.CodeSystem))
{
continue;
}
break;
case "ValueSet":
if (!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.ValueSet))
{
continue;
}
break;
case "StructureDefinition":
// note: structure definitions can be one of several types and need to be filtered again after parsing
if (_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.PrimitiveType) ||
_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.ComplexType) ||
_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Resource) ||
_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Extension) ||
_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Profile) ||
_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.LogicalModel) ||
_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Interface))
{
break;
}
continue;
case "SearchParameter":
if (!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.SearchParameter))
{
continue;
}
break;
case "OperationDefinition":
if (!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Operation))
{
continue;
}
break;
case "Conformance":
case "CapabilityStatement":
if (!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.CapabilityStatement))
{
continue;
}
break;
case "ImplementationGuide":
if (!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.ImplementationGuide))
{
continue;
}
break;
case "CompartmentDefinition":
if (!_rootConfiguration.LoadStructures.Contains(FhirArtifactClassEnum.Compartment))
{
continue;
}
break;
}
foreach (int fi in sortedFileIndexes[i])
{
ResourceMetadata pFile = packageIndex.Files[fi];
// load the file
string path = Path.Combine(packageRootDirectory, pFile.FilePath);
if (!File.Exists(path))