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.api.fhir.client.IExtendedGenericClient;
013import ca.cdr.api.model.json.oauth.SmartConfigurationJson;
014import ca.uhn.fhir.context.FhirContext;
015import ca.uhn.fhir.interceptor.api.IInterceptorService;
016import ca.uhn.fhir.jpa.bulk.export.model.BulkExportResponseJson;
017import ca.uhn.fhir.jpa.model.util.JpaConstants;
018import ca.uhn.fhir.model.primitive.IdDt;
019import ca.uhn.fhir.model.primitive.UriDt;
020import ca.uhn.fhir.rest.api.Constants;
021import ca.uhn.fhir.rest.api.EncodingEnum;
022import ca.uhn.fhir.rest.api.MethodOutcome;
023import ca.uhn.fhir.rest.api.RequestFormatParamStyleEnum;
024import ca.uhn.fhir.rest.api.SummaryEnum;
025import ca.uhn.fhir.rest.api.server.bulk.BulkExportJobParameters;
026import ca.uhn.fhir.rest.client.api.IGenericClient;
027import ca.uhn.fhir.rest.client.api.IHttpClient;
028import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException;
029import ca.uhn.fhir.rest.gclient.ICreate;
030import ca.uhn.fhir.rest.gclient.IDelete;
031import ca.uhn.fhir.rest.gclient.IFetchConformanceUntyped;
032import ca.uhn.fhir.rest.gclient.IGetPage;
033import ca.uhn.fhir.rest.gclient.IHistory;
034import ca.uhn.fhir.rest.gclient.IMeta;
035import ca.uhn.fhir.rest.gclient.IOperation;
036import ca.uhn.fhir.rest.gclient.IPatch;
037import ca.uhn.fhir.rest.gclient.IRawHttp;
038import ca.uhn.fhir.rest.gclient.IRead;
039import ca.uhn.fhir.rest.gclient.ITransaction;
040import ca.uhn.fhir.rest.gclient.IUntypedQuery;
041import ca.uhn.fhir.rest.gclient.IUpdate;
042import ca.uhn.fhir.rest.gclient.IValidate;
043import ca.uhn.fhir.rest.server.provider.ProviderConstants;
044import ca.uhn.fhir.test.utilities.HttpTestRequest;
045import ca.uhn.fhir.test.utilities.HttpTestResponse;
046import ca.uhn.fhir.util.ParametersUtil;
047import jakarta.annotation.Nonnull;
048import jakarta.annotation.Nullable;
049import org.hl7.fhir.instance.model.api.IBaseBundle;
050import org.hl7.fhir.instance.model.api.IBaseParameters;
051import org.hl7.fhir.instance.model.api.IBaseResource;
052import org.hl7.fhir.instance.model.api.IPrimitiveType;
053import tools.jackson.core.JacksonException;
054import tools.jackson.databind.json.JsonMapper;
055
056import java.time.Duration;
057import java.time.Instant;
058import java.util.Date;
059import java.util.Objects;
060import java.util.function.Function;
061
062public class CdrFhirClient implements IExtendedGenericClient {
063
064        private final IGenericClient myDelegate;
065        private final Function<String, HttpTestRequest> myPathRequests;
066        private final Function<String, HttpTestRequest> myServerUrlRequests;
067
068        public CdrFhirClient(
069                        @Nonnull IGenericClient theDelegate,
070                        @Nonnull Function<String, HttpTestRequest> thePathRequests,
071                        @Nonnull Function<String, HttpTestRequest> theServerUrlRequests) {
072                myDelegate = Objects.requireNonNull(theDelegate);
073                myPathRequests = Objects.requireNonNull(thePathRequests);
074                myServerUrlRequests = Objects.requireNonNull(theServerUrlRequests);
075        }
076
077        @Override
078        @Nonnull
079        public SmartConfigurationJson getSmartConfiguration() {
080                HttpTestResponse response =
081                                myPathRequests.apply("/.well-known/smart-configuration").get().assertStatus(200);
082                try {
083                        return JsonMapper.builderWithJackson2Defaults()
084                                        .build()
085                                        .readValue(response.getBody(), SmartConfigurationJson.class);
086                } catch (JacksonException e) {
087                        throw new IllegalStateException("Unparseable smart-configuration: " + response.getBody(), e);
088                }
089        }
090
091        @Override
092        @Nonnull
093        public String startBulkExport(@Nonnull BulkExportJobParameters theParameters) {
094                FhirContext fhirContext = getFhirContext();
095                IBaseParameters body = ParametersUtil.newInstance(fhirContext);
096                String outputFormat = theParameters.getOutputFormat();
097                ParametersUtil.addParameterToParametersString(
098                                fhirContext,
099                                body,
100                                JpaConstants.PARAM_EXPORT_OUTPUT_FORMAT,
101                                outputFormat == null ? Constants.CT_FHIR_NDJSON : outputFormat);
102                if (!theParameters.getResourceTypes().isEmpty()) {
103                        ParametersUtil.addParameterToParametersString(
104                                        fhirContext,
105                                        body,
106                                        JpaConstants.PARAM_EXPORT_TYPE,
107                                        String.join(",", theParameters.getResourceTypes()));
108                }
109                addInstant(fhirContext, body, JpaConstants.PARAM_EXPORT_SINCE, theParameters.getSince());
110                addInstant(fhirContext, body, JpaConstants.PARAM_EXPORT_UNTIL, theParameters.getUntil());
111                theParameters
112                                .getFilters()
113                                .forEach(filter -> ParametersUtil.addParameterToParametersString(
114                                                fhirContext, body, JpaConstants.PARAM_EXPORT_TYPE_FILTER, filter));
115                theParameters
116                                .getPostFetchFilterUrls()
117                                .forEach(url -> ParametersUtil.addParameterToParametersString(
118                                                fhirContext, body, JpaConstants.PARAM_EXPORT_TYPE_POST_FETCH_FILTER_URL, url));
119                theParameters
120                                .getPatientIds()
121                                .forEach(patientId -> ParametersUtil.addParameterToParametersReference(
122                                                fhirContext, body, JpaConstants.PARAM_EXPORT_PATIENT, patientId));
123                theParameters
124                                .getExpandMdm()
125                                .ifPresent(expandMdm -> ParametersUtil.addParameterToParametersBoolean(
126                                                fhirContext, body, JpaConstants.PARAM_EXPORT_MDM, expandMdm));
127                if (theParameters.getExportIdentifier() != null) {
128                        ParametersUtil.addParameterToParametersString(
129                                        fhirContext, body, JpaConstants.PARAM_EXPORT_IDENTIFIER, theParameters.getExportIdentifier());
130                }
131                if (theParameters.isIncludeHistory()) {
132                        ParametersUtil.addParameterToParametersBoolean(
133                                        fhirContext, body, JpaConstants.PARAM_EXPORT_INCLUDE_HISTORY, true);
134                }
135
136                HttpTestResponse response = myPathRequests
137                                .apply(bulkExportPath(theParameters))
138                                .withHeader("Prefer", "respond-async")
139                                .withHeader("Cache-Control", "no-cache")
140                                .post(body)
141                                .assertStatus(202);
142                String pollUrl = response.getHeader("Content-Location");
143                if (pollUrl == null || pollUrl.isBlank()) {
144                        throw new AssertionError("202 Accepted carried no Content-Location");
145                }
146                return pollUrl;
147        }
148
149        @Override
150        @Nonnull
151        public BulkExportResponseJson awaitBulkExport(@Nonnull String thePollUrl) {
152                return awaitBulkExport(thePollUrl, Duration.ofMinutes(5), Duration.ofSeconds(1));
153        }
154
155        @Override
156        @Nonnull
157        public BulkExportResponseJson awaitBulkExport(
158                        @Nonnull String thePollUrl, @Nonnull Duration theTimeout, @Nonnull Duration thePollInterval) {
159                Instant deadline = Instant.now().plus(theTimeout);
160                while (true) {
161                        HttpTestResponse response = myServerUrlRequests.apply(thePollUrl).get();
162                        if (response.getStatusCode() == 200) {
163                                return JsonMapper.builder().build().readValue(response.getBody(), BulkExportResponseJson.class);
164                        }
165                        if (response.getStatusCode() != 202) {
166                                throw new AssertionError("Bulk export at " + thePollUrl + " failed with HTTP "
167                                                + response.getStatusCode() + ": " + response.getBody());
168                        }
169                        if (Instant.now().isAfter(deadline)) {
170                                throw new AssertionError("Bulk export at " + thePollUrl + " still in progress after " + theTimeout
171                                                + " (X-Progress: " + response.getHeader("X-Progress") + ")");
172                        }
173                        try {
174                                Thread.sleep(thePollInterval.toMillis());
175                        } catch (InterruptedException e) {
176                                Thread.currentThread().interrupt();
177                                throw new IllegalStateException("Interrupted awaiting bulk export at " + thePollUrl, e);
178                        }
179                }
180        }
181
182        private static String bulkExportPath(BulkExportJobParameters theParameters) {
183                BulkExportJobParameters.ExportStyle style = theParameters.getExportStyle();
184                if (style == null || style == BulkExportJobParameters.ExportStyle.SYSTEM) {
185                        return "/" + ProviderConstants.OPERATION_EXPORT;
186                }
187                if (style == BulkExportJobParameters.ExportStyle.PATIENT) {
188                        return "/Patient/" + ProviderConstants.OPERATION_EXPORT;
189                }
190                String groupId = theParameters.getGroupId();
191                if (groupId == null || groupId.isBlank()) {
192                        throw new IllegalArgumentException("A GROUP export needs a group ID");
193                }
194                return "/Group/" + groupId.replaceFirst("^Group/", "") + "/" + ProviderConstants.OPERATION_EXPORT;
195        }
196
197        @SuppressWarnings("unchecked")
198        private static void addInstant(
199                        FhirContext theFhirContext, IBaseParameters theBody, String theName, @Nullable Date theValue) {
200                if (theValue == null) {
201                        return;
202                }
203                IPrimitiveType<Date> instant =
204                                (IPrimitiveType<Date>) Objects.requireNonNull(theFhirContext.getElementDefinition("instant"))
205                                                .newInstance();
206                instant.setValue(theValue);
207                ParametersUtil.addParameterToParameters(theFhirContext, theBody, theName, instant);
208        }
209
210        @Override
211        public IFetchConformanceUntyped capabilities() {
212                return myDelegate.capabilities();
213        }
214
215        @Override
216        public ICreate create() {
217                return myDelegate.create();
218        }
219
220        @Override
221        public IDelete delete() {
222                return myDelegate.delete();
223        }
224
225        @Override
226        @Deprecated(since = "3.0.0", forRemoval = true)
227        public IFetchConformanceUntyped fetchConformance() {
228                return myDelegate.fetchConformance();
229        }
230
231        @Override
232        public void forceConformanceCheck() throws FhirClientConnectionException {
233                myDelegate.forceConformanceCheck();
234        }
235
236        @Override
237        public IHistory history() {
238                return myDelegate.history();
239        }
240
241        @Override
242        public IGetPage loadPage() {
243                return myDelegate.loadPage();
244        }
245
246        @Override
247        public IMeta meta() {
248                return myDelegate.meta();
249        }
250
251        @Override
252        public IOperation operation() {
253                return myDelegate.operation();
254        }
255
256        @Override
257        public IPatch patch() {
258                return myDelegate.patch();
259        }
260
261        @Override
262        public IRead read() {
263                return myDelegate.read();
264        }
265
266        @Override
267        public IRawHttp rawHttpRequest() {
268                return myDelegate.rawHttpRequest();
269        }
270
271        @Override
272        @Deprecated
273        public <T extends IBaseResource> T read(Class<T> theType, String theUrl) {
274                return myDelegate.read(theType, theUrl);
275        }
276
277        @Override
278        @Deprecated
279        public <T extends IBaseResource> T read(Class<T> theType, UriDt theUrl) {
280                return myDelegate.read(theType, theUrl);
281        }
282
283        @Override
284        @Deprecated
285        public IBaseResource read(UriDt theUrl) {
286                return myDelegate.read(theUrl);
287        }
288
289        @Override
290        public void registerInterceptor(Object theInterceptor) {
291                myDelegate.registerInterceptor(theInterceptor);
292        }
293
294        @Override
295        public <T extends IBaseBundle> IUntypedQuery<T> search() {
296                return myDelegate.search();
297        }
298
299        @Override
300        @Deprecated
301        public void setLogRequestAndResponse(boolean theLogRequestAndResponse) {
302                myDelegate.setLogRequestAndResponse(theLogRequestAndResponse);
303        }
304
305        @Override
306        public ITransaction transaction() {
307                return myDelegate.transaction();
308        }
309
310        @Override
311        public void unregisterInterceptor(Object theInterceptor) {
312                myDelegate.unregisterInterceptor(theInterceptor);
313        }
314
315        @Override
316        public IUpdate update() {
317                return myDelegate.update();
318        }
319
320        @Override
321        @Deprecated
322        public MethodOutcome update(IdDt theId, IBaseResource theResource) {
323                return myDelegate.update(theId, theResource);
324        }
325
326        @Override
327        @Deprecated
328        public MethodOutcome update(String theId, IBaseResource theResource) {
329                return myDelegate.update(theId, theResource);
330        }
331
332        @Override
333        public IValidate validate() {
334                return myDelegate.validate();
335        }
336
337        @Override
338        @Deprecated
339        public MethodOutcome validate(IBaseResource theResource) {
340                return myDelegate.validate(theResource);
341        }
342
343        @Override
344        @Deprecated
345        public <T extends IBaseResource> T vread(Class<T> theType, IdDt theId) {
346                return myDelegate.vread(theType, theId);
347        }
348
349        @Override
350        @Deprecated
351        public <T extends IBaseResource> T vread(Class<T> theType, String theId, String theVersionId) {
352                return myDelegate.vread(theType, theId, theVersionId);
353        }
354
355        @Override
356        public IInterceptorService getInterceptorService() {
357                return myDelegate.getInterceptorService();
358        }
359
360        @Override
361        public void setInterceptorService(@Nonnull IInterceptorService theInterceptorService) {
362                myDelegate.setInterceptorService(theInterceptorService);
363        }
364
365        @Override
366        public <T extends IBaseResource> T fetchResourceFromUrl(Class<T> theResourceType, String theUrl) {
367                return myDelegate.fetchResourceFromUrl(theResourceType, theUrl);
368        }
369
370        @Override
371        public EncodingEnum getEncoding() {
372                return myDelegate.getEncoding();
373        }
374
375        @Override
376        public void setEncoding(EncodingEnum theEncoding) {
377                myDelegate.setEncoding(theEncoding);
378        }
379
380        @Override
381        public FhirContext getFhirContext() {
382                return myDelegate.getFhirContext();
383        }
384
385        @Override
386        public IHttpClient getHttpClient() {
387                return myDelegate.getHttpClient();
388        }
389
390        @Override
391        public String getServerBase() {
392                return myDelegate.getServerBase();
393        }
394
395        @Override
396        public void setPrettyPrint(Boolean thePrettyPrint) {
397                myDelegate.setPrettyPrint(thePrettyPrint);
398        }
399
400        @Override
401        public void setSummary(SummaryEnum theSummary) {
402                myDelegate.setSummary(theSummary);
403        }
404
405        @Override
406        public void setFormatParamStyle(RequestFormatParamStyleEnum theRequestFormatParamStyle) {
407                myDelegate.setFormatParamStyle(theRequestFormatParamStyle);
408        }
409}