-
Notifications
You must be signed in to change notification settings - Fork 581
Expand file tree
/
Copy pathFhirClient.cs
More file actions
734 lines (569 loc) · 32.4 KB
/
FhirClient.cs
File metadata and controls
734 lines (569 loc) · 32.4 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
// -------------------------------------------------------------------------------------------------
// 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 System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using EnsureThat;
using Hl7.Fhir.Model;
using Hl7.Fhir.Rest;
using Hl7.Fhir.Serialization;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.Health.Fhir.Client
{
public class FhirClient : IFhirClient
{
private const string BundleProcessingLogicHeader = "x-bundle-processing-logic";
private const string ConditionalQueryProcessingLogicHeader = "x-conditionalquery-processing-logic";
private const string IfNoneExistHeaderName = "If-None-Exist";
private const string ProvenanceHeader = "X-Provenance";
private const string IfMatchHeaderName = "If-Match";
private const string PreferHeaderName = "prefer";
public const string ProfileValidation = "x-ms-profile-validation";
public const string ReindexParametersStatus = "Status";
private readonly string _contentType;
private readonly Func<Base, SummaryType, string> _serialize;
private readonly Func<string, Resource> _deserialize;
private readonly MediaTypeWithQualityHeaderValue _mediaType;
/// <summary>
/// Initializes a new instance of the <see cref="FhirClient"/> class.
/// </summary>
/// <param name="baseAddress">The address of the FHIR server to communicate with.</param>
/// <param name="format">The format to communicate with the FHIR server.</param>
/// <exception cref="InvalidOperationException">Returned if the format specified is invalid.</exception>
public FhirClient(Uri baseAddress, ResourceFormat format)
: this(new HttpClient { BaseAddress = baseAddress }, format)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FhirClient"/> class.
/// </summary>
/// <param name="httpClient">The HttpClient to use for communication. It must have a BaseAddress specified.</param>
/// <param name="format">The format to communicate with the FHIR server.</param>
/// <exception cref="InvalidOperationException">Returned if the format specified is invalid.</exception>
public FhirClient(
HttpClient httpClient,
ResourceFormat format = ResourceFormat.Json)
{
EnsureArg.IsNotNull(httpClient, nameof(httpClient));
if (httpClient.BaseAddress == null)
{
throw new ArgumentException(Resources.BaseAddressMustBeSpecified);
}
HttpClient = httpClient;
Format = format;
if (format == ResourceFormat.Json)
{
var jsonSerializer = new FhirJsonSerializer();
_serialize = (resource, summary) => jsonSerializer.SerializeToString(resource, summary);
var jsonParser = new FhirJsonParser();
_deserialize = jsonParser.Parse<Resource>;
_contentType = ContentType.JSON_CONTENT_HEADER;
}
else if (format == ResourceFormat.Xml)
{
var xmlSerializer = new FhirXmlSerializer();
_serialize = (resource, summary) => xmlSerializer.SerializeToString(resource, summary);
var xmlParser = new FhirXmlParser();
_deserialize = xmlParser.Parse<Resource>;
_contentType = ContentType.XML_CONTENT_HEADER;
}
else
{
throw new InvalidOperationException("Unsupported format.");
}
_mediaType = MediaTypeWithQualityHeaderValue.Parse(_contentType);
}
public ResourceFormat Format { get; }
public HttpClient HttpClient { get; }
public Task<FhirResponse<T>> CreateAsync<T>(T resource, string conditionalCreateCriteria = null, string provenanceHeader = null, Dictionary<string, string> additionalHeaders = default, CancellationToken cancellationToken = default)
where T : Resource
{
return CreateAsync(resource.TypeName, resource, conditionalCreateCriteria, provenanceHeader, additionalHeaders, cancellationToken);
}
public async Task<FhirResponse<T>> CreateAsync<T>(string uri, T resource, string conditionalCreateCriteria = null, string provenanceHeader = null, Dictionary<string, string> additionalHeaders = default, CancellationToken cancellationToken = default)
where T : Resource
{
using var message = new HttpRequestMessage(HttpMethod.Post, uri);
message.Headers.Accept.Add(_mediaType);
message.Content = CreateStringContent(resource);
if (!string.IsNullOrEmpty(conditionalCreateCriteria))
{
message.Headers.TryAddWithoutValidation(IfNoneExistHeaderName, conditionalCreateCriteria);
}
if (!string.IsNullOrEmpty(provenanceHeader))
{
message.Headers.TryAddWithoutValidation(ProvenanceHeader, provenanceHeader);
}
if (additionalHeaders?.Any() ?? false)
{
foreach (var header in additionalHeaders)
{
message.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<T>(response);
}
public Task<FhirResponse<T>> ReadAsync<T>(ResourceType resourceType, string resourceId, CancellationToken cancellationToken = default)
where T : Resource
{
return ReadAsync<T>($"{resourceType}/{resourceId}", cancellationToken);
}
public async Task<FhirResponse<T>> ReadAsync<T>(string uri, CancellationToken cancellationToken = default)
where T : Resource
{
using var message = new HttpRequestMessage(HttpMethod.Get, uri);
message.Headers.Accept.Add(_mediaType);
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<T>(response);
}
public Task<FhirResponse<T>> VReadAsync<T>(ResourceType resourceType, string resourceId, string versionId, CancellationToken cancellationToken = default)
where T : Resource
{
return ReadAsync<T>($"{resourceType}/{resourceId}/_history/{versionId}", cancellationToken);
}
public Task<FhirResponse<Bundle>> ReadHistoryAsync(ResourceType resourceType, string resourceId, CancellationToken cancellationToken = default)
{
return SearchAsync($"{resourceType}/{resourceId}/_history", cancellationToken);
}
public Task<FhirResponse<T>> UpdateAsync<T>(T resource, string ifMatchHeaderETag = null, string provenanceHeader = null, bool metaHistory = true, CancellationToken cancellationToken = default)
where T : Resource
{
return UpdateAsync($"{resource.TypeName}/{resource.Id}", resource, ifMatchHeaderETag, provenanceHeader, metaHistory, cancellationToken);
}
public Task<FhirResponse<T>> ConditionalUpdateAsync<T>(T resource, string searchCriteria, string ifMatchHeaderETag = null, string provenanceHeader = null, bool metaHistory = true, CancellationToken cancellationToken = default)
where T : Resource
{
return UpdateAsync($"{resource.TypeName}?{searchCriteria}", resource, ifMatchHeaderETag, provenanceHeader, metaHistory, cancellationToken);
}
public async Task<FhirResponse<T>> UpdateAsync<T>(string uri, T resource, string ifMatchHeaderETag = null, string provenanceHeader = null, bool metaHistory = true, CancellationToken cancellationToken = default)
where T : Resource
{
using var message = new HttpRequestMessage(HttpMethod.Put, uri)
{
Content = CreateStringContent(resource),
};
message.Headers.Accept.Add(_mediaType);
if (ifMatchHeaderETag != null)
{
message.Headers.Add(IfMatchHeaderName, ifMatchHeaderETag);
}
if (provenanceHeader != null)
{
message.Headers.Add(ProvenanceHeader, provenanceHeader);
}
if (!metaHistory)
{
message.RequestUri = new Uri(message.RequestUri + (message.RequestUri.OriginalString.Contains('?', StringComparison.OrdinalIgnoreCase) ? "&" : "?") + "_meta-history=false", UriKind.Relative);
}
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<T>(response);
}
public Task<FhirResponse> DeleteAsync<T>(T resource, CancellationToken cancellationToken = default)
where T : Resource
{
return DeleteAsync($"{resource.TypeName}/{resource.Id}", cancellationToken);
}
public async Task<FhirResponse> DeleteAsync(string uri, CancellationToken cancellationToken = default)
{
return await DeleteAsync(uri, true, cancellationToken);
}
public async Task<FhirResponse> DeleteAsync(string uri, bool checkSuccess, CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Delete, uri);
message.Headers.Accept.Add(_mediaType);
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
if (checkSuccess)
{
await EnsureSuccessStatusCodeAsync(response);
}
return new FhirResponse(response);
}
public Task<FhirResponse> HardDeleteAsync<T>(T resource, bool checkSuccess, CancellationToken cancellationToken = default)
where T : Resource
{
return DeleteAsync($"{resource.TypeName}/{resource.Id}?hardDelete=true", checkSuccess, cancellationToken);
}
public Task<FhirResponse> HardDeleteAsync<T>(T resource, CancellationToken cancellationToken = default)
where T : Resource
{
return DeleteAsync($"{resource.TypeName}/{resource.Id}?hardDelete=true", cancellationToken);
}
public async Task<FhirResponse<T>> JsonPatchAsync<T>(T resource, string content, string ifMatchVersion = null, bool metaHistory = true, CancellationToken cancellationToken = default)
where T : Resource
{
return await JsonPatchAsync<T>($"{resource.TypeName}/{resource.Id}?_meta-history={metaHistory}", content, ifMatchVersion, cancellationToken);
}
public async Task<FhirResponse<T>> ConditionalJsonPatchAsync<T>(string resourceType, string searchCriteria, string content, string ifMatchVersion = null, bool metaHistory = true, CancellationToken cancellationToken = default)
where T : Resource
{
return await JsonPatchAsync<T>($"{resourceType}?{searchCriteria}&_meta-history={metaHistory}", content, ifMatchVersion, cancellationToken);
}
private async Task<FhirResponse<T>> JsonPatchAsync<T>(string uri, string content, string ifMatchVersion = null, CancellationToken cancellationToken = default)
where T : Resource
{
using var message = new HttpRequestMessage(HttpMethod.Patch, uri)
{
Content = new StringContent(content, Encoding.UTF8, "application/json-patch+json"),
};
message.Headers.Accept.Add(_mediaType);
if (ifMatchVersion != null)
{
var weakETag = $"W/\"{ifMatchVersion}\"";
message.Headers.Add(IfMatchHeaderName, weakETag);
}
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<T>(response);
}
public async Task<FhirResponse<T>> FhirPatchAsync<T>(T resource, Parameters patchRequest, string ifMatchVersion = null, bool metaHistory = true, CancellationToken cancellationToken = default)
where T : Resource
{
return await FhirPatchAsync<T>($"{resource.TypeName}/{resource.Id}?_meta-history={metaHistory}", patchRequest, ifMatchVersion, cancellationToken);
}
public async Task<FhirResponse<T>> ConditionalFhirPatchAsync<T>(string resourceType, string searchCriteria, Parameters patchRequest, string ifMatchVersion = null, bool metaHistory = true, CancellationToken cancellationToken = default)
where T : Resource
{
return await FhirPatchAsync<T>($"{resourceType}?{searchCriteria}&_meta-history={metaHistory}", patchRequest, ifMatchVersion, cancellationToken);
}
private async Task<FhirResponse<T>> FhirPatchAsync<T>(string uri, Parameters patchRequest, string ifMatchVersion = null, CancellationToken cancellationToken = default)
where T : Resource
{
using var message = new HttpRequestMessage(HttpMethod.Patch, uri)
{
Content = CreateStringContent(patchRequest),
};
message.Headers.Accept.Add(_mediaType);
if (ifMatchVersion != null)
{
var weakETag = $"W/\"{ifMatchVersion}\"";
message.Headers.Add(IfMatchHeaderName, weakETag);
}
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<T>(response);
}
public async Task<HttpResponseMessage> BulkUpdateAsync(string uri, Parameters patchRequest, CancellationToken cancellationToken)
{
using var message = new HttpRequestMessage(HttpMethod.Patch, uri)
{
Content = CreateStringContent(patchRequest),
};
message.Headers.Accept.Add(_mediaType);
message.Headers.Add(PreferHeaderName, "respond-async");
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
return response;
}
public Task<FhirResponse<Bundle>> SearchAsync(ResourceType resourceType, string query = null, int? count = null, CancellationToken cancellationToken = default)
{
var sb = new StringBuilder();
sb.Append(resourceType).Append('?');
if (query != null)
{
sb.Append(query);
}
if (count != null)
{
if (sb[^1] != '?')
{
sb.Append('&');
}
sb.Append("_count=").Append(count.Value);
}
return SearchAsync(sb.ToString(), null, cancellationToken);
}
public async Task<FhirResponse<Bundle>> SearchAsync(string url, CancellationToken cancellationToken = default)
{
return await SearchAsync(url, null, cancellationToken);
}
public async Task<FhirResponse<Bundle>> SearchAsync(string url, Tuple<string, string> customHeader, CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Get, url.TrimStart('/'));
message.Headers.Accept.Add(_mediaType);
if (customHeader != null)
{
message.Headers.Add(customHeader.Item1, customHeader.Item2);
}
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<Bundle>(response);
}
public async Task<FhirResponse<Bundle>> SearchPostAsync(string resourceType, string query, CancellationToken cancellationToken = default, params (string key, string value)[] body)
{
using var message = new HttpRequestMessage(HttpMethod.Post, $"{(string.IsNullOrEmpty(resourceType) ? null : $"{resourceType}/")}_search?{query}")
{
Content = new FormUrlEncodedContent(body.ToDictionary(p => p.key, p => p.value)),
};
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<Bundle>(response);
}
public async Task<FhirResponse<Resource>> PostAsync(string resourceType, string body, CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Post, $"{(string.IsNullOrEmpty(resourceType) ? null : $"{resourceType}/")}")
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
message.Headers.Accept.Add(_mediaType);
HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<Resource>(response);
}
public async Task<Uri> ExportAsync(string path = "", string parameters = "", CancellationToken cancellationToken = default)
{
string requestPath = $"{path}$export?{parameters}";
using var message = new HttpRequestMessage(HttpMethod.Get, requestPath);
message.Headers.Add("Accept", "application/fhir+json");
message.Headers.Add("Prefer", "respond-async");
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return response.Content.Headers.ContentLocation;
}
public async Task<Uri> AnonymizedExportAsync(string anonymizationConfig, DateTimeOffset since, string container, string etag = null, string path = "", CancellationToken cancellationToken = default)
{
anonymizationConfig = HttpUtility.UrlEncode(anonymizationConfig);
etag = HttpUtility.UrlEncode(etag);
container = HttpUtility.UrlEncode(container);
string requestUrl = $"{path}$export?_since={since.ToString("yyyy-MM-ddTHH:mm:ss")}&_container={container}&_anonymizationConfig={anonymizationConfig}&_anonymizationConfigEtag={etag}";
using var message = new HttpRequestMessage(HttpMethod.Get, requestUrl);
message.Headers.Add("Accept", "application/fhir+json");
message.Headers.Add("Prefer", "respond-async");
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return response.Content.Headers.ContentLocation;
}
public async Task<Uri> AnonymizedExportUsingAcrAsync(string anonymizationConfig, string anonymizationConfigCollectionReference, DateTimeOffset since, string container, string path = "", CancellationToken cancellationToken = default)
{
anonymizationConfig = HttpUtility.UrlEncode(anonymizationConfig);
anonymizationConfigCollectionReference = HttpUtility.UrlEncode(anonymizationConfigCollectionReference);
container = HttpUtility.UrlEncode(container);
string requestUrl = $"{path}$export?_since={since.ToString("yyyy-MM-ddTHH:mm:ss")}&_container={container}&_anonymizationConfig={anonymizationConfig}&_anonymizationConfigCollectionReference={anonymizationConfigCollectionReference}";
using var message = new HttpRequestMessage(HttpMethod.Get, requestUrl);
message.Headers.Add("Accept", "application/fhir+json");
message.Headers.Add("Prefer", "respond-async");
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return response.Content.Headers.ContentLocation;
}
public async Task<HttpResponseMessage> CheckExportAsync(Uri contentLocation, CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Get, contentLocation);
var response = await HttpClient.SendAsync(message, cancellationToken);
return response;
}
public async Task CancelExport(Uri contentLocation, CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Delete, contentLocation);
await HttpClient.SendAsync(message, cancellationToken);
}
public async Task<FhirResponse> ConvertDataAsync(Parameters parameters, CancellationToken cancellationToken = default)
{
string requestPath = "$convert-data";
using var message = new HttpRequestMessage(HttpMethod.Post, requestPath)
{
Content = CreateStringContent(parameters),
};
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return new FhirResponse(response);
}
public async Task<Uri> ImportAsync(Parameters parameters, CancellationToken cancellationToken = default)
{
string requestPath = "$import";
using var message = new HttpRequestMessage(HttpMethod.Post, requestPath)
{
Content = CreateStringContent(parameters),
};
message.Headers.Add("Prefer", "respond-async");
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return response.Content.Headers.ContentLocation;
}
public async Task<HttpResponseMessage> CancelImport(Uri contentLocation, CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Delete, contentLocation);
message.Headers.Add("Prefer", "respond-async");
return await HttpClient.SendAsync(message, cancellationToken);
}
public async Task<HttpResponseMessage> CheckImportAsync(Uri contentLocation, bool checkSuccessStatus = true, bool returnDetails = false, CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Get, contentLocation + (returnDetails ? "?_details=true" : string.Empty));
message.Headers.Add("Prefer", "respond-async");
var response = await HttpClient.SendAsync(message, cancellationToken);
if (checkSuccessStatus)
{
await EnsureSuccessStatusCodeAsync(response);
}
return response;
}
public async Task<FhirResponse<Bundle>> PostBundleAsync(Resource bundle, FhirBundleOptions bundleOptions = default, CancellationToken cancellationToken = default)
{
if (bundleOptions == null)
{
bundleOptions = FhirBundleOptions.Default;
}
using var message = new HttpRequestMessage(HttpMethod.Post, string.Empty)
{
Content = CreateStringContent(bundle),
};
message.Headers.Accept.Add(_mediaType);
// Profile validation.
if (bundleOptions.ProfileValidation)
{
message.Headers.Add(ProfileValidation, bundleOptions.ProfileValidation.ToString());
}
// Bundle processing logic (parallel or sequential).
message.Headers.Add(BundleProcessingLogicHeader, bundleOptions.BundleProcessingLogic.ToString());
// Conditional query processing logic.
if (bundleOptions.MaximizeConditionalQueryParallelism)
{
message.Headers.Add(ConditionalQueryProcessingLogicHeader, "parallel");
}
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<Bundle>(response);
}
public async Task<(FhirResponse<Parameters> Response, Uri Uri)> PostReindexJobAsync(
Parameters parameters,
string uniqueResource = null,
CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Post, $"{uniqueResource}$reindex")
{
Content = CreateStringContent(parameters),
};
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return (await CreateResponseAsync<Parameters>(response), response.Content.Headers.ContentLocation);
}
public async Task<FhirResponse<Parameters>> CheckJobAsync(Uri contentLocation, CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Get, contentLocation);
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
return await CreateResponseAsync<Parameters>(response);
}
public async Task<FhirResponse<Parameters>> WaitForReindexStatus(Uri reindexJobUri, params string[] desiredStatus)
{
const int maxSeconds = 300;
var sw = Stopwatch.StartNew();
string currentStatus;
FhirResponse<Parameters> reindexJobResult;
do
{
await Task.Delay(TimeSpan.FromSeconds(1));
reindexJobResult = await CheckJobAsync(reindexJobUri);
currentStatus = reindexJobResult.Resource.Parameter.FirstOrDefault(p => p.Name.Equals(ReindexParametersStatus, StringComparison.OrdinalIgnoreCase))?.Value.ToString();
}
while (!desiredStatus.Contains(currentStatus) && sw.Elapsed.TotalSeconds < maxSeconds);
sw.Stop();
if (sw.Elapsed.TotalSeconds >= maxSeconds && !desiredStatus.Contains(currentStatus))
{
#pragma warning disable CA2201 // Do not raise reserved exception types. This is used in a test and has a specific message.
throw new Exception($"ReindexJob did not complete within {maxSeconds} seconds. This may cause other tests using Reindex to fail.");
#pragma warning restore CA2201 // Do not raise reserved exception types
}
return reindexJobResult;
}
public async Task<FhirResponse<Parameters>> WaitForBulkJobStatus(string jobType, Uri bulkJobUri)
{
const int maxSeconds = 300;
var sw = Stopwatch.StartNew();
FhirResponse<Parameters> jobResult;
do
{
await Task.Delay(TimeSpan.FromSeconds(1));
jobResult = await CheckJobAsync(bulkJobUri);
}
while (jobResult.Response.StatusCode == System.Net.HttpStatusCode.Accepted && sw.Elapsed.TotalSeconds < maxSeconds);
sw.Stop();
if (sw.Elapsed.TotalSeconds >= maxSeconds && jobResult.Response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
#pragma warning disable CA2201 // Do not raise reserved exception types. This is used in a test and has a specific message.
throw new Exception($"${jobType} at ${bulkJobUri} did not complete within {maxSeconds} seconds.");
#pragma warning restore CA2201 // Do not raise reserved exception types
}
return jobResult;
}
/// <summary>
/// Calls the $validate endpoint.
/// </summary>
/// <param name="uri">The URL to call</param>
/// <param name="resource">The resource to be validated. The resource parameter is a string instead of a Resource object because the validate endpoint is frequently sent invalid resources that couldn't be parsed.</param>
/// <param name="profile">Profile uri to check resource against.</param>
/// <param name="cancellationToken">The cancellation token</param>
public async Task<OperationOutcome> ValidateAsync(string uri, string resource, string profile = null, CancellationToken cancellationToken = default)
{
using var message = new HttpRequestMessage(HttpMethod.Post, profile != null ? uri + $"?profile={profile}" : uri)
{
Content = new StringContent(resource, Encoding.UTF8, ContentType.JSON_CONTENT_HEADER),
};
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<OperationOutcome>(response);
}
public async Task<OperationOutcome> ValidateByIdAsync(ResourceType resourceType, string resourceId, string profile, CancellationToken cancellationToken = default)
{
var uri = $"{resourceType}/{resourceId}/$validate";
using var message = new HttpRequestMessage(HttpMethod.Get, profile != null ? uri + $"?profile={profile}" : uri);
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<OperationOutcome>(response);
}
private StringContent CreateStringContent(Resource resource)
{
return new StringContent(_serialize(resource, SummaryType.False), Encoding.UTF8, _contentType);
}
private async Task EnsureSuccessStatusCodeAsync(HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
await response.Content.LoadIntoBufferAsync();
using var message = new HttpRequestMessage(HttpMethod.Get, "health/check");
using HttpResponseMessage healthCheck = await HttpClient.SendAsync(message, CancellationToken.None);
FhirResponse<OperationOutcome> operationOutcome;
try
{
operationOutcome = await CreateResponseAsync<OperationOutcome>(response);
}
catch (Exception)
{
// The response could not be read as an OperationOutcome. Throw a generic HTTP error.
throw new HttpRequestException($"Status code: {response.StatusCode}; reason phrase: '{response.ReasonPhrase}'; body: '{await response.Content.ReadAsStringAsync()}'; health check: '{healthCheck.StatusCode}'");
}
throw new FhirClientException(operationOutcome, healthCheck.StatusCode);
}
}
private async Task<FhirResponse<T>> CreateResponseAsync<T>(HttpResponseMessage response)
where T : Resource
{
string content = await response.Content.ReadAsStringAsync();
return new FhirResponse<T>(
response,
string.IsNullOrWhiteSpace(content) ? null : (T)_deserialize(content));
}
public async Task<Parameters> MemberMatch(Patient patient, Coverage coverage, CancellationToken cancellationToken = default)
{
var inParams = new Parameters();
inParams.Add("MemberPatient", patient);
inParams.Add("OldCoverage", coverage);
using var message = new HttpRequestMessage(HttpMethod.Post, "Patient/$member-match");
message.Headers.Accept.Add(_mediaType);
message.Content = CreateStringContent(inParams);
using HttpResponseMessage response = await HttpClient.SendAsync(message, cancellationToken);
await EnsureSuccessStatusCodeAsync(response);
return await CreateResponseAsync<Parameters>(response);
}
}
}