001/*-
002 * #%L
003 * HAPI FHIR Storage api
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.api.pid;
021
022import jakarta.annotation.Nonnull;
023import jakarta.annotation.Nullable;
024import org.springframework.transaction.support.TransactionOperations;
025
026import java.util.function.Function;
027import java.util.function.Supplier;
028import java.util.stream.Stream;
029
030/**
031 * A template for stream queries, like JDBCTemplate and friends.
032 *
033 * We need to wrap access to the stream with a tx-span, a try-with-resources block, and RequestDetails.
034 * @param <T> The stream content type
035 */
036public interface StreamTemplate<T> {
037        @Nullable
038        <R> R call(@Nonnull Function<Stream<T>, R> theCallback);
039
040        /**
041         * Wrap this template with a transaction boundary.
042         * Our dao Stream methods require an active Hibernate session for the duration of the Stream.
043         * This advice uses a tx boundary to ensure that active session.
044         *
045         * @param theTxBuilder the transaction and partition settings
046         * @return the wrapped template
047         */
048        default StreamTemplate<T> withTransactionAdvice(TransactionOperations theTxBuilder) {
049                return new TransactionWrappingStreamTemplate<>(theTxBuilder, this);
050        }
051
052        /**
053         * Wrap the supplied stream as a StreamTemplate in a try-with-resources block to ensure it is closed.
054         * @param theStreamQuery the query to run
055         * @return a template that will always close the Stream on exit.
056         */
057        static <ST> StreamTemplate<ST> fromSupplier(Supplier<Stream<ST>> theStreamQuery) {
058                return new AutoClosingStreamTemplate<>(theStreamQuery);
059        }
060}