diff --git a/Client/Services/DiscoveryService.cs b/Client/Services/DiscoveryService.cs index 7e5cf2e..63d61e4 100644 --- a/Client/Services/DiscoveryService.cs +++ b/Client/Services/DiscoveryService.cs @@ -36,7 +36,15 @@ public DiscoveryService(HttpClient httpClient, ILogger logger) /// /// /// - public async Task GetUdapMetadataVerificationModel(string metadataUrl, string? community, CancellationToken token) + public Task GetUdapMetadataVerificationModel(string metadataUrl, string? community, CancellationToken token) => + GetUdapMetadataVerificationModel(metadataUrl, community, probe: false, token); + + /// + public Task ProbeUdapMetadata(string metadataUrl, CancellationToken token) => + GetUdapMetadataVerificationModel(metadataUrl, null, probe: true, token); + + private async Task GetUdapMetadataVerificationModel( + string metadataUrl, string? community, bool probe, CancellationToken token) { try { @@ -46,6 +54,12 @@ public DiscoveryService(HttpClient httpClient, ILogger logger) { var udapMetadataUrl = $"Metadata?metadataUrl={metadataUrl}"; + if (probe) + { + // Validate without making this URL the session's FHIR server. + udapMetadataUrl += "&probe=true"; + } + if (community != null) { udapMetadataUrl += $"&{UdapConstants.Community}={community}"; diff --git a/Client/Services/FhirService.cs b/Client/Services/FhirService.cs index 9c58fb8..17c588b 100644 --- a/Client/Services/FhirService.cs +++ b/Client/Services/FhirService.cs @@ -295,23 +295,27 @@ public async Task> SearchGet(string queryParameters) { var controller = await GetControllerPath(); var response = await _httpClient.PostAsJsonAsync($"{controller}/GetSearch", queryParameters); - - return await SearchHandler(response); + var result = await SearchHandler(response); + EnrichResult(response, result); + return result; } public async Task> SearchPost(SearchForm searchForm) { var controller = await GetControllerPath(); var response = await _httpClient.PostAsJsonAsync($"{controller}/PostSearch", searchForm); - - return await SearchHandler(response); + var result = await SearchHandler(response); + EnrichResult(response, result); + return result; } public async Task> Get(string resourcePath) { var controller = await GetControllerPath(); var response = await _httpClient.PostAsJsonAsync($"{controller}/Get", resourcePath); - return await GetHandler(response); + var result = await GetHandler(response); + EnrichResult(response, result); + return result; } private async Task> GetHandler(HttpResponseMessage response) @@ -653,6 +657,12 @@ private void EnrichResult(HttpResponseMessage responseMessage, FhirResultMode } } + if (responseMessage.Headers.TryGetValues(UdapEdConstants.FhirClient.FhirElapsedMs, out var elapsedValues) + && long.TryParse(elapsedValues.FirstOrDefault(), out var elapsedMs)) + { + resultModel.FhirElapsedMs = elapsedMs; + } + if (responseMessage.Headers.TryGetValues(UdapEdConstants.FhirClient.FhirOutgoingRequest, out var reqValues)) { var base64 = reqValues.FirstOrDefault(); diff --git a/Client/wwwroot/Packages/udap_urls.json b/Client/wwwroot/Packages/udap_urls.json index a8d5a3e..aacd506 100644 --- a/Client/wwwroot/Packages/udap_urls.json +++ b/Client/wwwroot/Packages/udap_urls.json @@ -6,7 +6,6 @@ "https://dev-mtx-interop.meditech.com/v2/uscore/STU6", "https://securefhir.zimt.work/udap-public", "https://identity-matching.fast.hl7.org/fhir", - "https://national-directory.fast.hl7.org/fhir", "https://udap.fhir.poolnook.me/evernorth", "https://fhir-udap.azurewebsites.net", "https://ihe-nimbus.epic.com/Interconnect-FHIR/api/fhir/r4" diff --git a/Client/wwwroot/index.html b/Client/wwwroot/index.html index bddd2ef..579b8b4 100644 --- a/Client/wwwroot/index.html +++ b/Client/wwwroot/index.html @@ -22,10 +22,10 @@ - - - - + + + + @@ -44,12 +44,12 @@ 🗙 - - - - + + + + - + diff --git a/Server/Controllers/FhirController.cs b/Server/Controllers/FhirController.cs index 3fde17b..59d587c 100644 --- a/Server/Controllers/FhirController.cs +++ b/Server/Controllers/FhirController.cs @@ -356,14 +356,13 @@ public async Task GetSearch([FromBody] string fullSearch) { try { - //Todo maybe inject in the future, so we don't exhaust underlying HttpClient - var httpClient = new HttpClient(_customDecompressionHandler); + using var httpClient = DirectoryHttpClient(); var fhirClient = new FhirClient(fullSearch, httpClient, new FhirClientSettings() { PreferredFormat = ResourceFormat.Json }); - Console.WriteLine(fullSearch); var bundle = await fhirClient.GetAsync(fullSearch); var bundleJson = await new FhirJsonSerializer().SerializeToStringAsync(bundle); + CopyCustomHeadersToResponse(); return Ok(bundleJson); } catch (FhirOperationException ex) @@ -402,20 +401,20 @@ public async Task PostSearch([FromBody] SearchForm searchForm) { try { - //Todo maybe inject in the future, so we don't exhaust underlying HttpClient - var httpClient = new HttpClient(_customDecompressionHandler); + using var httpClient = DirectoryHttpClient(); var fhirClient = new FhirClient(searchForm.Url, httpClient, new FhirClientSettings() { PreferredFormat = ResourceFormat.Json }); var searchParams = new SearchParams(); foreach (var pair in searchForm.FormUrlEncoded) { - var item = pair.Split('='); - searchParams.Add(item[0], item[1]); + var item = pair.Split('=', 2); + searchParams.Add(item[0], item.Length > 1 ? item[1] : string.Empty); } var bundle = await fhirClient.SearchUsingPostAsync(searchParams, searchForm.Resource); var bundleJson = await new FhirJsonSerializer().SerializeToStringAsync(bundle); + CopyCustomHeadersToResponse(); return Ok(bundleJson); } catch (FhirOperationException ex) @@ -454,13 +453,13 @@ public async Task Get([FromBody] string resourcePath) { try { - var httpClient = new HttpClient(_customDecompressionHandler); + using var httpClient = DirectoryHttpClient(); var fhirClient = new FhirClient(resourcePath, httpClient, new FhirClientSettings() { PreferredFormat = ResourceFormat.Json }); - - Console.WriteLine(resourcePath); + var resource = await fhirClient.GetAsync(resourcePath); var resourceJson = await new FhirJsonSerializer().SerializeToStringAsync(resource); + CopyCustomHeadersToResponse(); return Ok(resourceJson); } catch (FhirOperationException ex) @@ -494,6 +493,22 @@ public async Task Get([FromBody] string resourcePath) } } + /// + /// GetSearch, PostSearch and Get go to whatever absolute URL the page sends (a directory, its /metadata), so + /// they skip the session's FhirClientWithUrlProvider and its access token. This pipeline still asks for + /// compression and records the wire sizes, the outgoing request and the elapsed time for the page. + /// + private HttpClient DirectoryHttpClient() + { + var services = HttpContext.RequestServices; + var accessor = services.GetRequiredService(); + + return new HttpClient(new CustomDecompressionHandler(services.GetRequiredService(), accessor) + { + InnerHandler = new RequestCaptureHandler(accessor) { InnerHandler = new HttpClientHandler() } + }); + } + private void CopyCustomHeadersToResponse() { foreach (var kvp in HttpContext.Items.Where(i => i.Key is string key && key.StartsWith("X-"))) diff --git a/Server/Controllers/MetadataController.cs b/Server/Controllers/MetadataController.cs index 6bc9502..3caeb7c 100644 --- a/Server/Controllers/MetadataController.cs +++ b/Server/Controllers/MetadataController.cs @@ -49,7 +49,9 @@ public MetadataController(IUdapClient udapClient, HttpClient httpClient, IOption // get fully validated metadata from .well-known/udap [HttpGet] - public async Task Get([FromQuery] string metadataUrl, [FromQuery] string community) + // probe=true (the Directory page checking each Endpoint) validates without making metadataUrl the session's + // FHIR server, which Patient Search and the access token follow. + public async Task Get([FromQuery] string metadataUrl, [FromQuery] string community, [FromQuery] bool probe = false) { var anchorString = HttpContext.Session.GetString(UdapEdConstants.UDAP_ANCHOR_CERTIFICATE); @@ -83,7 +85,11 @@ public async Task Get([FromQuery] string metadataUrl, [FromQuery] // Show the metadata even when it failed validation, next to the problems found. The UdapClient keeps // only validated metadata in UdapServerMetadata; the response carries what was downloaded. result.UdapServerMetaData = _udapClient.UdapServerMetadata ?? response.UnvalidatedMetadata; - HttpContext.Session.SetString(UdapEdConstants.BASE_URL, metadataUrl); + + if (!probe) + { + HttpContext.Session.SetString(UdapEdConstants.BASE_URL, metadataUrl); + } return Ok(result); } diff --git a/Server/Services/Fhir/RequestCaptureHandler.cs b/Server/Services/Fhir/RequestCaptureHandler.cs index 621c7c4..4d1e8bd 100644 --- a/Server/Services/Fhir/RequestCaptureHandler.cs +++ b/Server/Services/Fhir/RequestCaptureHandler.cs @@ -7,6 +7,7 @@ // */ #endregion +using System.Diagnostics; using System.Text; using System.Text.Json; using UdapEd.Shared; @@ -71,6 +72,16 @@ protected override async Task SendAsync( Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); } - return await base.SendAsync(request, cancellationToken); + // Time the call to the FHIR server alone: this handler is innermost, so the UdapEd hop is not counted. + var stopwatch = Stopwatch.StartNew(); + var response = await base.SendAsync(request, cancellationToken); + stopwatch.Stop(); + + if (httpContext != null) + { + httpContext.Items[UdapEdConstants.FhirClient.FhirElapsedMs] = stopwatch.ElapsedMilliseconds.ToString(); + } + + return response; } } diff --git a/Shared/Components/FhirEditor.razor b/Shared/Components/FhirEditor.razor index 5d94ff5..77506f7 100644 --- a/Shared/Components/FhirEditor.razor +++ b/Shared/Components/FhirEditor.razor @@ -81,9 +81,13 @@ Language = _language, GlyphMargin = false, Value = _editorContent, - ShowFoldingControls = "false", + ShowFoldingControls = "always", AutoDetectHighContrast = false, - + // The editor can start inside a hidden tab; let Monaco track its container's size. + AutomaticLayout = true, + ReadOnly = true, + ScrollBeyondLastLine = false, + WordWrap = "on", }; } @@ -97,8 +101,6 @@ } await UpdateTheme(); - await _editor.Layout(new Dimension() { Height = 600, Width = 200 }); - await JS.InvokeVoidAsync("setMonacoEditorResize", _editor.Id); await _editor.SetValue(_editorContent ?? string.Empty); } diff --git a/Shared/Components/FhirResourceDialog.razor b/Shared/Components/FhirResourceDialog.razor new file mode 100644 index 0000000..fe5c4af --- /dev/null +++ b/Shared/Components/FhirResourceDialog.razor @@ -0,0 +1,250 @@ +@* + Shows one FHIR resource as readable sections, with its JSON alongside. References are links: a resource + already in hand (the search Bundle) opens at once, anything else goes through Resolve. Back walks the trail. +*@ +@using Hl7.Fhir.Model +@using Hl7.Fhir.Serialization +@using Task = System.Threading.Tasks.Task + + + + + @if (_trail.Count > 1) + { + + } + @Current.TypeName + @Title(Current) + @($"{Current.TypeName}/{Current.Id}") + + @if (_error != null) + { + @_error + } + + +
+ @if (Current.Meta is { } meta) + { + + @if (meta.LastUpdated != null) + { + Last updated @meta.LastUpdated.Value.ToString("u") + } + @foreach (var profile in meta.Profile) + { + Profile: @ShortUrl(profile) + } + + } + @Elements(Current, topLevel: true) +
+
+ +
@Json(Current)
+
+
+
+ + Close + +
+ +@code { + [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = null!; + + /// The resource to show first. + [Parameter] public Resource Resource { get; set; } = null!; + + /// Turns a reference into a resource: the search Bundle first, then the directory. + [Parameter] public Func>? Resolve { get; set; } + + /// Display name for a resource; the dialog falls back to the resource id. + [Parameter] public Func? DisplayName { get; set; } + + private readonly List _trail = []; + private string? _error; + + private Resource Current => _trail.Count > 0 ? _trail[^1] : Resource; + + /// Elements that are bookkeeping rather than content; meta is shown in the header line. + private static readonly HashSet SkippedTopLevel = ["id", "meta", "text", "contained", "implicitRules", "language"]; + + protected override void OnInitialized() + { + _trail.Add(Resource); + } + + private string Title(Resource resource) => DisplayName?.Invoke(resource) ?? resource.Id ?? resource.TypeName; + + private void Back() + { + if (_trail.Count > 1) + { + _trail.RemoveAt(_trail.Count - 1); + _error = null; + } + } + + private async Task Follow(string reference) + { + _error = null; + Resource? target = null; + + try + { + target = Resolve == null ? null : await Resolve(reference); + } + catch (Exception ex) + { + _error = $"Could not read {reference}: {ex.Message}"; + return; + } + + if (target == null) + { + _error = $"Could not read {reference}."; + return; + } + + _trail.Add(target); + } + + private static string Json(Resource resource) => + new FhirJsonSerializer(new SerializerSettings { Pretty = true }).SerializeToString(resource); + + private static string ShortUrl(string? url) => + url == null ? string.Empty : url.TrimEnd('/').Split('/').LastOrDefault() ?? url; + + /// The element name, or the extension's name for an extension. + private static string Label(ElementValue child) => + child.Value is Extension extension ? ShortUrl(extension.Url).Replace("base-ext-", string.Empty) : child.ElementName; + + /// The children of an element, grouped by name so repeats sit together. + private RenderFragment Elements(Base node, bool topLevel = false) => __builder => + { + var groups = node.NamedChildren + .Where(c => !topLevel || !SkippedTopLevel.Contains(c.ElementName)) + .GroupBy(Label) + .ToList(); + + + @foreach (var group in groups) + { + + + + + } +
+ @group.Key + + @foreach (var child in group) + { +
@Value(child.Value)
+ } +
+ }; + + /// One value: the common datatypes read as a line, anything else nests. + private RenderFragment Value(object? value) => __builder => + { + switch (value) + { + case null: + break; + case ResourceReference reference: + var label = reference.Display ?? reference.Reference ?? reference.Identifier?.Value ?? "(reference)"; + if (!string.IsNullOrEmpty(reference.Reference)) + { + @label + @if (reference.Display != null) + { + @reference.Reference + } + } + else + { + @label + } + break; + case Extension extension when extension.Value != null && extension.Extension.Count == 0: + @Value(extension.Value) + break; + case Extension extension: + @SubExtensions(extension) + break; + case Coding coding: + @CodingText(coding) + break; + case CodeableConcept concept: + + @(concept.Text ?? string.Join(", ", concept.Coding.Select(CodingText))) + + break; + case Hl7.Fhir.Model.Identifier identifier: + + @identifier.Value + + @(string.Join(" · ", new[] { identifier.Type?.Text ?? identifier.Type?.Coding.FirstOrDefault()?.Code, ShortUrl(identifier.System) }.Where(s => !string.IsNullOrEmpty(s)))) + + + break; + case HumanName name: + + @(name.Text ?? string.Join(" ", name.Prefix.Concat(name.Given).Append(name.Family).Concat(name.Suffix).Where(s => !string.IsNullOrEmpty(s)))) + + break; + case ContactPoint contact: + + @contact.Value + @string.Join(" · ", new[] { contact.System?.ToString(), contact.Use?.ToString() }.Where(s => s != null)) + + break; + case Hl7.Fhir.Model.Address address: + + @(address.Text ?? string.Join(", ", address.Line.Append(address.City).Append(string.Join(" ", new[] { address.State, address.PostalCode }.Where(s => !string.IsNullOrEmpty(s)))).Append(address.Country).Where(s => !string.IsNullOrEmpty(s)))) + + break; + case Period period: + @(period.StartElement?.Value ?? "…") – @(period.EndElement?.Value ?? "ongoing") + break; + case FhirUrl or FhirUri or Canonical when value.ToString() is { } url && url.StartsWith("http", StringComparison.OrdinalIgnoreCase): + @url + break; + case PrimitiveType primitive: + @primitive.ToString() + break; + case Base complex: +
@Elements(complex)
+ break; + default: + @value.ToString() + break; + } + }; + + private static string CodingText(Coding coding) => + coding.Display != null ? $"{coding.Display} ({coding.Code})" : coding.Code ?? string.Empty; + + /// A complex extension read as its sub-extensions, labelled by their short urls. + private RenderFragment SubExtensions(Extension extension) => __builder => + { + + @foreach (var sub in extension.Extension) + { + + + + + } + @if (extension.Value != null) + { + + } +
+ @ShortUrl(sub.Url) + @Value(sub)
@Value(extension.Value)
+ }; +} diff --git a/Shared/Model/FhirResultModel.cs b/Shared/Model/FhirResultModel.cs index 9ad253b..db0022c 100644 --- a/Shared/Model/FhirResultModel.cs +++ b/Shared/Model/FhirResultModel.cs @@ -21,6 +21,8 @@ public class FhirResultModel public Version? Version { get; private set; } public int? FhirCompressedSize { get; set; } public int? FhirDecompressedSize { get; set; } + /// Milliseconds the FHIR server took to answer, timed by UdapEd's server. + public long? FhirElapsedMs { get; set; } public OutgoingRequestInfo? OutgoingRequestInfo { get; set; } // Public flags (kept as fields to match existing signature) diff --git a/Shared/Pages/Directory.razor b/Shared/Pages/Directory.razor index b22573d..f3488d1 100644 --- a/Shared/Pages/Directory.razor +++ b/Shared/Pages/Directory.razor @@ -7,453 +7,458 @@ - - - - - - - - - - - - @foreach (var resource in _supportedResources) - { - @resource - } - - - - - - - - - Search parameter - - - - - - - - - - - - - - @if (_fhirSearch.SearchParams.Any()) - { - - - Search Parameter - Modifier - Value - - - - - - - @{ - var paramDefs = CapabilityLookup.SearchParamMap.SingleOrDefault(m => m.Resource == _fhirSearch.ResourceName)?.ParamDefinitions; - } - @if (paramDefs != null) - { - foreach (var paramDef in paramDefs) - { - @paramDef.Code - } - } - - - - - @if (@context.Name != "active" && @context.Name != "partof") - { - - - @foreach (SearchModifier item in SearchModifierValueSet.SearchModifiers) - { - @item.Name - } - - } - - - @if (context.ModifierName != "Missing") - { - @if (@context.Name != "active") - { - - } - else - { - @(@context.Value) - } - } - - - - - - - - - } - - - - - - - - Includes - - - @foreach (var include in CapabilityLookup.IncludeMap.Where(m => m.Key == _fhirSearch.ResourceName).SelectMany(m => m.Value)) - { - if (!_fhirSearch.Includes.ContainsKey(include)) + + + + + + + + @foreach (var known in KnownDirectories) + { + + @known.Url + @known.Note + + } + + + + + + @foreach (var resource in Resources) + { + @resource + } + + + + + + + + Search parameters + + + @if (_fhirSearch.SearchParams.Any()) + { + + + Parameter + Modifier + Value + + + + + + + @if (_capabilities.IsAdvertised("param", _fhirSearch.ResourceName, paramCode)) { - _fhirSearch.Includes.Add(include, false); + @paramCode } - - - } - - - - - - - - - Reverse Includes - - - @foreach (var revInclude in CapabilityLookup.ReverseIncludeMap.Where(m => m.Key == _fhirSearch.ResourceName).SelectMany(m => m.Value)) - { - if (!_fhirSearch.RevIncludes.ContainsKey(revInclude)) + else { - _fhirSearch.RevIncludes.Add(revInclude, false); + @paramCode (NDH IG) } - - + + + + + + @foreach (SearchModifier item in SearchModifierValueSet.SearchModifiers) + { + @item.Name } - - - - - - - - - - - - - - @($"GET {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}") - - - - - - @if (IsSearching) - { - - Searching - } - else - { - Search - } - - - - - - - - @($"POST {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}/_search") - - - - - - @if (IsSearching) - { - - Searching - } - else - { - Search - } - - - - - - - - - - - - Get - + + + + + + + + + + + } + + + + + + Includes + + + @foreach (var include in _capabilities.IncludesFor(_fhirSearch.ResourceName).Prepend($"{_fhirSearch.ResourceName}:*")) + { + + @IncludeLabel("include", include) + + } + + + + + + + + + Reverse Includes + + + @foreach (var revInclude in _capabilities.RevIncludesFor(_fhirSearch.ResourceName).Prepend("*")) + { + + @IncludeLabel("revinclude", revInclude) + + } + + + + + + @CapabilitiesNote + + + + - + + + + + + @($"GET {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}") + + + + + @if (_isSearching) + { + + Searching + } + else + { + Search + } + + + + + + + + @($"POST {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}/_search") + + + + + @if (_isSearching) + { + + Searching + } + else + { + Search + } + + + + + + - + + + @if (_lastRequest != null) + { + + Sent: @_lastRequest + + @if (!_isSearching && (_fhirResults.HttpStatus != null || _fhirResults.ElapsedMs != null)) + { + + @if (_fhirResults.HttpStatus != null) + { + HTTP @_fhirResults.HttpStatus + } + @if (_fhirResults.ElapsedMs != null) + { + @_fhirResults.ElapsedMs.Value.ToString("N0") ms + } + @if (_fhirResults.Bundle != null) + { + @_fhirResults.Bundle.EntryCount entries + } + + } + + @if (_fhirResults.OutgoingRequest is { } outgoing) + { + + +
@($"{outgoing.Method} {outgoing.Url} HTTP/1.1")
+ @foreach (var header in outgoing.Headers) + { +
@header.Name: @header.Value
+ } + @if (outgoing.Body != null) + { +
@outgoing.Body
+ } +
+
+ } + } @if (_outComeMessage != null) { - @(new MarkupString(_outComeMessage)) + @(new MarkupString(_outComeMessage)) } @if (!_fhirResults.RawFhir.IsNullOrEmpty()) { - - - - @* @if (_fhirResults.Entries != null) *@ - @* { *@ - @* @foreach (var entry in _fhirResults.Entries) *@ - @* { *@ - @* *@ - @*
@_fhirJsonSerializer.SerializeToString(entry)
*@ - @*
*@ - @* } *@ - @* } *@ - - @_fhirSearch.ResourceName List - - + + + + @_fhirSearch.ResourceName + @_fhirResults.Summary + + @if (_fhirResults.Bundle?.FirstUrl is { } first && _fhirResults.Bundle.PreviousUrl != null) + { + First + } + @if (_fhirResults.Bundle?.PreviousUrl is { } previous) + { + Previous + } + @if (_fhirResults.Bundle?.NextUrl is { } next) + { + Next + } + + + @if (_fhirResults.TreeViewStore.Count == 0) + { + No matches. + } + + @{ var presenter = item.Value!; } - + - - - @if (presenter.Link == null) + + @switch (presenter.Type) { - @($"{presenter.Name} ({presenter.ResourceReference})") - } - else - { - - @switch (presenter.Type) - { - case "udap": - - - - - + case ResourceType: + @presenter.Name + @if (presenter.Detail != null) + { + @presenter.Detail + } + @presenter.ResourceReference + break; + + case RelatedType: + + @presenter.Detail: + @presenter.Name + @presenter.ResourceReference + break; + + case UnresolvedType: + + @presenter.ResourceReference + + is not in these results: click to read it, or tick the endpoint include. + + break; + + case EndpointType: + + @presenter.Name + @if (!string.IsNullOrEmpty(presenter.Detail)) + { + @presenter.Detail + } + @presenter.ResourceReference + break; - - View Metadata - + case UdapType: + @if (presenter.IsLoading) + { + + Probing @presenter.Link ... + } + else + { + + + View UDAP metadata + @if (presenter.Untrusted != null && presenter.Untrusted.Any()) { - - @foreach (string note in presenter.Untrusted) - { -
  • @note
  • - } -
    - } - @if (presenter.TokenErrors != null && presenter.TokenErrors.Any()) - { - - @foreach (string note in presenter.TokenErrors) - { -
  • @note
  • - } -
    - } - @if (presenter.Problems != null && presenter.Problems.Any()) - { - - @foreach (string note in presenter.Problems) - { -
  • @note
  • - } -
    - } - - - @if (presenter.IsLoading) - { - - (Validating Metadata...) - } - else if (@presenter.Untrusted != null && @presenter.Untrusted.Any()) - { - Load UDAP Trust anchor - + StartIcon="@Icons.Material.Filled.Upload">Load UDAP Trust anchor } else { - Dynamically register with UDAP - + } - - break; - - case "smart": - - - - - - - SMART: @($" {presenter.Name} (Endpoint/{presenter.Id})") - - - - - View Metadata - + } + break; + + case UdapAbsentType: + No UDAP metadata at @presenter.Link + break; + + case "smart": + + + View SMART configuration + + + break; + + case "x509-mtls-certificate": + + @presenter.MtlsServerCertificate?.TrimForDisplay(30, "...") + @if (presenter.Untrusted != null && presenter.Untrusted.Any()) + { + Load mTLS Trust Anchor + } + else + { + Search + - break; - - case "x509-mtls-certificate": - - - - - - - - mTLS: @($" {presenter.Name} (Endpoint/{presenter.Id})") - - - - @presenter.MtlsServerCertificate?.TrimForDisplay(30, "...") - - @if (presenter.Untrusted != null && presenter.Untrusted.Any()) - { - - - - @foreach (string note in presenter.Untrusted) - { - @note - } - - - - Load mTls Trust Anchor - - } - else - { - Search - - - } - - break; - - default: - - @presenter.Type: @($" {presenter.Name} (Endpoint/{presenter.Id})") - - break; + } + break; - } + default: + @presenter.Type: @presenter.Name (@presenter.ResourceReference) + break; } -
    -
    + @{ + var alerts = new[] + { + (Severity.Error, presenter.Untrusted), + (Severity.Error, presenter.TokenErrors), + (Severity.Info, presenter.Problems) + }; + } + @foreach (var (severity, notes) in alerts) + { + @if (notes != null && notes.Any()) + { + + @foreach (var note in notes) + { +
  • @note
  • + } +
    + } + } +
    -
    -
    - - - - -
    + + + + + }
    - - - -
    +
                 @ex.Message
    -      
    +
    -
    \ No newline at end of file + diff --git a/Shared/Pages/Directory.razor.cs b/Shared/Pages/Directory.razor.cs index 1c5a170..e012141 100644 --- a/Shared/Pages/Directory.razor.cs +++ b/Shared/Pages/Directory.razor.cs @@ -2,7 +2,7 @@ // /* // Authors: // Joseph Shook Joseph.Shook@Surescripts.com -// +// // See LICENSE in the project root for license information. // */ #endregion @@ -20,7 +20,6 @@ using Udap.Common.Extensions; #pragma warning disable SDK0001 // ToTypedElement is experimental in Firely SDK 6 -#pragma warning disable SDK0002 // ToScopedNode is experimental in Firely SDK 6 using Udap.Model; using UdapEd.Shared.Components; using UdapEd.Shared.Extensions; @@ -44,37 +43,74 @@ public partial class Directory [Inject] IMutualTlsService MtlsService { get; set; } = null!; [Inject] private ICapabilityLookup CapabilityLookup { get; set; } = null!; [Inject] public required IDialogService DialogService { get; set; } - [Inject] public HtmlSanitizer HtmlSanitizer { get; set; } + [Inject] public HtmlSanitizer HtmlSanitizer { get; set; } = null!; private ErrorBoundary? _errorBoundary; - private readonly FhirSearch _fhirSearch = new(){BaseUrl = "https://national-directory.fast.hl7.org/fhir"}; + + /// + /// Directories known to answer NDH searches, offered in the Base Url field (any other URL can be typed). + /// The first is the default. Checked 2026-11-29. + /// + private static readonly IReadOnlyList<(string Url, string Note)> KnownDirectories = + [ + ("https://directory.cms.gov/fhir", "CMS National Provider Directory (anonymous search)"), + ("https://ndh-server.fast.hl7.org/fhir", "HL7 NDH reference server, Connectathon 43 (anonymous search)") + ]; + + private const int DefaultPageSize = 20; + private const string ValidStyle = "pre udap-indent-1"; + private const string ResourceType = "resource"; + private const string RelatedType = "related"; + private const string EndpointType = "endpoint"; + private const string UnresolvedType = "unresolved"; + private const string UdapType = "udap"; + private const string UdapAbsentType = "udap-absent"; + private const int MaxConcurrentProbes = 6; + private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(20); + + private readonly FhirSearch _fhirSearch = new() + { + BaseUrl = KnownDirectories[0].Url, + ResourceName = "Organization", + ResultCountPerPage = DefaultPageSize + }; + + private DirectoryCapabilities _igCapabilities = new(); + private DirectoryCapabilities _capabilities = new(); + private string? _capabilitiesLoadedFor; private string _searchString = string.Empty; private string _postSearchString = string.Empty; private List? _postSearchParams; - private const string ValidStyle = "pre udap-indent-1"; - private FhirResults _fhirResults = new FhirResults(); + private FhirResults _fhirResults = new(); private string? _outComeMessage; - private List? _entries; - private FhirJsonSerializer _fhirJsonSerializer = new FhirJsonSerializer(); -/// -/// Hl7.Fhir.Model.ModelInfo.SupportedResources is a source of truth for Resource names -/// -private readonly List _supportedResources = new List() - { - "Practitioner", "PractitionerRole", "Organization", "OrganizationAffiliation", - "InsurancePlan", "Endpoint", "Location" - }; + private Severity _outComeSeverity = Severity.Error; + /// The request the results came from, so it is clear which directory answered. + private string? _lastRequest; + private bool _isSearching; + private IReadOnlyList Resources => + _capabilities.Resources.Count > 0 ? _capabilities.Resources : DirectoryCapabilities.DefaultResources; + + private async T.Task PickDirectory(string url) + { + _fhirSearch.BaseUrl = url; + await BaseUrlChanged(); + } + + private static string? DirectoryNote(string? url) => + KnownDirectories.FirstOrDefault(d => string.Equals(d.Url, url, StringComparison.OrdinalIgnoreCase)).Note; + + private string CapabilitiesNote => + _capabilities.Source != null + ? $"Resources, parameters and includes from {_capabilities.Source}. Greyed options marked (NDH IG) are not listed there and the directory may ignore them." + : "Parameters and includes from the NDH IG (the directory's CapabilityStatement could not be read)."; - /// - /// Method invoked when the component is ready to start, having received its - /// initial parameters from its parent in the render tree. - /// Override this method if you will perform an asynchronous operation and - /// want the component to refresh when that operation is completed. - /// - /// A representing any asynchronous operation. protected override async T.Task OnInitializedAsync() { await CapabilityLookup.Build(); + _igCapabilities = DirectoryCapabilities.From(CapabilityLookup); + _capabilities = _igCapabilities; + BuildSearch(); + await LoadDirectoryCapabilities(); await base.OnInitializedAsync(); } @@ -83,421 +119,575 @@ protected override void OnParametersSet() _errorBoundary?.Recover(); } - private async T.Task AddSearchParam() + private async T.Task BaseUrlChanged() { - var searchParam = new FhirSearchParam(); + await LoadDirectoryCapabilities(); + BuildSearch(); + } - if (_fhirSearch.ResourceName == "Organization") + /// + /// Reads the directory's CapabilityStatement so the page offers the parameters and includes that directory + /// supports. Falls back to the NDH IG's when /metadata cannot be read. + /// + private async T.Task LoadDirectoryCapabilities() + { + var baseUrl = _fhirSearch.BaseUrl?.Trim().TrimEnd('/'); + + if (string.Equals(baseUrl, _capabilitiesLoadedFor, StringComparison.OrdinalIgnoreCase)) { - searchParam = new FhirSearchParam("name", "", null, "FhirLabsOrg"); + return; } - else if (_fhirSearch.ResourceName == "Endpoint") + + _capabilitiesLoadedFor = baseUrl; + _capabilities = _igCapabilities; + + if (!IsHttpAddress(baseUrl)) { - searchParam = new FhirSearchParam("dynamic-registration-trust-profile", "", null, "udap"); + return; } - - if (_fhirSearch.SearchParams.Any()) + try { - var paramLookups = CapabilityLookup.SearchParamMap - .Where(m => m.Resource == _fhirSearch.ResourceName) - .SelectMany(s => s.ParamDefinitions) - .ToList(); + var result = await FhirService.Get($"{baseUrl}/metadata"); - if (!paramLookups.Any()) + if (result.Result is CapabilityStatement capabilityStatement + && string.Equals(baseUrl, _capabilitiesLoadedFor, StringComparison.OrdinalIgnoreCase)) { - return; + _capabilities = DirectoryCapabilities.From(capabilityStatement, $"{baseUrl}/metadata") + .MergedWith(_igCapabilities); } + } + catch (Exception) + { + // Keep the NDH IG capabilities. + } - foreach (var param in paramLookups) - { - if (_fhirSearch.SearchParams.Any(pl => pl.Name == param.Code)) - { - continue; - } - - searchParam.Name = param.Code!; - searchParam.ModifierName = SearchModifierValueSet.SearchModifiers.First().Name; - searchParam.Modifier = SearchModifierValueSet.SearchModifiers.First().Value; - if (searchParam.Name == "active") - { - searchParam.Value = "true"; - } - else if(searchParam.Value != "FhirLabsOrg") - { - searchParam.Value = string.Empty; - } - - break; - } + if (!Resources.Contains(_fhirSearch.ResourceName)) + { + _fhirSearch.ResourceName = Resources.FirstOrDefault() ?? string.Empty; + _fhirSearch.ResetParameters(); } - searchParam.Id = _fhirSearch.SearchParams.Any() ? _fhirSearch.SearchParams.Max(sp => sp.Id) + 1 : 0; - _fhirSearch.SearchParams.Add(searchParam); + StateHasChanged(); + } - await T.Task.Delay(1); + private void ResourceChanged() + { + _fhirSearch.ResetParameters(); BuildSearch(); } + private T.Task> SearchParamNames(string? text, CancellationToken token) => + T.Task.FromResult(_capabilities.SearchParamsFor(_fhirSearch.ResourceName) + .OrderByDescending(code => _capabilities.IsAdvertised("param", _fhirSearch.ResourceName, code)) + .ThenBy(code => code, StringComparer.Ordinal) + .Where(code => string.IsNullOrWhiteSpace(text) || code.Contains(text, StringComparison.OrdinalIgnoreCase))); + + private void AddSearchParam() + { + // A new row starts blank, except for the first row of a resource with an obvious first parameter. + // Guessing the directory's first listed parameter picked unhelpful ones (PractitionerRole: practitioner, date). + var used = _fhirSearch.SearchParams.Select(p => p.Name).ToHashSet(); + var name = DefaultParam(_fhirSearch.ResourceName) is { } preferred && !used.Contains(preferred.Name) + ? preferred + : (string.Empty, null); + + _fhirSearch.SearchParams.Add(new FhirSearchParam(name.Name, string.Empty, null, name.Value ?? string.Empty) + { + Id = _fhirSearch.SearchParams.Count == 0 ? 0 : _fhirSearch.SearchParams.Max(sp => sp.Id) + 1 + }); + + BuildSearch(); + } + + /// The first parameter worth offering per resource. + private static (string Name, string? Value)? DefaultParam(string resource) => resource switch + { + "Organization" or "Practitioner" or "Location" or "HealthcareService" or "InsurancePlan" => ("name", null), + // NDH STU2 dropped the dynamic-registration-trust-profile search parameter. UDAP support is found by + // probing each endpoint's .well-known/udap, so start from the FHIR endpoints. + "Endpoint" => ("connection-type", "hl7-fhir-rest"), + _ => null + }; + private void DeleteParam(FhirSearchParam fhirSearchParam) { - _fhirSearch.SearchParams?.Remove(fhirSearchParam); + _fhirSearch.SearchParams.Remove(fhirSearchParam); BuildSearch(); - StateHasChanged(); } - - private void ActiveModifierChanged(bool obj) + + private static bool IncludeChecked(Dictionary map, string key) => map.GetValueOrDefault(key); + + /// + /// Wildcards (Resource:*, *) and what the directory advertises read plainly; options known only + /// from the NDH IG are greyed and tagged, since the directory may ignore them. + /// + private RenderFragment IncludeLabel(string kind, string value) => builder => + { + var plain = value.EndsWith('*') || _capabilities.IsAdvertised(kind, _fhirSearch.ResourceName, value); + builder.OpenElement(0, "span"); + if (!plain) + { + builder.AddAttribute(1, "class", "mud-text-secondary"); + builder.AddAttribute(2, "title", "In the NDH IG; this directory's CapabilityStatement does not list it"); + } + builder.AddContent(3, plain ? value : $"{value} (NDH IG)"); + builder.CloseElement(); + }; + + private void SetInclude(Dictionary map, string key, bool value) { + map[key] = value; BuildSearch(); } private void BuildSearch() { - _searchString = string.Empty; - _postSearchString = string.Empty; - var queryParameters = new List(); + var parameters = _fhirSearch.SearchParams + .Select(p => (Name: p.Name ?? string.Empty, + Modifier: SearchModifierValueSet.SearchModifiers.Find(sm => sm.Name == p.ModifierName)?.Value, + p.Value)) + .ToList(); + var includes = _fhirSearch.Includes.Where(i => i.Value).Select(i => i.Key).ToList(); + var revIncludes = _fhirSearch.RevIncludes.Where(i => i.Value).Select(i => i.Key).ToList(); + + _searchString = DirectoryQuery.Build(parameters, includes, revIncludes, _fhirSearch.ResultCountPerPage); + + // The POST form carries raw values: the server form-encodes them. + _postSearchParams = parameters + .Where(p => !string.IsNullOrWhiteSpace(p.Name)) + .Select(p => $"{(string.IsNullOrEmpty(p.Modifier) ? p.Name : $"{p.Name}:{p.Modifier}")}={p.Value}") + .Concat(includes.Select(i => $"_include={i}")) + .Concat(revIncludes.Select(i => $"_revinclude={i}")) + .Concat(_fhirSearch.ResultCountPerPage > 0 ? [$"_count={_fhirSearch.ResultCountPerPage}"] : []) + .ToList(); + _postSearchString = string.Join("\n", _postSearchParams); + } - foreach (var param in _fhirSearch.SearchParams) + private void PageSizeChanged(int size) + { + _fhirSearch.ResultCountPerPage = size; + BuildSearch(); + } + + private void BuildManualPostSearch(string text) + { + _postSearchParams = text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList(); + } + + /// + /// The GET box takes a query, Resource?query or a full URL pasted from a directory's documentation. + /// A pasted base URL or resource replaces the page's. + /// + private async T.Task ResolveGetUrl() + { + var parsed = DirectoryQuery.Parse(_searchString); + + if (parsed.BaseUrl != null + && !string.Equals(parsed.BaseUrl, _fhirSearch.BaseUrl?.TrimEnd('/'), StringComparison.OrdinalIgnoreCase)) { - var modifier = SearchModifierValueSet.SearchModifiers.Find(sm => sm.Name == param.ModifierName)?.Value; - queryParameters.Add($"{param.Name}{modifier.Prefix(":")}={param.Value}"); - + _fhirSearch.BaseUrl = parsed.BaseUrl; + await LoadDirectoryCapabilities(); } - foreach (var include in _fhirSearch.Includes.Where(i => i.Value)) + if (parsed.ResourceName != null && parsed.ResourceName != _fhirSearch.ResourceName) { - queryParameters.Add($"_include={include.Key}"); + // The parameter table described the old resource; the pasted query is what runs. + _fhirSearch.ResourceName = parsed.ResourceName; + _fhirSearch.ResetParameters(); } - foreach (var revInclude in _fhirSearch.RevIncludes.Where(i => i.Value)) + _searchString = parsed.Query; + + if (string.IsNullOrWhiteSpace(_fhirSearch.BaseUrl) || string.IsNullOrWhiteSpace(_fhirSearch.ResourceName)) { - queryParameters.Add($"_revinclude={revInclude.Key}"); + _outComeMessage = "Pick a directory base URL and a resource, or paste a full search URL."; + return null; } - _searchString = string.Join('&', queryParameters); - _postSearchString = string.Join("\n", queryParameters); - _postSearchParams = queryParameters; - + return DirectoryQuery.Url(_fhirSearch.BaseUrl, _fhirSearch.ResourceName, parsed.Query); } - private void BuildManualGetSearch(string obj) + private async T.Task SearchGet() { - _searchString = obj; - } + var url = await ResolveGetUrl(); - private void BuildManualPostSearch(string obj) - { - _postSearchParams = obj.Split("\n").ToList(); + if (url != null) + { + await RunSearch($"GET {url}", () => FhirService.SearchGet(url)); + } } - private bool IsSearching = false; + private T.Task SearchPost() => + RunSearch($"POST {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}/_search", () => FhirService.SearchPost(new SearchForm + { + Url = _fhirSearch.BaseUrl, + Resource = _fhirSearch.ResourceName, + FormUrlEncoded = _postSearchParams ?? [] + })); - private async T.Task SearchGet() + /// Follows a Bundle paging link (next, previous, first) exactly as the server gave it. + private T.Task GoToPage(string url) => RunSearch($"GET {url}", () => FhirService.SearchGet(url)); + + private async T.Task RunSearch(string request, Func>> search) { - IsSearching = true; + _isSearching = true; + _lastRequest = request; + _fhirResults = new FhirResults(); + _outComeMessage = null; + _outComeSeverity = Severity.Error; + StateHasChanged(); + try { - _fhirResults = new FhirResults(); - - StateHasChanged(); - await T.Task.Delay(100); - - var result = - await FhirService.SearchGet($" {_fhirSearch.BaseUrl}/{_fhirSearch.ResourceName}?{_searchString}"); - await SearchHandler(result); - StateHasChanged(); - await AugmentHandler(); + await SearchHandler(await search()); + } + catch (Exception ex) + { + _outComeMessage = HtmlSanitizer.Sanitize(ex.Message); } finally { - IsSearching = false; + _isSearching = false; } + + StateHasChanged(); + await AugmentHandler(); } - - private async T.Task SearchPost() - { - IsSearching = true; - try - { - _fhirResults = new FhirResults(); - - StateHasChanged(); - await T.Task.Delay(100); - var formSearch = new SearchForm() - { - Url = _fhirSearch.BaseUrl, - Resource = _fhirSearch.ResourceName, - FormUrlEncoded = _postSearchParams - }; + private async T.Task SearchHandler(FhirResultModel result) + { + // What went over the wire, kept for errors as well as results. + _fhirResults.CompressedSize = result.FhirCompressedSize; + _fhirResults.DecompressedSize = result.FhirDecompressedSize; + _fhirResults.ElapsedMs = result.FhirElapsedMs; + _fhirResults.OutgoingRequest = result.OutgoingRequestInfo; - var result = await FhirService.SearchPost(formSearch); - await SearchHandler(result); - StateHasChanged(); - await AugmentHandler(); - } - finally + if (result.HttpStatusCode != null) { - IsSearching = false; + _fhirResults.HttpStatus = $"{(int)result.HttpStatusCode} {result.HttpStatusCode}"; } - } - private async T.Task SearchHandler(FhirResultModel result) - { if (result.UnAuthorized) { - _outComeMessage = HttpStatusCode.Unauthorized.ToString(); + _outComeMessage = $"{HttpStatusCode.Unauthorized}. This directory needs an access token: get one on the B2B page first."; + return; } - else if (result.HttpStatusCode == HttpStatusCode.PreconditionFailed) + + if (result.HttpStatusCode == HttpStatusCode.PreconditionFailed) { - // await DiscoveryService.SetBaseFhirUrl(AppState.BaseUrl); _outComeMessage = "PreconditionFailed"; + return; } - else if (result.OperationOutcome != null) + if (result.OperationOutcome != null) { - _fhirResults.Entries = null; - string? errorMessage = null; - - foreach (var issue in result.OperationOutcome.Issue) + // A directory that ignores a parameter answers 200 with a warning and no matches (the CMS NPD does). + _outComeSeverity = result.OperationOutcome.Issue.All(i => + i.Severity is OperationOutcome.IssueSeverity.Warning or OperationOutcome.IssueSeverity.Information) + ? Severity.Warning + : Severity.Error; + _outComeMessage = string.Concat(result.OperationOutcome.Issue.Select(issue => + $"{issue.Severity}: {HtmlSanitizer.Sanitize(issue.Diagnostics ?? issue.Details?.Text)} ({issue.Code})
    ")); + + if (result.OperationOutcome.Issue.Any(i => i.Diagnostics?.Contains("_include", StringComparison.Ordinal) == true)) { - errorMessage += $"Error:: Details: {issue.Details?.Text}.
    " - + $"Diagnostics: {HtmlSanitizer.Sanitize(issue.Diagnostics)}.
    " - + $"IssueType: {issue.Code}.
    "; + _outComeMessage += "An _include or _revinclude names a resource and a search parameter, " + + "e.g. PractitionerRole:practitioner, or every reference with PractitionerRole:*."; } - _outComeMessage = errorMessage; + return; } - else + + if (result.Result == null) { - _outComeMessage = null; + return; + } - if (result.HttpStatusCode != null) - { - _fhirResults.HttpStatus = $"HTTP/{result.Version} {(int)result.HttpStatusCode} {result.HttpStatusCode}"; - } + _fhirResults.RawFhir = await new FhirJsonSerializer(new SerializerSettings { Pretty = true }) + .SerializeToStringAsync(result.Result); + var bundle = new DirectoryBundle(result.Result, _fhirSearch.ResourceName); + _fhirResults.Bundle = bundle; - if (result.Result != null) - { - _fhirResults.RawFhir = await new FhirJsonSerializer() - .SerializeToStringAsync(result.Result); + foreach (var match in bundle.Matches) + { + _fhirResults.TreeViewStore.Add(match is Endpoint endpoint + ? await EndpointNode(endpoint, bundle) + : await ResourceNode(match, bundle)); + } + } - var scopeNode = result.Result.ToTypedElement().ToScopedNode(); - var references = scopeNode.Select( - "Bundle.entry.resource.descendants().select(reference)"); + /// A matched resource with its endpoints and the related resources the search included. + private async T.Task> ResourceNode(Resource match, DirectoryBundle bundle) + { + var node = new TreeItemData(match.Id, bundle.DisplayName(match), DirectoryBundle.Reference(match), + type: ResourceType, isLoading: false, detail: NpiDetail(match)); + var children = new List>(); + var (endpoints, unresolved) = bundle.EndpointsOf(match); - if (_fhirSearch.ResourceName == "Endpoint") - { - var endpoints = - scopeNode.Select( - $"Bundle.entry.resource.select($this).where($this is Endpoint)"); - await BuildTreeviewForEndpoints(endpoints); - return; - } + foreach (var endpoint in endpoints) + { + children.Add(await EndpointNode(endpoint, bundle)); + } - var treeChildren = new List>(); - foreach (var referenceContext in scopeNode.Select($"Bundle.entry.resource.where($this.is ({_fhirSearch.ResourceName}))")) - { - var domainResource = referenceContext.ToPoco(); - var nameElement = domainResource.ToTypedElement().Children("name").FirstOrDefault(); - var resource = referenceContext.ToPoco(); - var orgEntry = new TreeItemData(nameElement?.Value?.ToString() ?? resource?.Id ?? "Unknown", resource?.Id ?? "Unknown", $"{resource?.TypeName}/{resource?.Id}"); + foreach (var reference in unresolved) + { + children.Add(new TreeItemData(reference, reference, reference, type: UnresolvedType, isLoading: false)); + } - treeChildren.Add(orgEntry); - } - _fhirResults.TreeViewStore.Children = treeChildren; - - foreach (var referenceItem in references) - { - //Organization/FhirLabsOrg - var parentReferencedId = - scopeNode.Select( - $"Bundle.entry.where($this.resource is {_fhirSearch.ResourceName} and $this.fullUrl.endsWith('{referenceItem.Value}')).resource.id"); - - foreach (var typedElement in parentReferencedId) - { - - var parentEntry = _fhirResults.TreeViewStore.Children?.FirstOrDefault(tv => tv.Value?.Id == typedElement.Value as string) as TreeItemData; - - // Get Endpoint addresses - var endpoints = - scopeNode.Select( - $"Bundle.entry.resource.select($this).where($this is Endpoint and $this.descendants().reference.endsWith('{_fhirSearch.ResourceName}/{typedElement.Value}'))"); - - await BuildTreeviewForEndpoints(endpoints, parentEntry); - } - } + foreach (var (relation, related) in bundle.RelatedTo(match)) + { + children.Add(new TreeItemData(related.Id, bundle.DisplayName(related), DirectoryBundle.Reference(related), + type: RelatedType, isLoading: false, detail: relation)); + } - _fhirResults.Entries = result.Result?.Entry - .Where(e => e.Resource != null) - .Select(e => e) - .ToList(); - } - else - { - _fhirResults.RawFhir = string.Empty; - } + if (children.Count > 0) + { + node.Children = children; } + + return node; } - private async T.Task BuildTreeviewForEndpoints(IEnumerable endpoints, TreeItemData? parentEntry = null) + /// Opens a result in the resource viewer, which follows further references the same way. + private async T.Task OpenResource(string reference) { - var treeStore = parentEntry ?? _fhirResults.TreeViewStore; - var storeChildren = (treeStore.Children as List>) ?? new List>(); + var resource = await ResolveReference(reference); - foreach (var endpoint in endpoints) + if (resource == null) { - var endpointResource = endpoint.ToPoco(); - if (storeChildren.Any(ts => ts.Value?.Id == endpointResource.Id)) - { - return; - } + _outComeSeverity = Severity.Warning; + _outComeMessage = $"Could not read {HtmlSanitizer.Sanitize(reference)}."; + return; + } - var endPointTreeItem = new TreeItemData(endpointResource.Id, endpointResource.Name, $"{endpointResource?.TypeName}/{endpointResource?.Id}"); - var endpointChildren = new List>(); + var parameters = new DialogParameters + { + { d => d.Resource, resource }, + { d => d.Resolve, ResolveReference }, + { d => d.DisplayName, r => _fhirResults.Bundle?.DisplayName(r) ?? new DirectoryBundle(new Bundle(), null).DisplayName(r) } + }; - storeChildren.Add(endPointTreeItem); + await DialogService.ShowAsync(null, parameters, new DialogOptions + { + MaxWidth = MaxWidth.Large, FullWidth = true, CloseButton = true, CloseOnEscapeKey = true + }); + } - var dynamicEndpointTypes = endpointResource.ToTypedElement().Select( - $"extension.where($this.url in 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-dynamicRegistration').descendants().select($this.descendants().coding.code)"); + /// + /// A reference from the results: taken from the search Bundle when it is there, otherwise read from the + /// directory (relative references resolve against the Base Url). + /// + private async T.Task ResolveReference(string reference) + { + if (_fhirResults.Bundle?.Resolve(reference) is { } inBundle) + { + return inBundle; + } + if (reference.StartsWith('#')) + { + return null; + } - foreach (var dynamicEndpointType in dynamicEndpointTypes) - { - if (dynamicEndpointType.Value?.ToString() == "udap") - { - endpointChildren.Add(new TreeItemData( - id: endpointResource.Id, - name: endpointResource.Name, - resourceReference: $"{endpointResource?.TypeName}/{endpointResource?.Id}", - icon: Icons.Material.TwoTone.DynamicForm, - iconColor: Color.Error, - link: AppendUdapWellKnown(endpointResource.Address), - type: dynamicEndpointType.Value?.ToString() - )); - } + var url = Uri.TryCreate(reference, UriKind.Absolute, out _) + ? reference + : $"{_fhirSearch.BaseUrl.Trim().TrimEnd('/')}/{reference.TrimStart('/')}"; + var result = await FhirService.Get(url); - if (dynamicEndpointType.Value?.ToString() == "smart") - { - var results = - await MetadataService.GetSmartMetadata( - $"{endpointResource.Address.EnsureTrailingSlash()}.well-known/smart-configuration", default); - - endpointChildren.Add(new TreeItemData( - endpointResource.Id, - endpointResource.Name, - $"{endpointResource?.TypeName}/{endpointResource?.Id}", - Icons.Material.TwoTone.SmartDisplay, - results == null ? Color.Error : Color.Success, - endpointResource.Address, - dynamicEndpointType.Value?.ToString())); - } - } + return result.Result is OperationOutcome ? null : result.Result; + } + private static string? NpiDetail(Resource resource) + { + var npis = DirectoryBundle.Npis(resource).ToList(); + return npis.Count == 0 ? null : $"NPI {string.Join(", ", npis)}"; + } - var mTlsEndpointTypes = endpointResource.ToTypedElement().Select( - $"extension.where($this.url = 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-secureExchangeArtifacts').select($this.where($this.descendants().coding.code in 'x509-mtls-certificate'))"); + /// + /// An Endpoint with what can be learned about its security: every http(s) address gets a UDAP node that + /// resolves by probing {address}/.well-known/udap. NDH STU2 removed the + /// extensions that used to say so; the STU1 ones are still read for directories that carry them. + /// + private async T.Task> EndpointNode(Endpoint endpoint, DirectoryBundle bundle) + { + var detail = string.Join(" · ", new[] + { + endpoint.ConnectionType?.Code, + endpoint.Status is { } status && status != Endpoint.EndpointStatus.Active ? status.ToString().ToLowerInvariant() : null, + endpoint.Name != null ? endpoint.Address : null + }.Where(s => !string.IsNullOrEmpty(s))); + var node = new TreeItemData(endpoint.Id, bundle.DisplayName(endpoint), DirectoryBundle.Reference(endpoint), + link: endpoint.Address, type: EndpointType, isLoading: false, detail: detail); + var children = new List>(); - foreach (var mTlsEndpointType in mTlsEndpointTypes) - { - var mtlsEncodeCertificate = GetMtlsServerCertificate(mTlsEndpointType); - var notifications = await MtlsService.VerifyMtlsTrust(mtlsEncodeCertificate); - - endpointChildren.Add(new TreeItemData( - endpointResource.Id, - endpointResource.Name, - $"{endpointResource?.TypeName}/{endpointResource?.Id}", - Icons.Material.TwoTone.DynamicForm, - notifications != null && notifications.Any() ? Color.Error : Color.Success, - endpointResource.Address, - mTlsEndpointType.Select("extension.descendants().coding.code").First().Value?.ToString(), - null, - notifications, - null, - null, - mtlsEncodeCertificate - )); - } + if (IsHttpAddress(endpoint.Address)) + { + children.Add(new TreeItemData( + id: endpoint.Id, + name: endpoint.Name ?? endpoint.Address, + resourceReference: DirectoryBundle.Reference(endpoint), + icon: Icons.Material.TwoTone.DynamicForm, + iconColor: Color.Default, + link: AppendUdapWellKnown(endpoint.Address), + type: UdapType)); + } + + await AddLegacyExtensionNodes(endpoint, children); + + if (children.Count > 0) + { + node.Children = children; + } + + return node; + } - if (endpointChildren.Count > 0) + /// NDH STU1 extensions: base-ext-dynamicRegistration (SMART) and the mTLS certificate. + private async T.Task AddLegacyExtensionNodes(Endpoint endpoint, List> children) + { + var typed = endpoint.ToTypedElement(); + var dynamicEndpointTypes = typed.Select( + "extension.where($this.url in 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-dynamicRegistration').descendants().select($this.descendants().coding.code)"); + + foreach (var dynamicEndpointType in dynamicEndpointTypes) + { + if (dynamicEndpointType.Value?.ToString() != "smart") { - endPointTreeItem.Children = endpointChildren; + continue; } + var results = await MetadataService.GetSmartMetadata( + $"{endpoint.Address.EnsureTrailingSlash()}.well-known/smart-configuration", default); - // var nondynamicEndpointTypes = endpointResource.ToTypedElement().Select( - // $"extension.where($this.url != 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-dynamicRegistration').descendants().select($this.descendants().coding.code)"); - // - // foreach (var nonDynamicEndpointType in nondynamicEndpointTypes) - // { - // endPointTreeItem.TreeItems.Add(new FhirHierarchyEntries() - // { - // Id = endpointResource.Id, - // Name = endpointResource.Name, - // Link = endpointResource.Address, - // Type = nonDynamicEndpointType.Value?.ToString(), - // // IconColor = Color.Default, - // // Icon = Icons.Material.TwoTone.Link - // }); - // } + children.Add(new TreeItemData(endpoint.Id, endpoint.Name ?? endpoint.Address, DirectoryBundle.Reference(endpoint), + Icons.Material.TwoTone.SmartDisplay, + results == null ? Color.Error : Color.Success, + endpoint.Address, + "smart", + isLoading: false)); + } + + var mTlsEndpointTypes = typed.Select( + "extension.where($this.url = 'http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-secureExchangeArtifacts').select($this.where($this.descendants().coding.code in 'x509-mtls-certificate'))"); + + foreach (var mTlsEndpointType in mTlsEndpointTypes) + { + var certificate = GetMtlsServerCertificate(mTlsEndpointType); + var notifications = certificate == null ? null : await MtlsService.VerifyMtlsTrust(certificate); + + children.Add(new TreeItemData(endpoint.Id, endpoint.Name ?? endpoint.Address, DirectoryBundle.Reference(endpoint), + Icons.Material.TwoTone.DynamicForm, + notifications != null && notifications.Any() ? Color.Error : Color.Success, + endpoint.Address, + mTlsEndpointType.Select("extension.descendants().coding.code").First().Value?.ToString(), + null, + notifications, + null, + null, + certificate, + isLoading: false)); } - treeStore.Children = storeChildren; } + /// + /// Probes .well-known/udap for every UDAP node still loading, at any depth of the tree. Nodes that share an + /// address (an endpoint shared by two organizations) are probed once. The tree re-renders as each probe finishes. + /// private async T.Task AugmentHandler() { - if (_fhirResults.TreeViewStore.Children != null) + var probesByLink = Flatten(_fhirResults.TreeViewStore) + .Select(item => item.Value) + .OfType() + .Where(entry => entry is { IsLoading: true, Type: UdapType, Link: not null }) + .GroupBy(entry => entry.Link!, StringComparer.OrdinalIgnoreCase) + .ToList(); + + if (probesByLink.Count == 0) { - var tasks = _fhirResults.TreeViewStore.Children.Where(c => - c.Children != null && c.Children.Any()) - .SelectMany(c => c.Children) - .Where(treeItemData => treeItemData.Value != null - && treeItemData.Value.IsLoading - && treeItemData.Value.Type == "udap") - .Select(async treeItemData => - { - var fhirHierarchyEntry = treeItemData.Value; - - if(fhirHierarchyEntry == null) - { - return; - } + return; + } - await T.Task.Yield(); - var results = await MetadataService.GetUdapMetadataVerificationModel( - $"{fhirHierarchyEntry.Link}", null, default); - - if (results == null) - { - return; - } - - fhirHierarchyEntry.IsLoading = false; - fhirHierarchyEntry.UdapMetadata = results; - fhirHierarchyEntry.Untrusted = results.Untrusted; - fhirHierarchyEntry.TokenErrors = results.TokenErrors; - fhirHierarchyEntry.Problems = results.Problems; - }); - await T.Task.WhenAll(tasks); + using var throttle = new SemaphoreSlim(MaxConcurrentProbes); + + await T.Task.WhenAll(probesByLink.Select(async group => + { + await throttle.WaitAsync(); + MetadataVerificationModel? result; + try + { + result = await ProbeUdap(group.Key); + } + finally + { + throttle.Release(); + } + + foreach (var entry in group) + { + ApplyProbeResult(entry, result); + } + + await InvokeAsync(StateHasChanged); + })); + } + + private async T.Task ProbeUdap(string link) + { + using var timeout = new CancellationTokenSource(ProbeTimeout); + try + { + return await MetadataService.ProbeUdapMetadata(link, timeout.Token); + } + catch (OperationCanceledException) + { + return null; } } - private string? AppendUdapWellKnown(string endpointResourceAddress) + private static void ApplyProbeResult(FhirHierarchyEntry entry, MetadataVerificationModel? result) { - if (!endpointResourceAddress.Contains(UdapConstants.Discovery.DiscoveryEndpoint)) + entry.IsLoading = false; + + if (!PublishesUdap(result?.UdapServerMetaData)) { - return endpointResourceAddress.EnsureTrailingSlash() + UdapConstants.Discovery.DiscoveryEndpoint; + entry.Type = UdapAbsentType; + return; } - return endpointResourceAddress; + entry.UdapMetadata = result; + entry.Untrusted = result!.Untrusted; + entry.TokenErrors = result.TokenErrors; + entry.Problems = result.Problems; } + /// + /// A 200 that is not UDAP metadata (an HTML page, an OperationOutcome) can still deserialize into an empty + /// . Count it as UDAP only when it names a UDAP version or carries signed metadata. + /// + private static bool PublishesUdap(UdapMetadata? metadata) => + metadata != null + && (metadata.UdapVersionsSupported?.Count > 0 || !string.IsNullOrEmpty(metadata.SignedMetadata)); + + private static IEnumerable> Flatten( + IEnumerable>? items) => + items?.SelectMany(item => Flatten(item.Children).Prepend(item)) ?? []; + + private static bool IsHttpAddress(string? address) => + Uri.TryCreate(address, UriKind.Absolute, out var uri) + && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp); + + private static string AppendUdapWellKnown(string endpointResourceAddress) => + endpointResourceAddress.Contains(UdapConstants.Discovery.DiscoveryEndpoint) + ? endpointResourceAddress + : endpointResourceAddress.EnsureTrailingSlash() + UdapConstants.Discovery.DiscoveryEndpoint; + private static string? GetMtlsServerCertificate(ITypedElement mTlsEndpointType) { try { - return mTlsEndpointType.Select("extension.where(url = 'certificate').value").FirstOrDefault().Value.ToString(); + return mTlsEndpointType.Select("extension.where(url = 'certificate').value").FirstOrDefault()?.Value?.ToString(); } catch { return "Can't parse"; } } @@ -526,16 +716,17 @@ private async T.Task OpenUdapAnchorDialogAsync() public class TreeItemData : TreeItemData { - public TreeItemData(string id, string name, + public TreeItemData(string id, string name, string resourceReference, string? icon = null, Color? iconColor = null, - string? link = null, string? type = null, - MetadataVerificationModel? metadata = null, + string? link = null, string? type = null, + MetadataVerificationModel? metadata = null, List? untrusted = null, List? tokenErrors = null, List? problems = null, string? mtlCertificate = null, - bool isLoading = true) : base(new FhirHierarchyEntry()) + bool isLoading = true, + string? detail = null) : base(new FhirHierarchyEntry()) { Value!.Id = id; Value.Name = name; @@ -550,55 +741,56 @@ public TreeItemData(string id, string name, Value.Problems = problems; Value.MtlsServerCertificate = mtlCertificate; Value.IsLoading = isLoading; + Value.Detail = detail; + Expanded = true; } } public record FhirHierarchyEntry { - public string Id; - public string Name; - public string ResourceReference; + public string Id = string.Empty; + public string Name = string.Empty; + public string ResourceReference = string.Empty; public string? Type; public string? Link; + public string? Detail; public bool IsLoading { get; set; } = true; public string? Icon { get; set; } public Color IconColor { get; set; } = Color.Warning; - public string? Metadata { get; set; } - - public List? Untrusted { get; set; } = null; - public List? TokenErrors { get; set; } = null; - public List? Problems { get; set; } = null; - public MetadataVerificationModel? UdapMetadata { get; set; } = null; + public List? Untrusted { get; set; } + public List? TokenErrors { get; set; } + public List? Problems { get; set; } + public MetadataVerificationModel? UdapMetadata { get; set; } public string? MtlsServerCertificate { get; set; } } - - record FhirResults + private sealed class FhirResults { - public string HttpStatus { get; set; } - public string RawFhir { get; set; } - public List? Entries { get; set; } - public TreeItemData TreeViewStore = new () { Children = new List>() }; - } - - - public class ObjectToFhirBoolConverter : IReversibleConverter - { - public bool? Convert(string input) + public string? HttpStatus { get; set; } + public int? CompressedSize { get; set; } + public int? DecompressedSize { get; set; } + public long? ElapsedMs { get; set; } + public OutgoingRequestInfo? OutgoingRequest { get; set; } + public string? RawFhir { get; set; } + public DirectoryBundle? Bundle { get; set; } + public List> TreeViewStore { get; } = []; + + public string Summary { - return input switch + get { - "true" => true, - "false" => false, - _ => null - }; - } + if (Bundle == null) + { + return string.Empty; + } - public string ConvertBack(bool? input) - { - return input == true ? "true" : "false"; + var count = Bundle.Matches.Count; + var total = Bundle.Total is { } t ? $" of {t}" : string.Empty; + var more = Bundle.NextUrl != null ? ", more on the next page" : string.Empty; + return $"{count}{total} matches on this page{more}"; + } } } } diff --git a/Shared/Search/DirectoryBundle.cs b/Shared/Search/DirectoryBundle.cs new file mode 100644 index 0000000..781db51 --- /dev/null +++ b/Shared/Search/DirectoryBundle.cs @@ -0,0 +1,262 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using Hl7.Fhir.Model; + +namespace UdapEd.Shared.Search; + +/// +/// One page of directory search results, indexed so that references resolve to the resources in the Bundle. +/// Endpoints are linked in both directions: forward (Organization.endpoint, PractitionerRole.endpoint, +/// ...) and backward (Endpoint.managingOrganization). Directories differ in which side they fill in: the +/// CMS NPD only fills the forward side. +/// +public sealed class DirectoryBundle +{ + public const string NpiSystem = "http://hl7.org/fhir/sid/us-npi"; + + private readonly Dictionary _byReference = new(StringComparer.Ordinal); + private readonly List _resources = []; + + public DirectoryBundle(Bundle bundle, string? searchedResource) + { + foreach (var entry in bundle.Entry.Where(e => e.Resource != null)) + { + var resource = entry.Resource; + _resources.Add(resource); + _byReference.TryAdd(Reference(resource), resource); + + if (!string.IsNullOrEmpty(entry.FullUrl)) + { + _byReference.TryAdd(entry.FullUrl, resource); + } + } + + var anyMode = bundle.Entry.Any(e => e.Search?.Mode != null); + Matches = bundle.Entry + .Where(e => e.Resource != null && e.Resource is not OperationOutcome) + .Where(e => anyMode + ? e.Search?.Mode == Bundle.SearchEntryMode.Match + : e.Resource.TypeName == searchedResource) + .Select(e => e.Resource) + .ToList(); + + Total = bundle.Total; + EntryCount = bundle.Entry.Count; + NextUrl = LinkUrl(bundle, "next"); + PreviousUrl = LinkUrl(bundle, "previous") ?? LinkUrl(bundle, "prev"); + FirstUrl = LinkUrl(bundle, "first"); + } + + public IReadOnlyList Matches { get; } + public int? Total { get; } + /// All entries on the page: matches, includes and outcomes. + public int EntryCount { get; } + public string? NextUrl { get; } + public string? PreviousUrl { get; } + public string? FirstUrl { get; } + + public static string Reference(Resource resource) => $"{resource.TypeName}/{resource.Id}"; + + /// + /// Resolves a relative (Endpoint/123) or absolute reference against the Bundle. Absolute references + /// fall back to their last two path segments, since servers mix the two forms. + /// + public Resource? Resolve(string? reference) + { + if (string.IsNullOrEmpty(reference)) + { + return null; + } + + if (_byReference.TryGetValue(reference, out var resource)) + { + return resource; + } + + var relative = RelativeReference(reference); + return relative != null && _byReference.TryGetValue(relative, out resource) ? resource : null; + } + + /// The endpoints a resource points at that are in the Bundle, plus the references that are not. + public (List Resolved, List Unresolved) EndpointsOf(Resource resource) + { + var resolved = new List(); + var unresolved = new List(); + + foreach (var reference in EndpointReferences(resource)) + { + if (Resolve(reference) is Endpoint endpoint) + { + resolved.Add(endpoint); + } + else + { + unresolved.Add(reference); + } + } + + var self = Reference(resource); + resolved.AddRange(_resources.OfType() + .Where(e => SameReference(e.ManagingOrganization?.Reference, self))); + + return (resolved.DistinctBy(e => e.Id).ToList(), unresolved.Distinct().ToList()); + } + + /// + /// Non-Endpoint resources in the Bundle that are related to a match: the ones it references + /// (PractitionerRole.practitioner, Organization.partOf) and the ones that reference it (a _revinclude). + /// + public IEnumerable<(string Relation, Resource Resource)> RelatedTo(Resource match) + { + var self = Reference(match); + var seen = new HashSet { self }; + + foreach (var (path, reference) in References(match)) + { + if (path == "endpoint" || Resolve(reference) is not { } target || target is Endpoint) + { + continue; + } + + if (seen.Add(Reference(target))) + { + yield return (path, target); + } + } + + foreach (var other in _resources.Where(r => r is not Endpoint && !Matches.Contains(r))) + { + var back = References(other).FirstOrDefault(r => SameReference(r.Reference, self)); + + if (back.Reference != null && seen.Add(Reference(other))) + { + yield return ($"{other.TypeName}.{back.Path}", other); + } + } + } + + public string DisplayName(Resource resource) + { + var name = resource switch + { + Organization o => o.Name, + Practitioner p => HumanName(p.Name.FirstOrDefault()), + PractitionerRole role => Join( + role.Practitioner?.Display ?? (Resolve(role.Practitioner?.Reference) is Practitioner p + ? HumanName(p.Name.FirstOrDefault()) : null), + role.Organization?.Display ?? (Resolve(role.Organization?.Reference) as Organization)?.Name, + CodeText(role.Code.FirstOrDefault())), + OrganizationAffiliation affiliation => Join( + affiliation.ParticipatingOrganization?.Display + ?? (Resolve(affiliation.ParticipatingOrganization?.Reference) as Organization)?.Name, + CodeText(affiliation.Code.FirstOrDefault())), + Location l => l.Name, + HealthcareService h => h.Name, + InsurancePlan i => i.Name, + Endpoint e => e.Name ?? e.Address, + _ => null + }; + + return string.IsNullOrWhiteSpace(name) ? Reference(resource) : name; + } + + /// NPIs carried by a resource, for display next to its name. + public static IEnumerable Npis(Resource resource) + { + var identifiers = resource switch + { + Organization o => o.Identifier, + Practitioner p => p.Identifier, + PractitionerRole r => r.Identifier, + Location l => l.Identifier, + _ => [] + }; + + return identifiers.Where(i => i.System == NpiSystem && !string.IsNullOrEmpty(i.Value)).Select(i => i.Value); + } + + private static IEnumerable EndpointReferences(Resource resource) => + References(resource).Where(r => r.Path == "endpoint").Select(r => r.Reference); + + /// + /// The references in a resource, labelled by the top-level element they sit in. References inside an + /// extension are labelled by the extension's name (NDH carries PractitionerRole's network that way, in + /// base-ext-network-reference). Contained resources are skipped. + /// + private static IEnumerable<(string Path, string Reference)> References(Base node, string? path = null) + { + foreach (var child in node.NamedChildren) + { + var label = child.Value is Extension extension + ? extension.Url?.Split('/').LastOrDefault()?.Replace("base-ext-", string.Empty) ?? child.ElementName + : path ?? child.ElementName; + + switch (child.Value) + { + case ResourceReference { Reference: { Length: > 0 } reference }: + yield return (label, reference); + break; + case Resource: + case PrimitiveType: + break; + case Base nested: + foreach (var found in References(nested, label)) + { + yield return found; + } + break; + } + } + } + + private static bool SameReference(string? reference, string relative) => + reference != null && (reference == relative || RelativeReference(reference) == relative); + + private static string? RelativeReference(string reference) + { + var parts = reference.Split('?')[0].TrimEnd('/').Split('/'); + + if (parts.Length >= 4 && parts[^2] == "_history") + { + parts = parts[..^2]; + } + + return parts.Length >= 2 ? $"{parts[^2]}/{parts[^1]}" : null; + } + + private static string? LinkUrl(Bundle bundle, string relation) => + bundle.Link.FirstOrDefault(l => l.Relation == relation)?.Url; + + private static string? HumanName(HumanName? name) + { + if (name == null) + { + return null; + } + + if (!string.IsNullOrWhiteSpace(name.Text)) + { + return name.Text; + } + + return JoinWith(" ", name.Prefix.Concat(name.Given).Append(name.Family).Concat(name.Suffix).ToArray()); + } + + private static string? CodeText(CodeableConcept? concept) => + concept?.Text ?? concept?.Coding.Select(c => c.Display ?? c.Code).FirstOrDefault(c => c != null); + + private static string? Join(params string?[] parts) => JoinWith(" · ", parts); + + private static string? JoinWith(string separator, string?[] parts) + { + var present = parts.Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); + return present.Count == 0 ? null : string.Join(separator, present); + } +} diff --git a/Shared/Search/DirectoryCapabilities.cs b/Shared/Search/DirectoryCapabilities.cs new file mode 100644 index 0000000..4234894 --- /dev/null +++ b/Shared/Search/DirectoryCapabilities.cs @@ -0,0 +1,151 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using Hl7.Fhir.Model; +using UdapEd.Shared.Services.Search; + +namespace UdapEd.Shared.Search; + +/// +/// The resources, search parameters, includes and reverse includes the Directory page offers. Read from the +/// directory's own CapabilityStatement, then topped up with the NDH IG's, because directories honor more than +/// they advertise (the CMS NPD answers _include=Organization:endpoint without listing it). +/// +public sealed class DirectoryCapabilities +{ + public static readonly IReadOnlyList DefaultResources = + [ + "Organization", "Practitioner", "PractitionerRole", "Endpoint", "Location", "HealthcareService", + "OrganizationAffiliation", "InsurancePlan" + ]; + + public List Resources { get; } = []; + public Dictionary> SearchParams { get; } = new(); + public Dictionary> Includes { get; } = new(); + public Dictionary> RevIncludes { get; } = new(); + + /// Where the directory-specific part came from; null when only the NDH IG is known. + public string? Source { get; private init; } + + /// Entries the directory's own CapabilityStatement lists, keyed "kind|resource|value". + private readonly HashSet _advertised = new(StringComparer.Ordinal); + + /// + /// Whether the directory itself advertises a search parameter ("param"), include ("include") or reverse + /// include ("revinclude"). True for everything when no directory CapabilityStatement was read. + /// + public bool IsAdvertised(string kind, string? resource, string value) => + Source == null || _advertised.Contains($"{kind}|{resource}|{value}"); + + public IReadOnlyList SearchParamsFor(string? resource) => Lookup(SearchParams, resource); + public IReadOnlyList IncludesFor(string? resource) => Lookup(Includes, resource); + public IReadOnlyList RevIncludesFor(string? resource) => Lookup(RevIncludes, resource); + + public static DirectoryCapabilities From(CapabilityStatement capabilityStatement, string source) + { + var capabilities = new DirectoryCapabilities { Source = source }; + + foreach (var resource in capabilityStatement.Rest.SelectMany(r => r.Resource)) + { + if (string.IsNullOrEmpty(resource.Type)) + { + continue; + } + + capabilities.Add(resource.Type, + resource.SearchParam.Select(p => p.Name), + resource.SearchInclude, + resource.SearchRevInclude); + } + + return capabilities; + } + + public static DirectoryCapabilities From(ICapabilityLookup lookup) + { + var capabilities = new DirectoryCapabilities(); + + foreach (var map in lookup.SearchParamMap) + { + capabilities.Add(map.Resource, + map.ParamDefinitions?.Select(d => d.Code) ?? [], + lookup.IncludeMap.GetValueOrDefault(map.Resource) ?? [], + lookup.ReverseIncludeMap.GetValueOrDefault(map.Resource) ?? []); + } + + return capabilities; + } + + /// + /// This directory's capabilities first, then anything the fallback adds for the same resources. The resource + /// list stays the directory's own when it published one. + /// + public DirectoryCapabilities MergedWith(DirectoryCapabilities fallback) + { + var merged = new DirectoryCapabilities { Source = Source }; + + foreach (var resource in Resources) + { + merged.Add(resource, SearchParamsFor(resource), IncludesFor(resource), RevIncludesFor(resource)); + } + + merged._advertised.UnionWith(Source == null ? [] : AllEntries()); + + foreach (var resource in fallback.Resources) + { + if (Resources.Count > 0 && !Resources.Contains(resource)) + { + continue; + } + + merged.Add(resource, fallback.SearchParamsFor(resource), fallback.IncludesFor(resource), + fallback.RevIncludesFor(resource)); + } + + return merged; + } + + private IEnumerable AllEntries() => + SearchParams.SelectMany(kv => kv.Value.Select(v => $"param|{kv.Key}|{v}")) + .Concat(Includes.SelectMany(kv => kv.Value.Select(v => $"include|{kv.Key}|{v}"))) + .Concat(RevIncludes.SelectMany(kv => kv.Value.Select(v => $"revinclude|{kv.Key}|{v}"))); + + private void Add(string resource, IEnumerable searchParams, IEnumerable includes, + IEnumerable revIncludes) + { + if (!Resources.Contains(resource)) + { + Resources.Add(resource); + } + + Append(SearchParams, resource, searchParams); + Append(Includes, resource, includes); + Append(RevIncludes, resource, revIncludes); + } + + private static void Append(Dictionary> map, string resource, IEnumerable values) + { + if (!map.TryGetValue(resource, out var list)) + { + list = []; + map[resource] = list; + } + + foreach (var value in values) + { + if (!string.IsNullOrWhiteSpace(value) && !list.Contains(value)) + { + list.Add(value); + } + } + } + + private static IReadOnlyList Lookup(Dictionary> map, string? resource) => + resource != null && map.TryGetValue(resource, out var list) ? list : []; +} diff --git a/Shared/Search/DirectoryQuery.cs b/Shared/Search/DirectoryQuery.cs new file mode 100644 index 0000000..8ba8470 --- /dev/null +++ b/Shared/Search/DirectoryQuery.cs @@ -0,0 +1,109 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +namespace UdapEd.Shared.Search; + +/// +/// Turns what a user types or pastes into the Directory page's GET box into a search URL. Accepts a bare query +/// (name=mayo), a resource-relative query (Organization?name=mayo) or a full URL copied from a +/// directory's documentation (https://directory.cms.gov/fhir/Organization?name=mayo). +/// +public static class DirectoryQuery +{ + public sealed record Parsed(string? BaseUrl, string? ResourceName, string Query); + + public static Parsed Parse(string? input) + { + var text = (input ?? string.Empty).Trim(); + + if (text.StartsWith("GET ", StringComparison.OrdinalIgnoreCase)) + { + text = text[4..].Trim(); + } + + var queryStart = text.IndexOf('?'); + var path = queryStart >= 0 ? text[..queryStart] : text; + var query = queryStart >= 0 ? text[(queryStart + 1)..] : string.Empty; + + if (Uri.TryCreate(path, UriKind.Absolute, out var uri) + && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp)) + { + var trimmed = path.TrimEnd('/'); + var lastSlash = trimmed.LastIndexOf('/'); + var lastSegment = lastSlash >= 0 ? trimmed[(lastSlash + 1)..] : string.Empty; + + return IsResourceName(lastSegment) && lastSlash > uri.GetLeftPart(UriPartial.Authority).Length + ? new Parsed(trimmed[..lastSlash], lastSegment, query) + : new Parsed(trimmed, null, query); + } + + var relative = path.Trim('/'); + + if (queryStart >= 0) + { + return IsResourceName(relative) + ? new Parsed(null, relative, query) + : new Parsed(null, null, relative.Length == 0 ? query : text); + } + + // No '?': a lone resource name, or a query without one ("name=mayo"). + return IsResourceName(relative) ? new Parsed(null, relative, string.Empty) : new Parsed(null, null, text); + } + + /// + /// Builds the query string for the parameters, includes and page size. Values are percent-encoded except + /// for the characters FHIR search gives meaning to (| token separators, , OR lists, :). + /// + public static string Build(IEnumerable<(string Name, string? Modifier, string? Value)> parameters, + IEnumerable includes, IEnumerable revIncludes, int? count) + { + var parts = new List(); + + foreach (var (name, modifier, value) in parameters) + { + if (string.IsNullOrWhiteSpace(name)) + { + continue; + } + + var key = string.IsNullOrEmpty(modifier) ? name.Trim() : $"{name.Trim()}:{modifier}"; + parts.Add($"{key}={EscapeValue(value)}"); + } + + parts.AddRange(includes.Select(i => $"_include={i}")); + parts.AddRange(revIncludes.Select(i => $"_revinclude={i}")); + + if (count is > 0) + { + parts.Add($"_count={count}"); + } + + return string.Join('&', parts); + } + + public static string EscapeValue(string? value) => + Uri.EscapeDataString(value ?? string.Empty) + .Replace("%7C", "|", StringComparison.OrdinalIgnoreCase) + .Replace("%2C", ",", StringComparison.OrdinalIgnoreCase) + .Replace("%3A", ":", StringComparison.OrdinalIgnoreCase); + + /// + /// Search URL for a base, resource and query. A query that already holds a full URL (a Bundle paging link) + /// is returned as is. + /// + public static string Url(string baseUrl, string resourceName, string? query) + { + var url = $"{baseUrl.Trim().TrimEnd('/')}/{resourceName.Trim()}"; + return string.IsNullOrWhiteSpace(query) ? url : $"{url}?{query.Trim().TrimStart('?')}"; + } + + /// FHIR resource type names are PascalCase letters, e.g. Organization or PractitionerRole. + public static bool IsResourceName(string? segment) => + !string.IsNullOrEmpty(segment) && char.IsUpper(segment[0]) && segment.All(char.IsAsciiLetter); +} diff --git a/Shared/Services/IDiscoveryService.cs b/Shared/Services/IDiscoveryService.cs index b5faa28..eea77c5 100644 --- a/Shared/Services/IDiscoveryService.cs +++ b/Shared/Services/IDiscoveryService.cs @@ -16,6 +16,15 @@ namespace UdapEd.Shared.Services; public interface IDiscoveryService { Task GetUdapMetadataVerificationModel(string metadataUrl, string? community, CancellationToken token); + + /// + /// Fetches and validates UDAP metadata like , without making + /// the session's FHIR server. The Directory page probes every Endpoint it lists; + /// the session's server (and the access token sent to it) must stay the one the user chose. + /// Apps without a server session fetch the metadata the usual way. + /// + Task ProbeUdapMetadata(string metadataUrl, CancellationToken token) => + GetUdapMetadataVerificationModel(metadataUrl, null, token); Task GetCapabilityStatement(string url, CancellationToken token); Task GetSmartMetadata(string metadataUrl, CancellationToken token); Task UploadAnchorCertificate(string certBytes); diff --git a/Shared/UdapEdConstants.cs b/Shared/UdapEdConstants.cs index 94a44a2..6ad98fc 100644 --- a/Shared/UdapEdConstants.cs +++ b/Shared/UdapEdConstants.cs @@ -69,5 +69,6 @@ public static class FhirClient public const string FhirCompressedSize = "X-Fhir-Compressed-Size"; public const string FhirDecompressedSize = "X-Fhir-Decompressed-Size"; public const string FhirOutgoingRequest = "X-Fhir-Outgoing-Request"; + public const string FhirElapsedMs = "X-Fhir-Elapsed-Ms"; } } \ No newline at end of file diff --git a/Shared/wwwroot/Packages/udap_urls.json b/Shared/wwwroot/Packages/udap_urls.json index a8d5a3e..aacd506 100644 --- a/Shared/wwwroot/Packages/udap_urls.json +++ b/Shared/wwwroot/Packages/udap_urls.json @@ -6,7 +6,6 @@ "https://dev-mtx-interop.meditech.com/v2/uscore/STU6", "https://securefhir.zimt.work/udap-public", "https://identity-matching.fast.hl7.org/fhir", - "https://national-directory.fast.hl7.org/fhir", "https://udap.fhir.poolnook.me/evernorth", "https://fhir-udap.azurewebsites.net", "https://ihe-nimbus.epic.com/Interconnect-FHIR/api/fhir/r4" diff --git a/_tests/UtilityTests/DirectorySearchTests.cs b/_tests/UtilityTests/DirectorySearchTests.cs new file mode 100644 index 0000000..4164807 --- /dev/null +++ b/_tests/UtilityTests/DirectorySearchTests.cs @@ -0,0 +1,208 @@ +#region (c) 2026 Joseph Shook. All rights reserved. +// /* +// Authors: +// Joseph Shook Joseph.Shook@Surescripts.com +// +// See LICENSE in the project root for license information. +// */ +#endregion + +using Hl7.Fhir.Model; +using Shouldly; +using UdapEd.Shared.Search; + +namespace UtilityTests; + +public class DirectorySearchTests +{ + [Theory] + [InlineData("name=mayo", null, null, "name=mayo")] + [InlineData("?name=mayo", null, null, "name=mayo")] + [InlineData("Organization?name=mayo", null, "Organization", "name=mayo")] + [InlineData("/Practitioner?family=smith&_count=5", null, "Practitioner", "family=smith&_count=5")] + [InlineData("PractitionerRole", null, "PractitionerRole", "")] + [InlineData("https://directory.cms.gov/fhir/Organization?identifier=1023405065", + "https://directory.cms.gov/fhir", "Organization", "identifier=1023405065")] + [InlineData("GET https://directory.cms.gov/fhir/Endpoint?connection-type=hl7-fhir-rest", + "https://directory.cms.gov/fhir", "Endpoint", "connection-type=hl7-fhir-rest")] + [InlineData("https://directory.cms.gov/fhir?name=x", "https://directory.cms.gov/fhir", null, "name=x")] + public void ParsesWhatIsPastedIntoTheGetBox(string input, string? baseUrl, string? resource, string query) + { + var parsed = DirectoryQuery.Parse(input); + + parsed.BaseUrl.ShouldBe(baseUrl); + parsed.ResourceName.ShouldBe(resource); + parsed.Query.ShouldBe(query); + } + + [Fact] + public void BuildsAnEncodedQueryWithIncludesAndCount() + { + var query = DirectoryQuery.Build( + [("name", null, "plymouth bay"), ("identifier", null, "http://hl7.org/fhir/sid/us-npi|1023405065"), + ("name", "contains", "o'neil & sons"), ("", null, "ignored")], + ["Organization:endpoint"], ["PractitionerRole:organization"], 20); + + query.ShouldBe("name=plymouth%20bay&identifier=http:%2F%2Fhl7.org%2Ffhir%2Fsid%2Fus-npi|1023405065" + + "&name:contains=o%27neil%20%26%20sons&_include=Organization:endpoint" + + "&_revinclude=PractitionerRole:organization&_count=20"); + } + + [Fact] + public void LinksEndpointsReferencedForwardAndBackward() + { + var bundle = new Bundle { Type = Bundle.BundleType.Searchset }; + // CMS NPD shape: the Organization points at the Endpoint, the Endpoint has no managingOrganization, + // and two organizations share one endpoint. + bundle.Entry.Add(Match(new Organization + { + Id = "org1", Name = "PLYMOUTH BAY ORTHOPEDIC", + Endpoint = [new ResourceReference("Endpoint/ep1")], + Identifier = [new Identifier(DirectoryBundle.NpiSystem, "1053582031")] + })); + bundle.Entry.Add(Match(new Organization + { + Id = "org2", Name = "PLYMOUTH BAY ORTHOPEDIC ASSOCIATES", + Endpoint = [new ResourceReference("https://directory.cms.gov/fhir/Endpoint/ep1"), new ResourceReference("Endpoint/missing")] + })); + // NDH RI shape: only the Endpoint points back at its Organization. + bundle.Entry.Add(Match(new Organization { Id = "org3", Name = "Back Reference Clinic" })); + bundle.Entry.Add(Include(new Endpoint { Id = "ep1", Address = "https://fhir4.healow.com/fhir/r4/CEIGAA" })); + bundle.Entry.Add(Include(new Endpoint + { + Id = "ep2", Address = "https://example.org/fhir", ManagingOrganization = new ResourceReference("Organization/org3") + })); + + var directory = new DirectoryBundle(bundle, "Organization"); + + directory.Matches.Select(m => m.Id).ShouldBe(["org1", "org2", "org3"]); + + var org1 = directory.EndpointsOf(directory.Matches[0]); + org1.Resolved.Select(e => e.Id).ShouldBe(["ep1"]); + org1.Unresolved.ShouldBeEmpty(); + + var org2 = directory.EndpointsOf(directory.Matches[1]); + org2.Resolved.Select(e => e.Id).ShouldBe(["ep1"]); + org2.Unresolved.ShouldBe(["Endpoint/missing"]); + + directory.EndpointsOf(directory.Matches[2]).Resolved.Select(e => e.Id).ShouldBe(["ep2"]); + DirectoryBundle.Npis(directory.Matches[0]).ShouldBe(["1053582031"]); + } + + [Fact] + public void ShowsPractitionerRoleByItsIncludedPractitionerAndOrganization() + { + var bundle = new Bundle { Type = Bundle.BundleType.Searchset }; + bundle.Entry.Add(Match(new PractitionerRole + { + Id = "role1", + Practitioner = new ResourceReference("Practitioner/p1"), + Organization = new ResourceReference("Organization/o1") + })); + bundle.Entry.Add(Include(new Practitioner + { + Id = "p1", Name = [new HumanName { Family = "Smith", Given = ["Jane"] }] + })); + bundle.Entry.Add(Include(new Organization { Id = "o1", Name = "Acme Clinic" })); + + var directory = new DirectoryBundle(bundle, "PractitionerRole"); + var role = directory.Matches.Single(); + + directory.DisplayName(role).ShouldBe("Jane Smith · Acme Clinic"); + directory.RelatedTo(role).Select(r => (r.Relation, r.Resource.Id)).ShouldBe([("practitioner", "p1"), ("organization", "o1")]); + } + + [Fact] + public void FollowsReferencesInsideExtensions() + { + var bundle = new Bundle { Type = Bundle.BundleType.Searchset }; + var role = new PractitionerRole { Id = "role1", Practitioner = new ResourceReference("Practitioner/p1") }; + role.Extension.Add(new Extension("http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-network-reference", + new ResourceReference("Organization/Network1"))); + bundle.Entry.Add(Match(role)); + bundle.Entry.Add(Include(new Organization { Id = "Network1", Name = "Network1" })); + + var directory = new DirectoryBundle(bundle, "PractitionerRole"); + + directory.RelatedTo(directory.Matches.Single()).Select(r => (r.Relation, r.Resource.Id)) + .ShouldBe([("network-reference", "Network1")]); + } + + [Fact] + public void ReadsPagingLinks() + { + var bundle = new Bundle { Type = Bundle.BundleType.Searchset, Total = 42 }; + bundle.Link.Add(new Bundle.LinkComponent { Relation = "next", Url = "https://directory.cms.gov/fhir/Organization?name=x&page=2" }); + + var directory = new DirectoryBundle(bundle, "Organization"); + + directory.NextUrl.ShouldBe("https://directory.cms.gov/fhir/Organization?name=x&page=2"); + directory.PreviousUrl.ShouldBeNull(); + directory.Total.ShouldBe(42); + } + + [Fact] + public void PrefersTheDirectoryCapabilitiesAndKeepsTheIgExtras() + { + var directory = new CapabilityStatement + { + Rest = + [ + new CapabilityStatement.RestComponent + { + Resource = + [ + new CapabilityStatement.ResourceComponent + { + Type = "Organization", + SearchParam = [new CapabilityStatement.SearchParamComponent { Name = "name" }], + SearchInclude = ["Organization:partof"] + } + ] + } + ] + }; + var ig = new CapabilityStatement + { + Rest = + [ + new CapabilityStatement.RestComponent + { + Resource = + [ + new CapabilityStatement.ResourceComponent + { + Type = "Organization", + SearchParam = [new CapabilityStatement.SearchParamComponent { Name = "endpoint" }], + SearchInclude = ["Organization:endpoint", "Organization:partof"] + }, + new CapabilityStatement.ResourceComponent { Type = "CareTeam" } + ] + } + ] + }; + + var merged = DirectoryCapabilities.From(directory, "cms").MergedWith(DirectoryCapabilities.From(ig, "ig")); + + merged.Resources.ShouldBe(["Organization"]); + merged.SearchParamsFor("Organization").ShouldBe(["name", "endpoint"]); + merged.IncludesFor("Organization").ShouldBe(["Organization:partof", "Organization:endpoint"]); + merged.Source.ShouldBe("cms"); + merged.IsAdvertised("include", "Organization", "Organization:partof").ShouldBeTrue(); + merged.IsAdvertised("include", "Organization", "Organization:endpoint").ShouldBeFalse(); + merged.IsAdvertised("param", "Organization", "name").ShouldBeTrue(); + merged.IsAdvertised("param", "Organization", "endpoint").ShouldBeFalse(); + DirectoryCapabilities.From(ig, "ig").MergedWith(new DirectoryCapabilities()) + .IsAdvertised("param", "Organization", "endpoint").ShouldBeTrue(); + } + + private static Bundle.EntryComponent Match(Resource resource) => Entry(resource, Bundle.SearchEntryMode.Match); + private static Bundle.EntryComponent Include(Resource resource) => Entry(resource, Bundle.SearchEntryMode.Include); + + private static Bundle.EntryComponent Entry(Resource resource, Bundle.SearchEntryMode mode) => new() + { + FullUrl = $"https://directory.cms.gov/fhir/{resource.TypeName}/{resource.Id}", + Resource = resource, + Search = new Bundle.SearchComponent { Mode = mode } + }; +}