001/*-
002 * #%L
003 * HAPI FHIR JPA Server
004 * %%
005 * Copyright (C) 2014 - 2024 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.jpa.search;
021
022import ca.uhn.fhir.context.FhirContext;
023import ca.uhn.fhir.context.RuntimeResourceDefinition;
024import ca.uhn.fhir.jpa.dao.data.IResourceSearchUrlDao;
025import ca.uhn.fhir.jpa.model.config.PartitionSettings;
026import ca.uhn.fhir.jpa.model.dao.JpaPid;
027import ca.uhn.fhir.jpa.model.entity.ResourceSearchUrlEntity;
028import ca.uhn.fhir.jpa.model.entity.ResourceTable;
029import ca.uhn.fhir.jpa.searchparam.MatchUrlService;
030import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
031import jakarta.persistence.EntityManager;
032import org.slf4j.Logger;
033import org.slf4j.LoggerFactory;
034import org.springframework.stereotype.Service;
035import org.springframework.transaction.annotation.Transactional;
036
037import java.util.Date;
038import java.util.List;
039
040/**
041 * This service ensures uniqueness of resources during create or create-on-update
042 * by storing the resource searchUrl.
043 *
044 * @see SearchUrlJobMaintenanceSvcImpl which deletes stale entities
045 */
046@Transactional
047@Service
048public class ResourceSearchUrlSvc {
049        private static final Logger ourLog = LoggerFactory.getLogger(ResourceSearchUrlSvc.class);
050        private final EntityManager myEntityManager;
051
052        private final IResourceSearchUrlDao myResourceSearchUrlDao;
053
054        private final MatchUrlService myMatchUrlService;
055
056        private final FhirContext myFhirContext;
057        private final PartitionSettings myPartitionSettings;
058
059        public ResourceSearchUrlSvc(
060                        EntityManager theEntityManager,
061                        IResourceSearchUrlDao theResourceSearchUrlDao,
062                        MatchUrlService theMatchUrlService,
063                        FhirContext theFhirContext,
064                        PartitionSettings thePartitionSettings) {
065                myEntityManager = theEntityManager;
066                myResourceSearchUrlDao = theResourceSearchUrlDao;
067                myMatchUrlService = theMatchUrlService;
068                myFhirContext = theFhirContext;
069                myPartitionSettings = thePartitionSettings;
070        }
071
072        /**
073         * Perform removal of entries older than {@code theCutoffDate} since the create operations are done.
074         */
075        public void deleteEntriesOlderThan(Date theCutoffDate) {
076                ourLog.debug("About to delete SearchUrl which are older than {}", theCutoffDate);
077                int deletedCount = myResourceSearchUrlDao.deleteAllWhereCreatedBefore(theCutoffDate);
078                ourLog.debug("Deleted {} SearchUrls", deletedCount);
079        }
080
081        /**
082         * Once a resource is updated or deleted, we can trust that future match checks will find the committed resource in the db.
083         * The use of the constraint table is done, and we can delete it to keep the table small.
084         */
085        public void deleteByResId(JpaPid theResId) {
086                myResourceSearchUrlDao.deleteByResId(theResId.getId());
087        }
088
089        public void deleteByResIds(List<Long> theResIds) {
090                myResourceSearchUrlDao.deleteByResIds(theResIds);
091        }
092
093        /**
094         *  We store a record of match urls with res_id so a db constraint can catch simultaneous creates that slip through.
095         */
096        public void enforceMatchUrlResourceUniqueness(
097                        String theResourceName, String theMatchUrl, ResourceTable theResourceTable) {
098                String canonicalizedUrlForStorage = createCanonicalizedUrlForStorage(theResourceName, theMatchUrl);
099
100                ResourceSearchUrlEntity searchUrlEntity = ResourceSearchUrlEntity.from(
101                                canonicalizedUrlForStorage,
102                                theResourceTable,
103                                myPartitionSettings.isConditionalCreateDuplicateIdentifiersEnabled());
104                // calling dao.save performs a merge operation which implies a trip to
105                // the database to see if the resource exists.  Since we don't need the check, we avoid the trip by calling
106                // em.persist.
107                myEntityManager.persist(searchUrlEntity);
108        }
109
110        /**
111         * Provides a sanitized matchUrl to circumvent ordering matters.
112         */
113        private String createCanonicalizedUrlForStorage(String theResourceName, String theMatchUrl) {
114
115                RuntimeResourceDefinition resourceDef = myFhirContext.getResourceDefinition(theResourceName);
116                SearchParameterMap matchUrlSearchParameterMap = myMatchUrlService.translateMatchUrl(theMatchUrl, resourceDef);
117
118                String canonicalizedMatchUrl = matchUrlSearchParameterMap.toNormalizedQueryString(myFhirContext);
119
120                return theResourceName + canonicalizedMatchUrl;
121        }
122}