package it.cavallium.dbengine.database; import it.cavallium.dbengine.client.query.current.data.TotalHitsCount; import it.cavallium.dbengine.lucene.LuceneCloseable; import it.cavallium.dbengine.utils.SimpleResource; import java.util.List; import java.util.Objects; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class LLSearchResultShard extends SimpleResource implements DiscardingCloseable { private static final Logger LOG = LogManager.getLogger(LLSearchResultShard.class); private final Stream results; private final TotalHitsCount totalHitsCount; public LLSearchResultShard(Stream results, TotalHitsCount totalHitsCount) { this.results = results; this.totalHitsCount = totalHitsCount; } public static LLSearchResultShard withResource(Stream results, TotalHitsCount totalHitsCount, SafeCloseable closeableResource) { if (closeableResource instanceof LuceneCloseable luceneCloseable) { return new LuceneLLSearchResultShard(results, totalHitsCount, List.of(luceneCloseable)); } else { return new ResourcesLLSearchResultShard(results, totalHitsCount, List.of(closeableResource)); } } public Stream results() { ensureOpen(); return results; } public TotalHitsCount totalHitsCount() { ensureOpen(); return totalHitsCount; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; var that = (LLSearchResultShard) obj; return Objects.equals(this.results, that.results) && Objects.equals(this.totalHitsCount, that.totalHitsCount); } @Override public int hashCode() { return Objects.hash(results, totalHitsCount); } @Override public String toString() { return "LLSearchResultShard[" + "results=" + results + ", " + "totalHitsCount=" + totalHitsCount + ']'; } @Override public void onClose() { } public static class ResourcesLLSearchResultShard extends LLSearchResultShard { private final List resources; public ResourcesLLSearchResultShard(Stream resultsFlux, TotalHitsCount count, List resources) { super(resultsFlux, count); this.resources = resources; } @Override public void onClose() { try { for (SafeCloseable resource : resources) { try { resource.close(); } catch (Throwable ex) { LOG.error("Failed to close resource", ex); } } } catch (Throwable ex) { LOG.error("Failed to close resources", ex); } super.onClose(); } } public static class LuceneLLSearchResultShard extends LLSearchResultShard implements LuceneCloseable { private final List resources; public LuceneLLSearchResultShard(Stream resultsFlux, TotalHitsCount count, List resources) { super(resultsFlux, count); this.resources = resources; } @Override public void onClose() { try { for (LuceneCloseable resource : resources) { try { resource.close(); } catch (Throwable ex) { LOG.error("Failed to close resource", ex); } } } catch (Throwable ex) { LOG.error("Failed to close resources", ex); } super.onClose(); } } }