001/*- 002 * #%L 003 * Smile CDR - CDR 004 * %% 005 * Copyright (C) 2016 - 2026 Smile CDR, Inc. 006 * %% 007 * All rights reserved. 008 * #L% 009 */ 010package ca.cdr.test.app.harness.impl; 011 012import ca.cdr.test.app.clients.AdminJsonRestClient; 013import ca.cdr.test.app.clients.CdrFhirClient; 014import ca.cdr.test.app.clients.CdsHooksClient; 015import ca.cdr.test.app.clients.HL7V2RestClient; 016import ca.cdr.test.app.clients.NpmPackageClient; 017import ca.cdr.test.app.clients.OutboundSmartClient; 018import ca.cdr.test.app.clients.SmartHealthLinkClient; 019import ca.cdr.test.app.clients.SmilePortalClient; 020import ca.cdr.test.app.clients.common.ISmileTestHttpClient; 021import ca.cdr.test.app.clients.common.RequestFactoryUtil; 022import ca.cdr.test.app.clients.common.SmileTestHttpClient; 023import ca.cdr.test.app.harness.api.HarnessContext; 024import ca.cdr.test.app.harness.api.SmileHarness; 025import ca.cdr.test.model.NodeConfigurations; 026import ca.cdr.test.util.UrlPathUtil; 027import ca.uhn.fhir.context.FhirContext; 028import ca.uhn.fhir.context.FhirVersionEnum; 029import ca.uhn.fhir.rest.client.api.IClientInterceptor; 030import ca.uhn.fhir.rest.client.api.IGenericClient; 031import ca.uhn.fhir.rest.client.interceptor.BasicAuthInterceptor; 032import ca.uhn.fhir.rest.client.interceptor.BearerTokenAuthInterceptor; 033import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 034import ca.uhn.fhir.test.utilities.HttpTestRequest; 035import jakarta.annotation.Nonnull; 036import jakarta.annotation.Nullable; 037import org.apache.commons.lang3.StringUtils; 038import org.apache.commons.lang3.Validate; 039import org.slf4j.Logger; 040import org.slf4j.LoggerFactory; 041import org.springframework.web.client.RestClient; 042 043import java.net.URI; 044import java.util.HashMap; 045import java.util.HashSet; 046import java.util.LinkedHashMap; 047import java.util.List; 048import java.util.Map; 049import java.util.Objects; 050import java.util.Optional; 051import java.util.Set; 052import java.util.concurrent.ConcurrentHashMap; 053import java.util.function.Function; 054import java.util.function.Predicate; 055import java.util.function.Supplier; 056import java.util.function.UnaryOperator; 057 058/** 059 * The {@code LocalhostSmileHarness} class is responsible for managing interaction 060 * with a Smile CDR environment running on the localhost. It provides utility methods to 061 * identify and interact with Smile modules, such as FHIR endpoints and HL7v2 endpoints, 062 * through exposed ports and administrative interfaces. 063 * <p> 064 * This class implements the {@link SmileHarness} interface to provide concrete 065 * implementations of the methods required to handle FHIR and administrative operations. 066 * <p> 067 * Every URL it builds is {@code protocol://host:port} followed by the target module's 068 * {@code context_path}, so modules mounted beneath a context path are reached there. The Admin JSON 069 * module's own context path comes from {@link HarnessContext#jsonAdminContextPath()}, since it is 070 * needed before any module configuration can be read; every other module's comes from that 071 * configuration. A port no module is configured with is addressed at the root. 072 * <p> 073 * This class was generated partly with the help of Claude Sonnet 3.7 074 */ 075public class LocalhostSmileHarness implements SmileHarness { 076 private static final Logger ourLog = LoggerFactory.getLogger(LocalhostSmileHarness.class); 077 private static final int DEFAULT_JSON_ADMIN_PORT = 9000; 078 079 private final Function<Integer, Integer> portResolver; 080 private final HarnessContext myContext; 081 private final SmileTestHttpClient myHttpClient; 082 /** 083 * The Admin JSON port this harness talks to, resolved once so that every caller agrees on it. 084 * A context that names no port falls back to {@link #DEFAULT_JSON_ADMIN_PORT}, which is the port 085 * the connectivity check then runs against. 086 */ 087 private final int myJsonAdminPort; 088 /** 089 * Filled in configuration order, which is what makes the no-argument accessors deterministic 090 * when a node has several modules of one type. 091 */ 092 private final Map<String, Integer> myFhirModulePortMap = new LinkedHashMap<>(); 093 094 private final Map<String, Integer> myEndpointHl7V2PortMap = new LinkedHashMap<>(); 095 private final Map<String, Integer> mySmartEndpointPortMap = new LinkedHashMap<>(); 096 private final Map<String, Integer> myPackageRegistryPortMap = new LinkedHashMap<>(); 097 private final Map<String, Integer> myCdsHooksPortMap = new LinkedHashMap<>(); 098 /** 099 * Every discovered port map, in the order {@link #discoveredPortFor(String)} searches them. Constant 100 * once the constructor has run, since the maps behind it are only written during discovery. 101 */ 102 private final List<Map<String, Integer>> myDiscoveredPortMaps = List.of( 103 myFhirModulePortMap, 104 myEndpointHl7V2PortMap, 105 mySmartEndpointPortMap, 106 myPackageRegistryPortMap, 107 myCdsHooksPortMap); 108 /** 109 * The normalized context path of each module, keyed by the port it is configured with rather 110 * than the one it is published on. Written only in the constructor. 111 */ 112 private final Map<Integer, String> myContextPathByPort = new HashMap<>(); 113 /** 114 * Holds only the contexts resolved from {@link #myNodeConfigurations}, which cannot go stale 115 * because that snapshot cannot change. A module the snapshot does not cover is re-resolved per 116 * call and never lands here — see {@link #locateFhirModule(String)}. 117 * <p> 118 * One harness is shared by every test using a given {@link ca.cdr.test.extensions.SmileCdrContainer}, 119 * so this is populated on demand from more than one thread. 120 */ 121 private final Map<String, FhirContext> myFhirContextByModuleId = new ConcurrentHashMap<>(); 122 /** 123 * The node's module configuration as it was when this harness was built — one 124 * {@code GET /module-config/} response, kept so that building a request costs no round trip. 125 * A module added to the node afterwards will not be in here; {@link #locateFhirModule(String)}, 126 * {@link #addressOf(String)} and {@link #cachedFhirContext(String)} fall back to the node for 127 * those. 128 */ 129 private final NodeConfigurations myNodeConfigurations; 130 131 private static final List<String> HL7V2_COMPATIBLE_MODULE_TYPES = 132 List.of("ENDPOINT_HL7V2_IN_V2", "ENDPOINT_HL7V2_IN"); 133 134 private static final List<String> SMART_COMPATIBLE_MODULE_TYPES = List.of("SECURITY_OUT_SMART"); 135 136 private static final List<String> PACKAGE_REGISTRY_COMPATIBLE_MODULE_TYPES = List.of("ENDPOINT_PACKAGE_REGISTRY"); 137 138 private static final List<String> CDS_HOOKS_COMPATIBLE_MODULE_TYPES = List.of("ENDPOINT_CDS_HOOKS"); 139 140 private static final String DEFAULT_FHIR_MODULE_ID = "fhir_endpoint"; 141 private static final String DEFAULT_SMART_MODULE_ID = "smart_auth"; 142 private static final int DEFAULT_HL7V2_PORT = 7000; 143 private static final String CONTEXT_PATH = "context_path"; 144 145 /** 146 * Version markers that can appear inside a module type, checked in this order — the first one 147 * the type contains wins. 148 */ 149 private static final List<Map.Entry<String, Supplier<FhirContext>>> CONTEXT_BY_VERSION_MARKER = List.of( 150 Map.entry("R4", FhirContext::forR4Cached), 151 Map.entry("DSTU3", FhirContext::forDstu3Cached), 152 Map.entry("R5", FhirContext::forR5Cached), 153 Map.entry("DSTU2", FhirContext::forDstu2Cached)); 154 155 public LocalhostSmileHarness(HarnessContext theContext) { 156 this(theContext, null); 157 } 158 159 public LocalhostSmileHarness(HarnessContext theContext, Map<Integer, Integer> theExposedPortMappings) { 160 this(theContext, theExposedPortMappings, SmileTestHttpClient.create()); 161 } 162 163 /** 164 * Builds a harness over an existing HTTP client. The harness takes ownership: {@link #close()} 165 * releases the client, as does a failure during discovery. 166 */ 167 LocalhostSmileHarness( 168 HarnessContext theContext, 169 Map<Integer, Integer> theExposedPortMappings, 170 SmileTestHttpClient theHttpClient) { 171 myContext = theContext; 172 if (theExposedPortMappings == null || theExposedPortMappings.isEmpty()) { 173 portResolver = i -> i; 174 } else { 175 portResolver = theExposedPortMappings::get; 176 } 177 myHttpClient = theHttpClient; 178 myJsonAdminPort = resolveJsonAdminPort(theContext); 179 myContextPathByPort.put(myJsonAdminPort, theContext.jsonAdminContextPath()); 180 try { 181 myNodeConfigurations = fetchNodeConfigurations(); 182 recordContextPaths(); 183 discoverEndpoints(); 184 } catch (RuntimeException e) { 185 // Discovery talks to the running node, so it fails whenever the node is not up yet or 186 // the ports are wrong. Without this the caller never gets a reference to close, and the 187 // connection pool survives until the JVM exits. 188 myHttpClient.close(); 189 throw e; 190 } 191 } 192 193 /** 194 * Records the port of every module this harness can reach, all read from 195 * {@link #myNodeConfigurations}. 196 */ 197 private void discoverEndpoints() { 198 discoverEndpoints( 199 "FHIR", NodeConfigurations.ModuleConfiguration::isFhirEndpointModuleType, myFhirModulePortMap); 200 discoverEndpoints("HL7v2", moduleTypeIn(HL7V2_COMPATIBLE_MODULE_TYPES), myEndpointHl7V2PortMap); 201 discoverEndpoints("SMART", moduleTypeIn(SMART_COMPATIBLE_MODULE_TYPES), mySmartEndpointPortMap); 202 discoverEndpoints( 203 "package registry", moduleTypeIn(PACKAGE_REGISTRY_COMPATIBLE_MODULE_TYPES), myPackageRegistryPortMap); 204 discoverEndpoints("CDS Hooks", moduleTypeIn(CDS_HOOKS_COMPATIBLE_MODULE_TYPES), myCdsHooksPortMap); 205 } 206 207 /** 208 * Records the context path of every module with a port. The Admin JSON port keeps the context 209 * path the {@link HarnessContext} named, since that is the one discovery just succeeded with. 210 */ 211 private void recordContextPaths() { 212 myNodeConfigurations.getNodes().stream() 213 .flatMap(node -> node.getModules().stream()) 214 .filter(module -> StringUtils.isNotBlank(optionalConfigProperty(module, "port"))) 215 .forEach(module -> myContextPathByPort.putIfAbsent( 216 Integer.parseInt(module.getConfigProperty("port")), contextPathOf(module))); 217 } 218 219 private static @Nullable String optionalConfigProperty( 220 NodeConfigurations.ModuleConfiguration theModule, String theKey) { 221 // Unlike getConfigProperty(String), this tolerates a key the node reports with a null value. 222 return theModule.getConfigProperties().stream() 223 .filter(property -> theKey.equals(property.getKey())) 224 .map(NodeConfigurations.ModuleConfigProperty::getValue) 225 .filter(Objects::nonNull) 226 .findFirst() 227 .orElse(null); 228 } 229 230 /** 231 * A module's {@code context_path}, normalized. Only {@code context_path} decides where a module's 232 * server is mounted; {@code base_url.fixed} changes the links a module writes, not where it 233 * listens, so it is not consulted. 234 */ 235 private static String contextPathOf(NodeConfigurations.ModuleConfiguration theModule) { 236 return UrlPathUtil.normalizeContextPath(optionalConfigProperty(theModule, CONTEXT_PATH)); 237 } 238 239 /** 240 * Records the configured port of every module {@code theIsWanted} accepts, then fails fast if 241 * the port resolver cannot map one of them. 242 * 243 * @param theKind how to describe this group of modules in the log 244 */ 245 private void discoverEndpoints( 246 String theKind, 247 Predicate<NodeConfigurations.ModuleConfiguration> theIsWanted, 248 Map<String, Integer> theTargetPortMap) { 249 myNodeConfigurations.getNodes().stream() 250 .flatMap(node -> node.getModules().stream()) 251 .filter(theIsWanted) 252 .forEach(module -> { 253 String port = module.getConfigProperty("port"); 254 if (StringUtils.isBlank(port)) { 255 ourLog.warn( 256 "Found {} module, but it had no port assigned! [moduleId={}, moduleType={}]", 257 theKind, 258 module.getModuleId(), 259 module.getModuleType()); 260 return; 261 } 262 ourLog.info( 263 "Found {} module. [moduleId={}, moduleType={}, port={}, contextPath={}]", 264 theKind, 265 module.getModuleId(), 266 module.getModuleType(), 267 port, 268 contextPathOf(module)); 269 theTargetPortMap.put(module.getModuleId(), Integer.parseInt(port)); 270 }); 271 272 validatePortResolverCanResolvePorts(theTargetPortMap); 273 } 274 275 private static Predicate<NodeConfigurations.ModuleConfiguration> moduleTypeIn(List<String> theModuleTypes) { 276 return module -> theModuleTypes.contains(module.getModuleType()); 277 } 278 279 private void validatePortResolverCanResolvePorts(Map<String, Integer> theModuleToPortMap) { 280 // Ensure all the endpoints we found have Mappings 281 theModuleToPortMap.forEach((key, value) -> { 282 if (portResolver.apply(value) == null) { 283 throw unmappedPort(key + " (" + value + ")"); 284 } 285 }); 286 } 287 288 /** 289 * The one failure both discovery and {@link #resolvePort(int)} report, so that the same condition 290 * does not read two different ways depending on which of them reached it. 291 * 292 * @param theSubject what could not be mapped — a port on its own, or a module ID and its port 293 */ 294 private static IllegalStateException unmappedPort(String theSubject) { 295 return new IllegalStateException( 296 "Could not find a mapped port for module. Please ensure your port resolver can resolve this port! : " 297 + theSubject); 298 } 299 300 /** 301 * The Admin JSON port to use, which is the one the context names or {@link #DEFAULT_JSON_ADMIN_PORT}. 302 * Resolved once in the constructor so that discovery, {@link #getAdminJsonClient()} and 303 * {@link #adminJsonRequest(String)} cannot disagree about which port this harness talks to. 304 */ 305 static int resolveJsonAdminPort(HarnessContext theContext) { 306 Integer jsonAdminPort = theContext.jsonAdminPort(); 307 if (jsonAdminPort == null) { 308 ourLog.warn( 309 "No JSON Admin port was provided in the provided harness context. Attempting to fallback to the default port [port={}]", 310 DEFAULT_JSON_ADMIN_PORT); 311 return DEFAULT_JSON_ADMIN_PORT; 312 } 313 ourLog.info("Found a JSON Admin port in the context provided. [port={}]", jsonAdminPort); 314 return jsonAdminPort; 315 } 316 317 /** 318 * The connectivity check and the configuration read are the same request, so this returns what 319 * it fetched rather than making the caller ask again. 320 */ 321 private NodeConfigurations fetchNodeConfigurations() { 322 try { 323 ourLog.info( 324 "Performing a connectivity check for Admin JSON module. [host={}, port={}, contextPath={}]", 325 myContext.getContextRoot(), 326 myJsonAdminPort, 327 myContext.jsonAdminContextPath()); 328 NodeConfigurations retVal = getAdminJsonClient(myJsonAdminPort).getNodeConfigurations(); 329 ourLog.info( 330 "Connectivity check succeeded, client can be used! [host={}, port={}]", 331 myContext.getContextRoot(), 332 myJsonAdminPort); 333 return retVal; 334 } catch (Exception e) { 335 throw new InternalErrorException( 336 String.format( 337 "Connectivity check failed for Admin JSON module. [host=%s, port=%d, contextPath=%s]", 338 myContext.getContextRoot(), myJsonAdminPort, myContext.jsonAdminContextPath()), 339 e); 340 } 341 } 342 343 @Override 344 public CdrFhirClient getSuperuserFhirClient() { 345 return getSuperuserFhirClient(firstFhirModule().getKey()); 346 } 347 348 @Override 349 public CdrFhirClient getSuperuserFhirClient(int thePort) { 350 return cdrFhirClient( 351 addressAt(thePort), 352 () -> cachedFhirContext(fhirModuleIdForPort(thePort)), 353 new BasicAuthInterceptor(myContext.username(), myContext.password()), 354 this::withSuperuserAuth); 355 } 356 357 @Override 358 public AdminJsonRestClient getAdminJsonClient() { 359 return getAdminJsonClient(myJsonAdminPort); 360 } 361 362 @Override 363 public AdminJsonRestClient getAdminJsonClient(int theAdminPort) { 364 return AdminJsonRestClient.issuingOn( 365 myHttpClient, restClientBaseUrl(addressAt(theAdminPort)), myContext.username(), myContext.password()); 366 } 367 368 @Override 369 public CdrFhirClient getSuperuserFhirClient(String theModuleId) { 370 ModuleLocation module = locateFhirModule(theModuleId); 371 return cdrFhirClient( 372 module.address(), 373 module::fhirContext, 374 new BasicAuthInterceptor(myContext.username(), myContext.password()), 375 this::withSuperuserAuth); 376 } 377 378 @Override 379 public CdrFhirClient getFhirClient() { 380 return getFhirClient(firstFhirModule().getKey()); 381 } 382 383 /** 384 * The FHIR endpoint used whenever a caller does not name one, so that {@link #getFhirClient()} 385 * and {@link #fhirAnonymousRequest(String)} always pick the same one. The entry carries both the 386 * module ID and its port, which callers generally need together. 387 */ 388 private Map.Entry<String, Integer> firstFhirModule() { 389 return defaultModule(myFhirModulePortMap, DEFAULT_FHIR_MODULE_ID) 390 .orElseThrow(() -> new IllegalStateException("No FHIR Endpoint found in the configuration.")); 391 } 392 393 /** 394 * The module a no-argument accessor uses: the one with the conventional ID if there is one, 395 * otherwise the first of its type in the node's configuration. 396 */ 397 private static Optional<Map.Entry<String, Integer>> defaultModule( 398 Map<String, Integer> theDiscovered, @Nullable String theConventionalModuleId) { 399 if (theConventionalModuleId != null && theDiscovered.containsKey(theConventionalModuleId)) { 400 return Optional.of(Map.entry(theConventionalModuleId, theDiscovered.get(theConventionalModuleId))); 401 } 402 return theDiscovered.entrySet().stream().findFirst(); 403 } 404 405 @Override 406 public CdrFhirClient getFhirClient(int thePort) { 407 return cdrFhirClient( 408 addressAt(thePort), 409 () -> cachedFhirContext(fhirModuleIdForPort(thePort)), 410 null, 411 UnaryOperator.identity()); 412 } 413 414 @Override 415 public CdrFhirClient getFhirClient(String theModuleId) { 416 ModuleLocation module = locateFhirModule(theModuleId); 417 return cdrFhirClient(module.address(), module::fhirContext, null, UnaryOperator.identity()); 418 } 419 420 @Override 421 public CdrFhirClient getFhirClient(@Nonnull String theModuleId, @Nonnull String theBearerToken) { 422 Validate.notEmpty(theBearerToken, "Bearer token is required"); 423 ModuleLocation module = locateFhirModule(theModuleId); 424 return cdrFhirClient( 425 module.address(), 426 module::fhirContext, 427 new BearerTokenAuthInterceptor(theBearerToken), 428 request -> request.withHeader("Authorization", "Bearer " + theBearerToken)); 429 } 430 431 private CdrFhirClient cdrFhirClient( 432 ModuleAddress theAddress, 433 Supplier<FhirContext> theFhirContext, 434 @Nullable IClientInterceptor theAuthInterceptor, 435 UnaryOperator<HttpTestRequest> theAuth) { 436 String baseUrl = baseUrl(theAddress); 437 FhirContext fhirContext = theFhirContext.get(); 438 IGenericClient delegate = fhirContext.newRestfulGenericClient(baseUrl); 439 if (theAuthInterceptor != null) { 440 delegate.registerInterceptor(theAuthInterceptor); 441 } 442 return new CdrFhirClient( 443 delegate, 444 path -> theAuth.apply(myHttpClient.cookielessRequest(fhirContext, buildUrl(theAddress, path))), 445 url -> theAuth.apply(myHttpClient.cookielessRequest(fhirContext, resolveServerUrl(url)))); 446 } 447 448 private HttpTestRequest withSuperuserAuth(HttpTestRequest theRequest) { 449 return theRequest.withBasicAuth(myContext.username(), myContext.password()); 450 } 451 452 @Override 453 public @Nonnull HttpTestRequest fhirRequest(@Nonnull String thePath) { 454 return fhirRequest(firstFhirModule().getKey(), thePath); 455 } 456 457 @Override 458 public @Nonnull HttpTestRequest fhirRequest(@Nonnull String theModuleId, @Nonnull String thePath) { 459 return buildFhirRequest(theModuleId, thePath).withBasicAuth(myContext.username(), myContext.password()); 460 } 461 462 @Override 463 public @Nonnull HttpTestRequest fhirAnonymousRequest(@Nonnull String thePath) { 464 return fhirAnonymousRequest(firstFhirModule().getKey(), thePath); 465 } 466 467 @Override 468 public @Nonnull HttpTestRequest fhirAnonymousRequest(@Nonnull String theModuleId, @Nonnull String thePath) { 469 return buildFhirAnonymousRequest(theModuleId, thePath); 470 } 471 472 @Override 473 public @Nonnull HttpTestRequest serverUrlRequest(@Nonnull String theServerUrl) { 474 return withSuperuserAuth(myHttpClient.request(resolveServerUrl(theServerUrl))); 475 } 476 477 private String resolveServerUrl(String theServerUrl) { 478 URI uri = URI.create(theServerUrl); 479 Validate.isTrue(uri.isAbsolute(), "Expected an absolute URL the server returned, got %s", theServerUrl); 480 if (uri.getPort() == -1) { 481 return theServerUrl; 482 } 483 return myContext.getContextRoot() + ":" + resolvePort(uri.getPort()) + uri.getRawPath() 484 + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery()); 485 } 486 487 @Override 488 public @Nonnull HttpTestRequest fhirBearerRequest( 489 @Nonnull String theModuleId, @Nonnull String thePath, @Nonnull String theBearerToken) { 490 Validate.notEmpty(theBearerToken, "Bearer token is required"); 491 return buildFhirAnonymousRequest(theModuleId, thePath).withHeader("Authorization", "Bearer " + theBearerToken); 492 } 493 494 @Override 495 public @Nonnull HttpTestRequest request(int thePort, @Nonnull String thePath) { 496 return authenticatedRequest(addressAt(thePort), thePath); 497 } 498 499 @Override 500 public @Nonnull HttpTestRequest request(@Nonnull String theModuleId, @Nonnull String thePath) { 501 return authenticatedRequest(addressOf(theModuleId), thePath); 502 } 503 504 private HttpTestRequest authenticatedRequest(ModuleAddress theAddress, String thePath) { 505 return myHttpClient 506 .request(buildUrl(theAddress, thePath)) 507 .withBasicAuth(myContext.username(), myContext.password()); 508 } 509 510 @Override 511 public @Nonnull HttpTestRequest adminJsonRequest(@Nonnull String thePath) { 512 return request(myJsonAdminPort, thePath); 513 } 514 515 @Override 516 public @Nonnull HttpTestRequest anonymousRequest(int thePort, @Nonnull String thePath) { 517 return myHttpClient.cookielessRequest(buildUrl(addressAt(thePort), thePath)); 518 } 519 520 @Override 521 public @Nonnull HttpTestRequest anonymousRequest(@Nonnull String theModuleId, @Nonnull String thePath) { 522 return myHttpClient.cookielessRequest(buildUrl(addressOf(theModuleId), thePath)); 523 } 524 525 @Override 526 public @Nonnull ISmileTestHttpClient getHttpClient() { 527 return myHttpClient; 528 } 529 530 @Override 531 public void clearCookies() { 532 myHttpClient.clearCookies(); 533 } 534 535 @Override 536 public void close() { 537 myHttpClient.close(); 538 } 539 540 /** 541 * Whether {@link #close()} has been called. {@link ca.cdr.test.extensions.SmileCdrContainer} 542 * caches a harness and uses this to replace one a caller closed, since every request through a 543 * closed harness fails on the shut-down pool. 544 */ 545 public boolean isClosed() { 546 return myHttpClient.isClosed(); 547 } 548 549 private HttpTestRequest buildFhirRequest(String theModuleId, String thePath) { 550 ModuleLocation module = locateFhirModule(theModuleId); 551 return myHttpClient.request(module.fhirContext(), buildUrl(module.address(), thePath)); 552 } 553 554 private HttpTestRequest buildFhirAnonymousRequest(String theModuleId, String thePath) { 555 ModuleLocation module = locateFhirModule(theModuleId); 556 return myHttpClient.cookielessRequest(module.fhirContext(), buildUrl(module.address(), thePath)); 557 } 558 559 /** 560 * Where a module is served: the port it is configured with, which {@link #resolvePort(int)} has 561 * yet to map, and its normalized context path. 562 */ 563 private record ModuleAddress(int port, String contextPath) {} 564 565 /** 566 * A module's address together with the {@link FhirContext} its requests encode with. 567 */ 568 private record ModuleLocation(ModuleAddress address, FhirContext fhirContext) {} 569 570 /** 571 * Both halves of a FHIR request builder, always resolved from one configuration — a port read 572 * live against a FHIR version read from the stored snapshot would find a module and then fail on 573 * its version. 574 * <p> 575 * Which configuration that is, is what decides whether either half may be cached. A module 576 * {@link #myNodeConfigurations} covers is resolved from that snapshot, which cannot change, so the 577 * context is cached and nothing goes over the wire. A module added after this harness was built is 578 * resolved from one live {@code GET /module-config/} per call and <em>neither</em> half is cached: 579 * discovery's port map is written only at construction, so that module's port is re-read every 580 * time, and a version cached beside a port that is not would leave a re-versioned module encoding 581 * its body against whichever version it happened to have the first time it was asked for. 582 */ 583 private ModuleLocation locateFhirModule(String theModuleId) { 584 Validate.notEmpty(theModuleId, "Module ID is required"); 585 if (isInNodeConfigurations(theModuleId)) { 586 return new ModuleLocation( 587 addressIn(myNodeConfigurations, theModuleId), cachedSnapshotFhirContext(theModuleId)); 588 } 589 590 NodeConfigurations live = getAdminJsonClient().getNodeConfigurations(); 591 return new ModuleLocation(addressIn(live, theModuleId), resolveFhirContext(live, theModuleId)); 592 } 593 594 /** 595 * A module's address, from the snapshot for a module it covers and otherwise from one live 596 * {@code GET /module-config/}, for the reasons given on {@link #locateFhirModule(String)}. 597 */ 598 private ModuleAddress addressOf(String theModuleId) { 599 Validate.notEmpty(theModuleId, "Module ID is required"); 600 NodeConfigurations nodeConfigs = isInNodeConfigurations(theModuleId) 601 ? myNodeConfigurations 602 : getAdminJsonClient().getNodeConfigurations(); 603 return addressIn(nodeConfigs, theModuleId); 604 } 605 606 private ModuleAddress addressIn(NodeConfigurations theNodeConfigs, String theModuleId) { 607 int port = portIn(theNodeConfigs, theModuleId); 608 String contextPath = moduleIn(theNodeConfigs, theModuleId) 609 .map(LocalhostSmileHarness::contextPathOf) 610 .orElseGet(() -> addressAt(port).contextPath()); 611 return new ModuleAddress(port, contextPath); 612 } 613 614 /** 615 * The address of whichever module the snapshot says is configured with {@code thePort}, or the 616 * root of that port when none is. 617 */ 618 private ModuleAddress addressAt(int thePort) { 619 return new ModuleAddress(thePort, myContextPathByPort.getOrDefault(thePort, "")); 620 } 621 622 /** 623 * The port discovery recorded for a module, or the one the given configuration names for a module 624 * discovery did not cover. 625 */ 626 private int portIn(NodeConfigurations theNodeConfigs, String theModuleId) { 627 Integer discovered = discoveredPortFor(theModuleId); 628 return discovered != null ? discovered : portFromConfiguration(theNodeConfigs, theModuleId); 629 } 630 631 /** 632 * The port discovery recorded for a module, or {@literal null} for one it did not cover. 633 */ 634 private Integer discoveredPortFor(String theModuleId) { 635 for (Map<String, Integer> discovered : myDiscoveredPortMaps) { 636 Integer port = discovered.get(theModuleId); 637 if (port != null) { 638 return port; 639 } 640 } 641 return null; 642 } 643 644 /** 645 * The port a module is configured with, read from a configuration the caller already holds — the 646 * same {@code port} property discovery reads, so a module resolved here and one resolved at 647 * construction agree. 648 */ 649 private static int portFromConfiguration(NodeConfigurations theNodeConfigs, String theModuleId) { 650 NodeConfigurations.ModuleConfiguration module = moduleIn(theNodeConfigs, theModuleId) 651 .orElseThrow(() -> new IllegalArgumentException( 652 "Module with ID " + theModuleId + " not found in node configuration")); 653 654 String port = module.getConfigProperty("port"); 655 if (StringUtils.isBlank(port)) { 656 throw new IllegalArgumentException("Module has no port configured. [moduleId=%s, moduleType=%s]" 657 .formatted(theModuleId, module.getModuleType())); 658 } 659 return Integer.parseInt(port); 660 } 661 662 private static Optional<NodeConfigurations.ModuleConfiguration> moduleIn( 663 NodeConfigurations theNodeConfigs, String theModuleId) { 664 return theNodeConfigs.getNodes().stream() 665 .map(node -> node.getModule(theModuleId)) 666 .flatMap(Optional::stream) 667 .findFirst(); 668 } 669 670 /** 671 * The ID of the FHIR endpoint module configured with the given port, falling back to the node 672 * for a port discovery did not cover. 673 */ 674 private String fhirModuleIdForPort(int thePort) { 675 return myFhirModulePortMap.entrySet().stream() 676 .filter(entry -> entry.getValue() == thePort) 677 .map(Map.Entry::getKey) 678 .findFirst() 679 .orElseGet(() -> getAdminJsonClient().getFhirEndpointModuleIdFromPort(thePort)); 680 } 681 682 /** 683 * The FHIR context of a module {@link #myNodeConfigurations} covers, read once from that snapshot 684 * and then cached — the snapshot cannot change, so neither can the answer. 685 * {@link #getFhirContext(String)} re-reads the node's configuration on every call, which a 686 * request builder must not do: that would cost a round trip per assertion and would make an 687 * anonymous request depend on the Admin JSON credentials. 688 * <p> 689 * A module added after this harness was built falls back to that live lookup, and its answer is 690 * deliberately <em>not</em> cached, for the reason given on {@link #locateFhirModule(String)}. 691 */ 692 private FhirContext cachedFhirContext(String theModuleId) { 693 return isInNodeConfigurations(theModuleId) 694 ? cachedSnapshotFhirContext(theModuleId) 695 : getFhirContext(theModuleId); 696 } 697 698 /** 699 * The cached half of {@link #cachedFhirContext(String)}, for a caller that has already established 700 * that {@link #myNodeConfigurations} covers the module. 701 */ 702 private FhirContext cachedSnapshotFhirContext(String theModuleId) { 703 FhirContext cached = myFhirContextByModuleId.get(theModuleId); 704 if (cached != null) { 705 return cached; 706 } 707 return cacheFhirContext(theModuleId, resolveFhirContext(myNodeConfigurations, theModuleId)); 708 } 709 710 /** 711 * Publishes a resolved context, keeping whichever value won if another thread resolved the same 712 * module first. A duplicate resolve under a race costs nothing — the work is a string match over 713 * a configuration already in memory, and {@link FhirContext#forR4Cached()} and its siblings are 714 * themselves cached. 715 */ 716 private FhirContext cacheFhirContext(String theModuleId, FhirContext theResolved) { 717 FhirContext raced = myFhirContextByModuleId.putIfAbsent(theModuleId, theResolved); 718 return raced != null ? raced : theResolved; 719 } 720 721 private boolean isInNodeConfigurations(String theModuleId) { 722 return moduleIn(myNodeConfigurations, theModuleId).isPresent(); 723 } 724 725 private String buildUrl(ModuleAddress theAddress, String thePath) { 726 return baseUrl(theAddress) + requirePath(thePath); 727 } 728 729 /** 730 * A module's base URL, such as {@code http://localhost:8000/fhir-request}, with no trailing 731 * slash. Every URL this harness builds starts here. 732 */ 733 private String baseUrl(ModuleAddress theAddress) { 734 return myContext.getContextRoot() + ":" + resolvePort(theAddress.port()) + theAddress.contextPath(); 735 } 736 737 private String restClientBaseUrl(ModuleAddress theAddress) { 738 return UrlPathUtil.withTrailingSlash(baseUrl(theAddress)); 739 } 740 741 /** 742 * Guards every request builder against being handed a module ID where it wants a path — the two 743 * single-{@code String} request builders take a path, every other single-{@code String} method on 744 * {@link SmileHarness} takes a module ID, and {@code fhirRequest("my_endpoint")} would otherwise 745 * issue against the default module and report a 404 from a module the caller never named. 746 * <p> 747 * An empty path is allowed: it addresses the module's base URL, where a transaction bundle is 748 * posted. 749 */ 750 private static String requirePath(String thePath) { 751 if (!thePath.isEmpty() && !thePath.startsWith("/")) { 752 throw new IllegalArgumentException( 753 "Path must begin with a slash; a module ID belongs in the two-argument overload. [path=%s]" 754 .formatted(thePath)); 755 } 756 return thePath; 757 } 758 759 /** 760 * The port a module configured with {@code thePort} is actually published on. Every URL this 761 * harness builds goes through here, so that an unresolvable port fails with the port that could 762 * not be mapped rather than with a URL containing the literal {@literal null}. 763 */ 764 private int resolvePort(int thePort) { 765 Integer resolvedPort = portResolver.apply(thePort); 766 if (resolvedPort == null) { 767 throw unmappedPort(String.valueOf(thePort)); 768 } 769 return resolvedPort; 770 } 771 772 /** 773 * Gets the only persistence module's FhirContext. 774 * If More or less than 1 persistence modules are present, throws {@link IllegalStateException}.} 775 * <p> 776 * See {@link #getFhirContext(String)} if you have multiple persistence modules. 777 * 778 * @return the {@link FhirContext} of the only persistence module.} 779 */ 780 @Override 781 public FhirContext getFhirContext() { 782 NodeConfigurations nodeConfigs = getAdminJsonClient().getNodeConfigurations(); 783 Set<String> persistenceModuleIds = new HashSet<>(); 784 785 for (NodeConfigurations.NodeConfiguration node : nodeConfigs.getNodes()) { 786 for (NodeConfigurations.ModuleConfiguration module : node.getModules()) { 787 String moduleType = module.getModuleType(); 788 if (moduleType != null && moduleType.startsWith("PERSISTENCE_")) { 789 persistenceModuleIds.add(module.getModuleId()); 790 } 791 } 792 } 793 794 if (persistenceModuleIds.size() > 1) { 795 throw new IllegalStateException( 796 "Multiple different persistence modules found in the configuration, please specify. " 797 + String.join(", ", persistenceModuleIds)); 798 } else { 799 return persistenceModuleIds.stream() 800 .map(this::getFhirContext) 801 .findFirst() 802 .orElseThrow(() -> new IllegalStateException("No persistence module found in the configuration.")); 803 } 804 } 805 806 /** 807 * Get the FHIR context for a specific persistence/fhir endpoint module. 808 * @param moduleId The ID of the persistence or FHIR endpoint module to get the FHIR context for 809 * @return The FHIR context for the specified module 810 * @throws IllegalStateException if the module is not found or has an unsupported type 811 */ 812 @Override 813 public FhirContext getFhirContext(String moduleId) { 814 return resolveFhirContext(getAdminJsonClient().getNodeConfigurations(), moduleId); 815 } 816 817 private FhirContext resolveFhirContext(NodeConfigurations theNodeConfigs, String theModuleId) { 818 Validate.notEmpty(theModuleId, "Module ID is required"); 819 820 NodeConfigurations.ModuleConfiguration module = moduleIn(theNodeConfigs, theModuleId) 821 .orElseThrow( 822 () -> new IllegalArgumentException("No module found. [moduleId=%s]".formatted(theModuleId))); 823 824 return fhirContextOf(theNodeConfigs, module) 825 .orElseThrow(() -> new IllegalArgumentException( 826 "Could not retrieve a FhirContext from the provided module. [moduleId=%s, module_type=%s]" 827 .formatted(theModuleId, module.getModuleType()))); 828 } 829 830 /** 831 * A module's FHIR version comes from one of two places: a version marker in its own type 832 * ({@code ENDPOINT_FHIR_REST_R4}), or — for the types that carry no version — whatever the 833 * module points at. Empty when the type offers neither. 834 */ 835 private Optional<FhirContext> fhirContextOf( 836 NodeConfigurations theNodeConfigs, NodeConfigurations.ModuleConfiguration theModule) { 837 String moduleType = theModule.getModuleType(); 838 if (moduleType == null) { 839 return Optional.empty(); 840 } 841 return fhirContextFromVersionMarker(moduleType) 842 .or(() -> fhirContextFromDelegatingType(theNodeConfigs, theModule, moduleType)); 843 } 844 845 private static Optional<FhirContext> fhirContextFromVersionMarker(String theModuleType) { 846 return CONTEXT_BY_VERSION_MARKER.stream() 847 .filter(marker -> theModuleType.contains(marker.getKey())) 848 .findFirst() 849 .map(marker -> marker.getValue().get()); 850 } 851 852 /** 853 * The types that name no version of their own: the FHIR endpoint takes its version from the 854 * persistence module it depends on, and the other two read it from their configuration. 855 */ 856 private Optional<FhirContext> fhirContextFromDelegatingType( 857 NodeConfigurations theNodeConfigs, NodeConfigurations.ModuleConfiguration theModule, String theModuleType) { 858 return switch (theModuleType) { 859 case "ENDPOINT_FHIR_REST" -> persistenceModuleIdOf(theModule) 860 .map(targetModuleId -> resolveFhirContext(theNodeConfigs, targetModuleId)); 861 case "ENDPOINT_FHIR_GATEWAY" -> Optional.of( 862 fhirContextForVersion(theModule.getConfigProperty("fhir_version"))); 863 case "ENDPOINT_HYBRID_PROVIDERS" -> Optional.of( 864 fhirContextForVersion(theModule.getConfigProperty("definitions.fhir_version"))); 865 default -> Optional.empty(); 866 }; 867 } 868 869 private static Optional<String> persistenceModuleIdOf(NodeConfigurations.ModuleConfiguration theModule) { 870 return theModule.getDependencies().stream() 871 .filter(dependency -> dependency.getDependencyType().startsWith("PERSISTENCE_")) 872 .map(NodeConfigurations.ModuleDependency::getTargetModuleId) 873 .findFirst(); 874 } 875 876 private static FhirContext fhirContextForVersion(String theFhirVersion) { 877 return FhirContext.forCached(FhirVersionEnum.forVersionString(theFhirVersion)); 878 } 879 880 @Override 881 public HL7V2RestClient getHL7V2RestClient() { 882 Optional<Map.Entry<String, Integer>> discovered = defaultModule(myEndpointHl7V2PortMap, null); 883 if (discovered.isPresent()) { 884 return getHL7V2RestClient(discovered.get().getKey()); 885 } 886 ourLog.warn("No HL7v2 endpoint found in configuration, using default port {}", DEFAULT_HL7V2_PORT); 887 return getHL7V2RestClient(DEFAULT_HL7V2_PORT); 888 } 889 890 @Override 891 public HL7V2RestClient getHL7V2RestClient(int thePort) { 892 return hl7V2RestClientAt(addressAt(thePort)); 893 } 894 895 @Override 896 public HL7V2RestClient getHL7V2RestClient(String theModuleId) { 897 return hl7V2RestClientAt(addressOf(theModuleId)); 898 } 899 900 private HL7V2RestClient hl7V2RestClientAt(ModuleAddress theAddress) { 901 // The HL7v2 client posts to its base URL itself, so it takes that URL without a trailing slash. 902 return HL7V2RestClient.issuingOn(myHttpClient, baseUrl(theAddress), myContext.username(), myContext.password()); 903 } 904 905 @Override 906 public OutboundSmartClient getOutboundSmartClient() { 907 return defaultModule(mySmartEndpointPortMap, DEFAULT_SMART_MODULE_ID) 908 .map(module -> getOutboundSmartClient(module.getKey())) 909 .orElseThrow(() -> new IllegalStateException( 910 "No SMART endpoint found in the configuration for OutboundSmartClient.")); 911 } 912 913 @Override 914 public OutboundSmartClient getOutboundSmartClient(int thePort) { 915 return outboundSmartClientAt(addressAt(thePort)); 916 } 917 918 @Override 919 public OutboundSmartClient getOutboundSmartClient(String theModuleId) { 920 return outboundSmartClientAt(addressOf(theModuleId)); 921 } 922 923 private OutboundSmartClient outboundSmartClientAt(ModuleAddress theAddress) { 924 String baseUrl = baseUrl(theAddress); 925 RestClient restClient = RestClient.builder() 926 .requestFactory(RequestFactoryUtil.wrap(myHttpClient)) 927 .baseUrl(UrlPathUtil.withTrailingSlash(baseUrl)) 928 .build(); 929 return new OutboundSmartClient(restClient, baseUrl); 930 } 931 932 @Override 933 public NpmPackageClient getNpmPackageClient() { 934 // Look for the first available Package Registry module 935 Optional<Map.Entry<String, Integer>> discovered = defaultModule(myPackageRegistryPortMap, null); 936 if (discovered.isPresent()) { 937 return getNpmPackageClient(discovered.get().getKey()); 938 } else { 939 // Fall back to default port 8002 if no modules discovered 940 ourLog.warn("No Package Registry endpoint found in configuration, using default port 8002"); 941 return getNpmPackageClient(8002); 942 } 943 } 944 945 @Override 946 public NpmPackageClient getNpmPackageClient(int thePort) { 947 return npmPackageClientAt(addressAt(thePort)); 948 } 949 950 @Override 951 public NpmPackageClient getNpmPackageClient(String theModuleId) { 952 return npmPackageClientAt(addressOf(theModuleId)); 953 } 954 955 @Override 956 public @Nonnull SmartHealthLinkClient getSmartHealthLinkClient(@Nonnull String theModuleId) { 957 return SmartHealthLinkClient.issuingOn( 958 myHttpClient, restClientBaseUrl(addressOf(theModuleId)), myContext.username(), myContext.password()); 959 } 960 961 @Override 962 public @Nonnull SmilePortalClient getSmilePortalClient(@Nonnull String theModuleId) { 963 return SmilePortalClient.issuingOn( 964 myHttpClient, restClientBaseUrl(addressOf(theModuleId)), myContext.username(), myContext.password()); 965 } 966 967 private NpmPackageClient npmPackageClientAt(ModuleAddress theAddress) { 968 return NpmPackageClient.issuingOn( 969 myHttpClient, restClientBaseUrl(theAddress), myContext.username(), myContext.password()); 970 } 971 972 @Override 973 public @Nonnull CdsHooksClient getCdsHooksClient() { 974 return defaultModule(myCdsHooksPortMap, null) 975 .map(module -> getCdsHooksClient(module.getKey())) 976 .orElseThrow(() -> new IllegalStateException("No CDS Hooks endpoint found in the configuration.")); 977 } 978 979 @Override 980 public @Nonnull CdsHooksClient getCdsHooksClient(int thePort) { 981 return cdsHooksClientAt(addressAt(thePort)); 982 } 983 984 @Override 985 public @Nonnull CdsHooksClient getCdsHooksClient(@Nonnull String theModuleId) { 986 return cdsHooksClientAt(addressOf(theModuleId)); 987 } 988 989 private CdsHooksClient cdsHooksClientAt(ModuleAddress theAddress) { 990 return CdsHooksClient.issuingOn(myHttpClient, baseUrl(theAddress), myContext.username(), myContext.password()); 991 } 992}