-
Notifications
You must be signed in to change notification settings - Fork 522
/
Copy pathCapabilityStatementBuilder.cs
407 lines (347 loc) · 17.6 KB
/
CapabilityStatementBuilder.cs
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
// -------------------------------------------------------------------------------------------------
// 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.IO;
using System.Linq;
using EnsureThat;
using Hl7.Fhir.ElementModel;
using Hl7.Fhir.Serialization;
using Microsoft.Extensions.Options;
using Microsoft.Health.Fhir.Core.Configs;
using Microsoft.Health.Fhir.Core.Data;
using Microsoft.Health.Fhir.Core.Features.Conformance.Models;
using Microsoft.Health.Fhir.Core.Features.Conformance.Serialization;
using Microsoft.Health.Fhir.Core.Features.Definition;
using Microsoft.Health.Fhir.Core.Features.Routing;
using Microsoft.Health.Fhir.Core.Features.Search;
using Microsoft.Health.Fhir.Core.Features.Search.Registry;
using Microsoft.Health.Fhir.Core.Features.Validation;
using Microsoft.Health.Fhir.Core.Features.Version;
using Microsoft.Health.Fhir.Core.Models;
using Microsoft.Health.Fhir.ValueSets;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.Health.Fhir.Core.Features.Conformance
{
internal class CapabilityStatementBuilder : ICapabilityStatementBuilder
{
private readonly ListedCapabilityStatement _statement;
private readonly IModelInfoProvider _modelInfoProvider;
private readonly ISearchParameterDefinitionManager _searchParameterDefinitionManager;
private readonly CoreFeatureConfiguration _configuration;
private readonly ISupportedProfilesStore _supportedProfiles;
private CapabilityStatementBuilder(
ListedCapabilityStatement statement,
IModelInfoProvider modelInfoProvider,
ISearchParameterDefinitionManager searchParameterDefinitionManager,
IOptions<CoreFeatureConfiguration> configuration,
ISupportedProfilesStore supportedProfiles)
{
EnsureArg.IsNotNull(statement, nameof(statement));
EnsureArg.IsNotNull(modelInfoProvider, nameof(modelInfoProvider));
EnsureArg.IsNotNull(searchParameterDefinitionManager, nameof(searchParameterDefinitionManager));
EnsureArg.IsNotNull(configuration, nameof(configuration));
EnsureArg.IsNotNull(supportedProfiles, nameof(supportedProfiles));
_statement = statement;
_modelInfoProvider = modelInfoProvider;
_searchParameterDefinitionManager = searchParameterDefinitionManager;
_configuration = configuration.Value;
_supportedProfiles = supportedProfiles;
}
public static ICapabilityStatementBuilder Create(
IModelInfoProvider modelInfoProvider,
ISearchParameterDefinitionManager searchParameterDefinitionManager,
IOptions<CoreFeatureConfiguration> configuration,
ISupportedProfilesStore supportedProfiles,
Uri metadataUrl,
SearchParameterStatusManager searchParameterStatusManager)
{
EnsureArg.IsNotNull(modelInfoProvider, nameof(modelInfoProvider));
EnsureArg.IsNotNull(searchParameterDefinitionManager, nameof(searchParameterDefinitionManager));
EnsureArg.IsNotNull(metadataUrl, nameof(metadataUrl));
using Stream resourceStream = modelInfoProvider.OpenVersionedFileStream("BaseCapabilities.json");
using var reader = new StreamReader(resourceStream);
var statement = JsonConvert.DeserializeObject<ListedCapabilityStatement>(reader.ReadToEnd());
FileVersionInfo version = ProductVersionInfo.Version;
var versionString = $"{version.FileMajorPart}.{version.FileMinorPart}.{version.FileBuildPart}";
if (modelInfoProvider.Version == FhirSpecification.Stu3 ||
modelInfoProvider.Version == FhirSpecification.R4)
{
((DefaultOptionHashSet<string>)statement.Status).DefaultOption = "active";
}
statement.Name = string.Format(Core.Resources.CapabilityStatementNameFormat, statement.Publisher, configuration.Value.SoftwareName, versionString);
statement.Software = new SoftwareComponent
{
Name = configuration.Value.SoftwareName,
Version = versionString,
};
statement.FhirVersion = modelInfoProvider.SupportedVersion.VersionString;
statement.Date = ProductVersionInfo.CreationTime.ToString("O");
statement.Url = metadataUrl;
return new CapabilityStatementBuilder(statement, modelInfoProvider, searchParameterDefinitionManager, configuration, supportedProfiles);
}
public ICapabilityStatementBuilder Apply(Action<ListedCapabilityStatement> action)
{
EnsureArg.IsNotNull(action, nameof(action));
action(_statement);
return this;
}
public ICapabilityStatementBuilder ApplyToResource(string resourceType, Action<ListedResourceComponent> action)
{
EnsureArg.IsNotNullOrEmpty(resourceType, nameof(resourceType));
EnsureArg.IsNotNull(action, nameof(action));
EnsureArg.IsTrue(_modelInfoProvider.IsKnownResource(resourceType), nameof(resourceType), x => GenerateTypeErrorMessage(x, resourceType));
ListedRestComponent listedRestComponent = _statement.Rest.Server();
ListedResourceComponent resourceComponent = listedRestComponent.Resource.SingleOrDefault(x => string.Equals(x.Type, resourceType, StringComparison.OrdinalIgnoreCase));
if (resourceComponent == null)
{
resourceComponent = new ListedResourceComponent()
{
Type = resourceType,
Profile = new ReferenceComponent
{
Reference = $"http://hl7.org/fhir/StructureDefinition/{resourceType}",
},
};
((DefaultOptionHashSet<string>)resourceComponent.Versioning).DefaultOption = _configuration.Versioning.ResourceTypeOverrides.TryGetValue(resourceType, out string overrideValue) ? overrideValue : _configuration.Versioning.Default;
listedRestComponent.Resource.Add(resourceComponent);
}
action(resourceComponent);
return this;
}
private CapabilityStatementBuilder AddResourceInteraction(string resourceType, string interaction)
{
ApplyToResource(resourceType, c =>
{
if (!c.Interaction.Where(x => x.Code == interaction).Any())
{
c.Interaction.Add(new ResourceInteractionComponent
{
Code = interaction,
});
}
});
return this;
}
private void RemoveRestInteraction(string resourceType, string interaction)
{
ApplyToResource(resourceType, c =>
{
var toRemove = c.Interaction.Where(x => x.Code == interaction).FirstOrDefault();
if (toRemove != null)
{
c.Interaction.Remove(toRemove);
}
});
}
public ICapabilityStatementBuilder AddGlobalInteraction(string systemInteraction)
{
EnsureArg.IsNotNullOrEmpty(systemInteraction, nameof(systemInteraction));
_statement.Rest.Server().Interaction.Add(new ResourceInteractionComponent { Code = systemInteraction });
return this;
}
public ICapabilityStatementBuilder AddGlobalSearchParameters()
{
_statement.Rest.Server().SearchParam.Add(new SearchParamComponent { Name = SearchParameterNames.ResourceType, Definition = SearchParameterNames.TypeUri, Type = SearchParamType.Token });
_statement.Rest.Server().SearchParam.Add(new SearchParamComponent { Name = KnownQueryParameterNames.Count, Type = SearchParamType.Number });
return this;
}
private CapabilityStatementBuilder SyncSearchParamsAsync(string resourceType)
{
EnsureArg.IsNotNullOrEmpty(resourceType, nameof(resourceType));
EnsureArg.IsTrue(_modelInfoProvider.IsKnownResource(resourceType), nameof(resourceType), x => GenerateTypeErrorMessage(x, resourceType));
List<SearchParameterInfo> searchParams = _searchParameterDefinitionManager.GetSearchParameters(resourceType).ToList();
if (searchParams.Any())
{
ApplyToResource(resourceType, c =>
{
c.SearchParam.Clear();
foreach (SearchParamComponent searchParam in searchParams.Select(x => new SearchParamComponent
{
Name = x.Name,
Type = x.Type,
Definition = x.Url,
Documentation = x.Description,
}))
{
// Exclude _type search param under resource
if (string.Equals("_type", searchParam.Name, StringComparison.OrdinalIgnoreCase))
{
continue;
}
c.SearchParam.Add(searchParam);
}
});
AddResourceInteraction(resourceType, TypeRestfulInteraction.SearchType);
}
else
{
RemoveRestInteraction(resourceType, TypeRestfulInteraction.SearchType);
}
// Add search include for resource
ApplyToResource(resourceType, c =>
{
c.SearchInclude.Clear();
foreach (var referenceParam in searchParams.Where(x => x.Type == SearchParamType.Reference))
{
c.SearchInclude.Add($"{resourceType}:{referenceParam.Code}");
}
if (c.SearchInclude.Any())
{
c.SearchInclude.Add("*");
}
});
// Add search revinclude for resource
foreach (var referenceParam in searchParams.Where(x => x.Type == SearchParamType.Reference))
{
foreach (var targetType in referenceParam.TargetResourceTypes)
{
ApplyToResource(targetType, c =>
{
c.SearchRevInclude.Add($"{resourceType}:{referenceParam.Code}");
});
}
}
return this;
}
private CapabilityStatementBuilder SyncProfile(string resourceType, bool disableCacheRefresh)
{
EnsureArg.IsNotNullOrEmpty(resourceType, nameof(resourceType));
EnsureArg.IsTrue(_modelInfoProvider.IsKnownResource(resourceType), nameof(resourceType), x => GenerateTypeErrorMessage(x, resourceType));
ApplyToResource(resourceType, resourceComponent =>
{
var supportedProfiles = _supportedProfiles.GetSupportedProfiles(resourceType, disableCacheRefresh);
if (supportedProfiles != null)
{
if (!_modelInfoProvider.Version.Equals(FhirSpecification.Stu3))
{
resourceComponent.SupportedProfile.Clear();
foreach (var profile in supportedProfiles)
{
resourceComponent.SupportedProfile.Add(profile);
}
}
else
{
foreach (var profile in supportedProfiles)
{
_statement.Profile.Add(new ReferenceComponent
{
Reference = profile,
});
}
}
}
});
return this;
}
public ICapabilityStatementBuilder PopulateDefaultResourceInteractions()
{
foreach (string resource in _modelInfoProvider.GetResourceTypeNames())
{
// Parameters is a non-persisted resource used to pass information into and back from an operation.
if (string.Equals(resource, KnownResourceTypes.Parameters, StringComparison.Ordinal))
{
continue;
}
AddResourceInteraction(resource, TypeRestfulInteraction.Create);
AddResourceInteraction(resource, TypeRestfulInteraction.Read);
AddResourceInteraction(resource, TypeRestfulInteraction.Vread);
AddResourceInteraction(resource, TypeRestfulInteraction.HistoryType);
AddResourceInteraction(resource, TypeRestfulInteraction.HistoryInstance);
// AuditEvents should not allow Update or Delete
if (!string.Equals(resource, KnownResourceTypes.AuditEvent, StringComparison.Ordinal))
{
AddResourceInteraction(resource, TypeRestfulInteraction.Update);
AddResourceInteraction(resource, TypeRestfulInteraction.Patch);
AddResourceInteraction(resource, TypeRestfulInteraction.Delete);
}
ApplyToResource(resource, component =>
{
component.Versioning.Add(ResourceVersionPolicy.NoVersion);
component.Versioning.Add(ResourceVersionPolicy.Versioned);
component.Versioning.Add(ResourceVersionPolicy.VersionedUpdate);
// Create is added for every resource above.
component.ConditionalCreate = true;
// AuditEvent don't allow update, so no conditional update as well.
if (!string.Equals(resource, KnownResourceTypes.AuditEvent, StringComparison.Ordinal))
{
component.ConditionalUpdate = true;
component.ConditionalDelete.Add(ConditionalDeleteStatus.NotSupported);
component.ConditionalDelete.Add(ConditionalDeleteStatus.Single);
component.ConditionalDelete.Add(ConditionalDeleteStatus.Multiple);
}
component.ReadHistory = true;
component.UpdateCreate = true;
});
}
AddGlobalInteraction(SystemRestfulInteraction.HistorySystem);
return this;
}
public ICapabilityStatementBuilder SyncSearchParametersAsync()
{
foreach (string resource in _modelInfoProvider.GetResourceTypeNames())
{
ApplyToResource(resource, c => c.SearchRevInclude.Clear());
}
foreach (string resource in _modelInfoProvider.GetResourceTypeNames())
{
// Parameters is a non-persisted resource used to pass information into and back from an operation
if (string.Equals(resource, KnownResourceTypes.Parameters, StringComparison.Ordinal))
{
continue;
}
SyncSearchParamsAsync(resource);
}
return this;
}
public ICapabilityStatementBuilder SyncProfiles(bool disableCacheRefresh = false)
{
if (!disableCacheRefresh)
{
_supportedProfiles.Refresh();
}
// This line needs to come after the refresh because the refresh can trigger this method to run and can add duplicate values to the Profile in STU3.
_statement.Profile.Clear();
foreach (string resource in _modelInfoProvider.GetResourceTypeNames())
{
// Parameters is a non-persisted resource used to pass information into and back from an operation
if (string.Equals(resource, KnownResourceTypes.Parameters, StringComparison.Ordinal))
{
continue;
}
SyncProfile(resource, disableCacheRefresh);
}
return this;
}
public ITypedElement Build()
{
// To build a CapabilityStatement we use a custom JsonConverter that serializes
// the ListedCapabilityStatement into a CapabilityStatement poco
var json = JsonConvert.SerializeObject(_statement, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter>
{
new DefaultOptionHashSetJsonConverter(),
new EnumLiteralJsonConverter(),
new ReferenceComponentConverter(_modelInfoProvider),
new CodingJsonConverter(),
},
NullValueHandling = NullValueHandling.Ignore,
});
ISourceNode jsonStatement = FhirJsonNode.Parse(json);
// Using a version specific StructureDefinitionSummaryProvider ensures the metadata to be
// compatible with the current FhirSerializer/output formatter.
return jsonStatement.ToTypedElement(_modelInfoProvider.StructureDefinitionSummaryProvider);
}
private static EnsureOptions GenerateTypeErrorMessage(EnsureOptions options, string resourceType)
{
return options.WithMessage($"Unknown resource type {resourceType}");
}
}
}