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.clients;
011
012import ca.cdr.test.app.clients.common.HttpClientOwnership;
013import ca.cdr.test.app.clients.common.RequestFactoryUtil;
014import ca.cdr.test.app.clients.common.SmileTestHttpClient;
015import ca.uhn.fhir.jpa.packages.NpmPackageAssetInfoListJson;
016import ca.uhn.fhir.jpa.packages.NpmPackageMetadataJson;
017import ca.uhn.fhir.jpa.packages.NpmPackageSearchResultJson;
018import ca.uhn.fhir.jpa.packages.PackageDeleteOutcomeJson;
019import ca.uhn.fhir.jpa.packages.PackageInstallOutcomeJson;
020import ca.uhn.fhir.jpa.packages.PackageInstallationSpec;
021import ca.uhn.fhir.jpa.packages.PackageInstallationStatusJson;
022import jakarta.annotation.Nonnull;
023import jakarta.annotation.Nullable;
024import org.apache.commons.lang3.Validate;
025import org.slf4j.Logger;
026import org.slf4j.LoggerFactory;
027import org.springframework.http.HttpHeaders;
028import org.springframework.http.HttpStatus;
029import org.springframework.http.MediaType;
030import org.springframework.http.ResponseEntity;
031import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
032import org.springframework.http.client.support.BasicAuthenticationInterceptor;
033import org.springframework.util.MultiValueMap;
034import org.springframework.web.client.RestClient;
035import org.springframework.web.util.UriComponentsBuilder;
036
037import java.util.Objects;
038
039/**
040 * NpmPackageClient is a client for the NPM Package Registry API of the CDR.
041 * It currently supports anonymous and http-basic authentication.
042 *
043 * This client provides access to package installation operations through
044 * Smile CDR's package registry endpoint, typically running on port 8002.
045 */
046public class NpmPackageClient implements AutoCloseable {
047        private static final Logger ourLog = LoggerFactory.getLogger(NpmPackageClient.class);
048
049        private final RestClient myRestClient;
050
051        /**
052         * The client this one issues on, and whether closing this client should release it.
053         * {@literal null} for a client built from a {@link RestClient} directly, which brought no
054         * connection pool of its own.
055         */
056        private final HttpClientOwnership myOwnership;
057
058        NpmPackageClient(RestClient theRestClient) {
059                this(theRestClient, null);
060        }
061
062        private NpmPackageClient(RestClient theRestClient, @Nullable HttpClientOwnership theOwnership) {
063                myRestClient = theRestClient;
064                myOwnership = theOwnership;
065        }
066
067        /**
068         * Build an NpmPackageClient with authentication
069         * @param theBaseUrl The base URL of the package registry
070         * @param theUsername Username for authentication
071         * @param thePassword Password for authentication
072         * @return Configured NpmPackageClient
073         */
074        /**
075         * Opens a client authenticating as the given user, over a connection pool of its own.
076         * <p>
077         * The caller owns the pool: open this in a try-with-resources block, or close it from an
078         * {@code @AfterAll} when it is a field. Use
079         * {@link #issuingOn(SmileTestHttpClient, String, String, String)} instead where a client to
080         * issue on already exists.
081         *
082         * @param theBaseUrl the base URL of the package registry
083         * @param theUsername the user to authenticate as
084         * @param thePassword that user's password
085         */
086        public static @Nonnull NpmPackageClient open(
087                        @Nonnull String theBaseUrl, @Nonnull String theUsername, @Nonnull String thePassword) {
088                return authenticatedClient(HttpClientOwnership.resolve(null), theBaseUrl, theUsername, thePassword);
089        }
090
091        /**
092         * Opens a client sending no credentials, over a connection pool of its own.
093         * <p>
094         * The caller owns the pool — see {@link #open(String, String, String)}.
095         *
096         * @param theBaseUrl the base URL of the package registry
097         */
098        public static @Nonnull NpmPackageClient openAnonymous(@Nonnull String theBaseUrl) {
099                HttpClientOwnership ownership = HttpClientOwnership.resolve(null);
100
101                return new NpmPackageClient(
102                                builderForUrlWithJsonDefault(theBaseUrl, ownership.client()).build(), ownership);
103        }
104
105        /**
106         * Builds a client that issues its requests on {@code theHttpClient}, sharing that client's
107         * connection pool and cookie store with everything else built over it.
108         * <p>
109         * The pool stays the caller's: {@link #close()} leaves it open, so there is nothing here for the
110         * caller to release. Use {@link #open(String, String, String)} to build a pool of your own.
111         *
112         * @param theHttpClient the client to issue on, which the caller keeps ownership of
113         * @param theBaseUrl the base URL of the package registry
114         * @param theUsername the user to authenticate as
115         * @param thePassword that user's password
116         * @see ca.cdr.test.app.clients.common.RequestFactoryUtil#wrap(SmileTestHttpClient)
117         */
118        public static @Nonnull NpmPackageClient issuingOn(
119                        @Nonnull SmileTestHttpClient theHttpClient,
120                        @Nonnull String theBaseUrl,
121                        @Nonnull String theUsername,
122                        @Nonnull String thePassword) {
123                return authenticatedClient(HttpClientOwnership.resolve(theHttpClient), theBaseUrl, theUsername, thePassword);
124        }
125
126        private static @Nonnull NpmPackageClient authenticatedClient(
127                        @Nonnull HttpClientOwnership theOwnership,
128                        @Nonnull String theBaseUrl,
129                        @Nonnull String theUsername,
130                        @Nonnull String thePassword) {
131                RestClient restClient = builderForUrlWithJsonDefault(theBaseUrl, theOwnership.client())
132                                .requestInterceptor(new BasicAuthenticationInterceptor(theUsername, thePassword))
133                                .build();
134
135                return new NpmPackageClient(restClient, theOwnership);
136        }
137
138        /**
139         * @deprecated Use {@link #open(String, String, String)}, whose name says that the client owns the
140         *    connection pool it returns and that the caller has to close it.
141         */
142        @Deprecated(since = "2026.11.R01", forRemoval = true)
143        public static @Nonnull NpmPackageClient build(
144                        @Nonnull String theBaseUrl, @Nonnull String theUsername, @Nonnull String thePassword) {
145                return open(theBaseUrl, theUsername, thePassword);
146        }
147
148        /**
149         * @deprecated Use {@link #openAnonymous(String)}, whose name says that the client owns the
150         *    connection pool it returns and that the caller has to close it.
151         */
152        @Deprecated(since = "2026.11.R01", forRemoval = true)
153        public static @Nonnull NpmPackageClient buildAnonymous(@Nonnull String theBaseUrl) {
154                return openAnonymous(theBaseUrl);
155        }
156
157        /**
158         * Install a package using the provided specification
159         * @param theSpec The package installation specification
160         * @return The installation outcome
161         */
162        @Nonnull
163        public PackageInstallOutcomeJson installPackageBySpec(PackageInstallationSpec theSpec) {
164                Validate.notNull(theSpec, "Package specification is required");
165                Validate.notEmpty(theSpec.getName(), "Package name is required");
166                Validate.notEmpty(theSpec.getVersion(), "Package version is required");
167
168                ourLog.info("Installing package {}#{}", theSpec.getName(), theSpec.getVersion());
169
170                PackageInstallOutcomeJson result = myRestClient
171                                .put()
172                                .uri("/write/install/by-spec")
173                                .body(theSpec)
174                                .contentType(MediaType.APPLICATION_JSON)
175                                .retrieve()
176                                .body(PackageInstallOutcomeJson.class);
177                return Objects.requireNonNull(result);
178        }
179
180        /**
181         * Install a package using the provided specification as a JSON string
182         * @param theSpecJson The package installation specification as JSON string
183         * @return The installation outcome
184         */
185        @Nonnull
186        public PackageInstallOutcomeJson installPackageBySpec(String theSpecJson) {
187                Validate.notEmpty(theSpecJson, "Package specification JSON is required");
188
189                ourLog.info("Installing package from JSON specification: {}", theSpecJson);
190
191                PackageInstallOutcomeJson result = myRestClient
192                                .put()
193                                .uri("/write/install/by-spec")
194                                .contentType(MediaType.APPLICATION_JSON)
195                                .body(theSpecJson)
196                                .retrieve()
197                                .body(PackageInstallOutcomeJson.class);
198                return Objects.requireNonNull(result);
199        }
200
201        @Nonnull
202        public String installPackageBySpecAsync(@Nonnull PackageInstallationSpec theSpec) {
203                Validate.notNull(theSpec, "Package specification is required");
204
205                ResponseEntity<Void> response = myRestClient
206                                .put()
207                                .uri("/write/install/by-spec")
208                                .header("Prefer", "respond-async")
209                                .contentType(MediaType.APPLICATION_JSON)
210                                .body(theSpec)
211                                .retrieve()
212                                .toBodilessEntity();
213                Validate.isTrue(
214                                response.getStatusCode().isSameCodeAs(HttpStatus.ACCEPTED),
215                                "Expected 202 Accepted for an async install but got %s",
216                                response.getStatusCode());
217                String pollLocation = Validate.notEmpty(
218                                response.getHeaders().getFirst(HttpHeaders.CONTENT_LOCATION),
219                                "Async install response had no Content-Location");
220                String jobId = UriComponentsBuilder.fromUriString(pollLocation)
221                                .build()
222                                .getQueryParams()
223                                .getFirst("_jobId");
224                return Validate.notEmpty(jobId, "Content-Location %s had no _jobId", pollLocation);
225        }
226
227        @Nonnull
228        public PackageInstallationStatusJson getInstallationStatus(String theJobId) {
229                Validate.notEmpty(theJobId, "Job ID is required");
230
231                PackageInstallationStatusJson result = myRestClient
232                                .get()
233                                .uri("/write/install/status?_jobId={jobId}", theJobId)
234                                .retrieve()
235                                .body(PackageInstallationStatusJson.class);
236                return Objects.requireNonNull(result);
237        }
238
239        @Nonnull
240        public PackageInstallOutcomeJson installPackageByParam(
241                        String theName,
242                        String theVersion,
243                        boolean theFetchDependencies,
244                        @Nonnull PackageInstallationSpec.InstallModeEnum theInstallMode,
245                        @Nonnull PackageInstallationSpec.VersionPolicyEnum theVersionPolicy) {
246                Validate.notEmpty(theName, "Package name is required");
247                Validate.notEmpty(theVersion, "Package version is required");
248
249                PackageInstallOutcomeJson result = myRestClient
250                                .put()
251                                .uri(builder -> builder.path("/write/install/by-param")
252                                                .queryParam("name", theName)
253                                                .queryParam("version", theVersion)
254                                                .queryParam("fetchDependencies", theFetchDependencies)
255                                                .queryParam("installMode", theInstallMode)
256                                                .queryParam("versionPolicy", theVersionPolicy)
257                                                .build())
258                                .retrieve()
259                                .body(PackageInstallOutcomeJson.class);
260                return Objects.requireNonNull(result);
261        }
262
263        @Nonnull
264        public PackageDeleteOutcomeJson deletePackage(String theName, String theVersion) {
265                Validate.notEmpty(theName, "Package name is required");
266                Validate.notEmpty(theVersion, "Package version is required");
267
268                PackageDeleteOutcomeJson result = myRestClient
269                                .delete()
270                                .uri("/write/{name}/{version}", theName, theVersion)
271                                .retrieve()
272                                .body(PackageDeleteOutcomeJson.class);
273                return Objects.requireNonNull(result);
274        }
275
276        @Nonnull
277        public NpmPackageSearchResultJson searchPackages(@Nonnull MultiValueMap<String, String> theQueryParams) {
278                NpmPackageSearchResultJson result = myRestClient
279                                .get()
280                                .uri(builder -> builder.path("/npm/-/v1/search")
281                                                .queryParams(theQueryParams)
282                                                .build())
283                                .retrieve()
284                                .body(NpmPackageSearchResultJson.class);
285                return Objects.requireNonNull(result);
286        }
287
288        @Nonnull
289        public NpmPackageMetadataJson getPackageMetadata(String theName) {
290                Validate.notEmpty(theName, "Package name is required");
291
292                NpmPackageMetadataJson result =
293                                myRestClient.get().uri("/npm/{name}", theName).retrieve().body(NpmPackageMetadataJson.class);
294                return Objects.requireNonNull(result);
295        }
296
297        @Nonnull
298        public NpmPackageAssetInfoListJson findPackageAssetInfoByUrl(String theFhirVersion, String theCanonicalUrl) {
299                Validate.notEmpty(theFhirVersion, "FHIR version is required");
300                Validate.notEmpty(theCanonicalUrl, "Canonical URL is required");
301
302                NpmPackageAssetInfoListJson result = myRestClient
303                                .get()
304                                .uri(builder -> builder.path("/npm/-/v1/findPackageAssetInfoByUrl")
305                                                .queryParam("_fhirVersion", theFhirVersion)
306                                                .queryParam("_canonicalUrl", theCanonicalUrl)
307                                                .build())
308                                .retrieve()
309                                .body(NpmPackageAssetInfoListJson.class);
310                return Objects.requireNonNull(result);
311        }
312
313        /**
314         * Create a RestClient builder configured for JSON communication
315         * @param theBaseUrl The base URL
316         * @return Configured RestClient builder
317         */
318        private static @Nonnull RestClient.Builder builderForUrlWithJsonDefault(
319                        String theBaseUrl, @Nonnull SmileTestHttpClient theHttpClient) {
320                HttpComponentsClientHttpRequestFactory requestFactory = RequestFactoryUtil.wrap(theHttpClient);
321
322                return RestClient.builder()
323                                .baseUrl(theBaseUrl)
324                                .requestFactory(requestFactory)
325                                // This sets the default content type to JSON, but allows the actual request to override it.
326                                .defaultRequest(r -> r.accept(MediaType.APPLICATION_JSON));
327        }
328
329        /**
330         * Releases the connection pool this client built for itself. A no-op when the client was built
331         * over one supplied by a caller, which owns its own pool.
332         */
333        @Override
334        public void close() {
335                if (myOwnership != null) {
336                        myOwnership.closeIfOwned();
337                }
338        }
339}