/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.druid.query;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Function;
import org.apache.druid.guice.annotations.ExtensionPoint;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.query.aggregation.AggregatorFactory;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 *
 */
@ExtensionPoint
public interface CacheStrategy<T, CacheType, QueryType extends Query<T>>
{
  /**
   * Returns the given query is cacheable or not.
   * The {@code willMergeRunners} parameter can be used for distinguishing the caller is a broker or a data node.
   *
   * @param query            the query to be cached
   * @param willMergeRunners indicates that {@link QueryRunnerFactory#mergeRunners(ExecutorService, Iterable)} will be
   *                         called on the cached by-segment results
   *
   * @return true if the query is cacheable, otherwise false.
   */
  boolean isCacheable(QueryType query, boolean willMergeRunners);

  /**
   * Computes the cache key for the given query
   *
   * @param query the query to compute a cache key for
   *
   * @return the cache key
   */
  byte[] computeCacheKey(QueryType query);

  /**
   * Computes the result level cache key for the given query.
   * Some implementations may include query parameters that might not be used in {@code computeCacheKey} for same query
   *
   * @param query the query to be cached
   *
   * @return the result level cache key
   */
  byte[] computeResultLevelCacheKey(QueryType query);

  /**
   * Returns the class type of what is used in the cache
   *
   * @return Returns the class type of what is used in the cache
   */
  TypeReference<CacheType> getCacheObjectClazz();

  /**
   * Returns a function that converts from the QueryType's result type to something cacheable.
   * <p>
   * The resulting function must be thread-safe.
   *
   * @param isResultLevelCache indicates whether the function is invoked for result-level caching or segment-level caching
   *
   * @return a thread-safe function that converts the QueryType's result type into something cacheable
   */
  Function<T, CacheType> prepareForCache(boolean isResultLevelCache);

  /**
   * A function that does the inverse of the operation that the function prepareForCache returns
   *
   * @param isResultLevelCache indicates whether the function is invoked for result-level caching or segment-level caching
   *
   * @return A function that does the inverse of the operation that the function prepareForCache returns
   */
  Function<CacheType, T> pullFromCache(boolean isResultLevelCache);


  default Function<T, CacheType> prepareForSegmentLevelCache()
  {
    return prepareForCache(false);
  }

  default Function<CacheType, T> pullFromSegmentLevelCache()
  {
    return pullFromCache(false);
  }

  /**
   * Helper function used by TopN, GroupBy, Timeseries queries in {@link #pullFromCache(boolean)}.
   * When using the result level cache, the agg values seen here are
   * finalized values generated by AggregatorFactory.finalizeComputation().
   * These finalized values are deserialized from the cache as generic Objects, which will
   * later be reserialized and returned to the user without further modification.
   * Because the agg values are deserialized as generic Objects, the values are subject to the same
   * type consistency issues handled by DimensionHandlerUtils.convertObjectToType() in the pullFromCache implementations
   * for dimension values (e.g., a Float would become Double).
   */
  static void fetchAggregatorsFromCache(
      List<AggregatorFactory> aggregators,
      Iterator<Object> resultIter,
      boolean isResultLevelCache,
      AddToResultFunction addToResultFunction
  )
  {
    for (int i = 0; i < aggregators.size(); i++) {
      final AggregatorFactory aggregator = aggregators.get(i);
      if (!resultIter.hasNext()) {
        throw new ISE("Ran out of objects while reading aggregators from cache!");
      }

      if (isResultLevelCache) {
        addToResultFunction.apply(aggregator.getName(), i, resultIter.next());
      } else {
        addToResultFunction.apply(aggregator.getName(), i, aggregator.deserialize(resultIter.next()));
      }
    }
  }

  interface AddToResultFunction
  {
    void apply(String aggregatorName, int aggregatorIndex, Object object);
  }
}

@@ -1197,16 +1197,165 @@
 %0A%0A/**%0A *
+ Handles caching-related tasks for a particular query type.%0A *%0A * Generally returned by the toolchest method %7B@link QueryToolChest#getCacheStrategy%7D.
 %0A */%0A@Ex
@@ -1457,24 +1457,32 @@
   * Returns 
+whether 
 the given qu
@@ -2025,24 +2025,36 @@
 omputes the 
+per-segment 
 cache key fo
@@ -2074,68 +2074,270 @@
 uery
-%0A   *%0A   * @param query the query to compute a cache key for
+. Because this is a per-segment cache key, it should only%0A   * include parts of the query that affect the results for a specific segment (i.e., the results returned from%0A   * %7B@link QueryRunnerFactory#createRunner%7D).%0A   *%0A   * @param query the query to be cached
 %0A   
@@ -2351,24 +2351,36 @@
 @return the 
+per-segment 
 cache key%0A  
@@ -2449,33 +2449,33 @@
 putes the result
- 
+-
 level cache key 
@@ -2494,16 +2494,242 @@
 n query.
+ The result-level cache will tack on datasource and%0A   * interval details, so this key does not need to include datasource and interval. But it should include anything%0A   * else that might affect the results of the query.%0A   *
 %0A   * So
@@ -2747,19 +2747,28 @@
 tations 
-may
+will need to
  include
@@ -2794,21 +2794,16 @@
 hat 
-might
+are
  not 
-be 
 used
@@ -2808,21 +2808,22 @@
 ed in %7B@
-code 
+link #
 computeC
@@ -2834,16 +2834,25 @@
 Key%7D for
+ the%0A   *
  same qu
@@ -2854,16 +2854,17 @@
 me query
+.
 %0A   *%0A  
@@ -2922,33 +2922,33 @@
 eturn the result
- 
+-
 level cache key%0A

Improve Javadocs. (#9280)