{"action":"created","comment":{"url":"https://api.github.com/repos/apache/incubator-druid/pulls/comments/237722857","pull_request_review_id":180042187,"id":237722857,"node_id":"MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDIzNzcyMjg1Nw==","diff_hunk":"@@ -16,55 +16,1991 @@\n  * specific language governing permissions and limitations\n  * under the License.\n  */\n+\n package org.apache.druid.indexing.seekablestream;\n \n \n+import com.fasterxml.jackson.annotation.JsonCreator;\n+import com.fasterxml.jackson.annotation.JsonProperty;\n+import com.fasterxml.jackson.core.JsonProcessingException;\n+import com.fasterxml.jackson.core.type.TypeReference;\n+import com.fasterxml.jackson.databind.ObjectMapper;\n import com.google.common.annotations.VisibleForTesting;\n+import com.google.common.base.Function;\n+import com.google.common.base.Joiner;\n+import com.google.common.base.Optional;\n+import com.google.common.base.Preconditions;\n+import com.google.common.base.Supplier;\n+import com.google.common.base.Throwables;\n+import com.google.common.collect.ImmutableMap;\n+import com.google.common.collect.Sets;\n+import com.google.common.util.concurrent.FutureCallback;\n+import com.google.common.util.concurrent.Futures;\n+import com.google.common.util.concurrent.ListenableFuture;\n+import com.google.common.util.concurrent.SettableFuture;\n+import org.apache.druid.data.input.Committer;\n+import org.apache.druid.data.input.InputRow;\n+import org.apache.druid.data.input.impl.InputRowParser;\n+import org.apache.druid.discovery.DiscoveryDruidNode;\n+import org.apache.druid.discovery.LookupNodeService;\n+import org.apache.druid.discovery.NodeType;\n+import org.apache.druid.indexer.IngestionState;\n import org.apache.druid.indexer.TaskStatus;\n+import org.apache.druid.indexing.common.IngestionStatsAndErrorsTaskReport;\n+import org.apache.druid.indexing.common.IngestionStatsAndErrorsTaskReportData;\n+import org.apache.druid.indexing.common.TaskRealtimeMetricsMonitorBuilder;\n+import org.apache.druid.indexing.common.TaskReport;\n import org.apache.druid.indexing.common.TaskToolbox;\n+import org.apache.druid.indexing.common.actions.CheckPointDataSourceMetadataAction;\n+import org.apache.druid.indexing.common.actions.ResetDataSourceMetadataAction;\n+import org.apache.druid.indexing.common.actions.SegmentTransactionalInsertAction;\n import org.apache.druid.indexing.common.stats.RowIngestionMeters;\n+import org.apache.druid.indexing.common.stats.RowIngestionMetersFactory;\n+import org.apache.druid.indexing.common.task.IndexTaskUtils;\n+import org.apache.druid.indexing.common.task.RealtimeIndexTask;\n+import org.apache.druid.indexing.seekablestream.common.OrderedPartitionableRecord;\n+import org.apache.druid.indexing.seekablestream.common.OrderedSequenceNumber;\n+import org.apache.druid.indexing.seekablestream.common.RecordSupplier;\n+import org.apache.druid.indexing.seekablestream.common.StreamPartition;\n+import org.apache.druid.java.util.common.DateTimes;\n+import org.apache.druid.java.util.common.ISE;\n+import org.apache.druid.java.util.common.StringUtils;\n+import org.apache.druid.java.util.common.collect.Utils;\n+import org.apache.druid.java.util.common.parsers.ParseException;\n+import org.apache.druid.java.util.emitter.EmittingLogger;\n+import org.apache.druid.segment.indexing.RealtimeIOConfig;\n+import org.apache.druid.segment.realtime.FireDepartment;\n+import org.apache.druid.segment.realtime.FireDepartmentMetrics;\n import org.apache.druid.segment.realtime.appenderator.Appenderator;\n+import org.apache.druid.segment.realtime.appenderator.AppenderatorDriverAddResult;\n+import org.apache.druid.segment.realtime.appenderator.SegmentsAndMetadata;\n+import org.apache.druid.segment.realtime.appenderator.StreamAppenderatorDriver;\n+import org.apache.druid.segment.realtime.appenderator.TransactionalSegmentPublisher;\n import org.apache.druid.segment.realtime.firehose.ChatHandler;\n+import org.apache.druid.segment.realtime.firehose.ChatHandlerProvider;\n+import org.apache.druid.server.security.Access;\n+import org.apache.druid.server.security.Action;\n+import org.apache.druid.server.security.AuthorizerMapper;\n+import org.apache.druid.timeline.DataSegment;\n+import org.apache.druid.utils.CircularBuffer;\n+import org.joda.time.DateTime;\n \n+import javax.annotation.Nullable;\n+import javax.annotation.ParametersAreNonnullByDefault;\n+import javax.servlet.http.HttpServletRequest;\n+import javax.validation.constraints.NotNull;\n+import javax.ws.rs.Consumes;\n+import javax.ws.rs.DefaultValue;\n+import javax.ws.rs.GET;\n+import javax.ws.rs.POST;\n+import javax.ws.rs.Path;\n+import javax.ws.rs.Produces;\n+import javax.ws.rs.QueryParam;\n+import javax.ws.rs.core.Context;\n+import javax.ws.rs.core.MediaType;\n import javax.ws.rs.core.Response;\n+import java.io.File;\n+import java.io.IOException;\n+import java.nio.ByteBuffer;\n+import java.util.ArrayList;\n+import java.util.Collections;\n+import java.util.HashMap;\n+import java.util.HashSet;\n+import java.util.Iterator;\n+import java.util.List;\n import java.util.Map;\n+import java.util.Set;\n+import java.util.TreeMap;\n+import java.util.concurrent.ConcurrentHashMap;\n+import java.util.concurrent.CopyOnWriteArrayList;\n+import java.util.concurrent.ExecutionException;\n+import java.util.concurrent.Future;\n+import java.util.concurrent.RejectedExecutionException;\n+import java.util.concurrent.TimeUnit;\n+import java.util.concurrent.TimeoutException;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+import java.util.concurrent.locks.Condition;\n+import java.util.concurrent.locks.Lock;\n+import java.util.concurrent.locks.ReentrantLock;\n+import java.util.stream.Collectors;\n \n /**\n  * Interface for abstracting the indexing task run logic. Only used by Kafka indexing tasks,\n  * but will also be used by Kinesis indexing tasks once implemented\n  *\n  * @param <PartitionType> Partition Number Type\n- * @param <SequenceType> Sequence Number Type\n+ * @param <SequenceType>  Sequence Number Type\n  */\n-public interface SeekableStreamIndexTaskRunner<PartitionType, SequenceType> extends ChatHandler\n+public abstract class SeekableStreamIndexTaskRunner<PartitionType, SequenceType> implements ChatHandler\n {\n-  Appenderator getAppenderator();\n+  public enum Status\n+  {\n+    NOT_STARTED,\n+    STARTING,\n+    READING,\n+    PAUSED,\n+    PUBLISHING\n+  }\n \n-  TaskStatus run(TaskToolbox toolbox);\n+  private final EmittingLogger log = new EmittingLogger(this.getClass());\n+  private static final String METADATA_NEXT_PARTITIONS = \"nextPartitions\";\n+  private static final String METADATA_PUBLISH_PARTITIONS = \"publishPartitions\";\n \n-  void stopGracefully();\n+  private final Map<PartitionType, SequenceType> endOffsets;\n+  private final Map<PartitionType, SequenceType> currOffsets = new ConcurrentHashMap<>();\n+  private final Map<PartitionType, SequenceType> lastPersistedOffsets = new ConcurrentHashMap<>();\n \n-  @VisibleForTesting\n-  RowIngestionMeters getRowIngestionMeters();\n+  // The pause lock and associated conditions are to support coordination between the Jetty threads and the main\n+  // ingestion loop. The goal is to provide callers of the API a guarantee that if pause() returns successfully\n+  // the ingestion loop has been stopped at the returned sequences and will not ingest any more data until resumed. The\n+  // fields are used as follows (every step requires acquiring [pauseLock]):\n+  //   Pausing:\n+  //   - In pause(), [pauseRequested] is set to true and then execution waits for [status] to change to PAUSED, with the\n+  //     condition checked when [hasPaused] is signalled.\n+  //   - In possiblyPause() called from the main loop, if [pauseRequested] is true, [status] is set to PAUSED,\n+  //     [hasPaused] is signalled, and execution pauses until [pauseRequested] becomes false, either by being set or by\n+  //     the [pauseMillis] timeout elapsing. [pauseRequested] is checked when [shouldResume] is signalled.\n+  //   Resuming:\n+  //   - In resume(), [pauseRequested] is set to false, [shouldResume] is signalled, and execution waits for [status] to\n+  //     change to something other than PAUSED, with the condition checked when [shouldResume] is signalled.\n+  //   - In possiblyPause(), when [shouldResume] is signalled, if [pauseRequested] has become false the pause loop ends,\n+  //     [status] is changed to STARTING and [shouldResume] is signalled.\n+  private final Lock pauseLock = new ReentrantLock();\n+  private final Condition hasPaused = pauseLock.newCondition();\n+  private final Condition shouldResume = pauseLock.newCondition();\n \n-  @VisibleForTesting\n-  SeekableStreamIndexTask.Status getStatus();\n+  protected final AtomicBoolean stopRequested = new AtomicBoolean(false);\n+  private final AtomicBoolean publishOnStop = new AtomicBoolean(false);\n+\n+  // [statusLock] is used to synchronize the Jetty thread calling stopGracefully() with the main run thread. It prevents\n+  // the main run thread from switching into a publishing state while the stopGracefully() thread thinks it's still in\n+  // a pre-publishing state. This is important because stopGracefully() will try to use the [stopRequested] flag to stop\n+  // the main thread where possible, but this flag is not honored once publishing has begun so in this case we must\n+  // interrupt the thread. The lock ensures that if the run thread is about to transition into publishing state, it\n+  // blocks until after stopGracefully() has set [stopRequested] and then does a final check on [stopRequested] before\n+  // transitioning to publishing state.\n+  private final Object statusLock = new Object();\n+\n+  protected final Lock pollRetryLock = new ReentrantLock();\n+  protected final Condition isAwaitingRetry = pollRetryLock.newCondition();\n+\n+  private final SeekableStreamIndexTask<PartitionType, SequenceType> task;\n+  private final SeekableStreamIOConfig<PartitionType, SequenceType> ioConfig;\n+  private final SeekableStreamTuningConfig tuningConfig;\n+  private final InputRowParser<ByteBuffer> parser;\n+  private final AuthorizerMapper authorizerMapper;\n+  private final Optional<ChatHandlerProvider> chatHandlerProvider;\n+  private final CircularBuffer<Throwable> savedParseExceptions;\n+  private final String stream;\n+  private final RowIngestionMeters rowIngestionMeters;\n+\n+  private final Set<String> publishingSequences = Sets.newConcurrentHashSet();\n+  private final List<ListenableFuture<SegmentsAndMetadata>> publishWaitList = new ArrayList<>();\n+  private final List<ListenableFuture<SegmentsAndMetadata>> handOffWaitList = new ArrayList<>();\n+  private final Map<PartitionType, SequenceType> initialOffsetsSnapshot = new HashMap<>();\n+  private final Set<PartitionType> exclusiveStartingPartitions = new HashSet<>();\n+\n+  // true for kafka, falsse for kinesis\n+  private final boolean isSkipSegmentLineageCheck;\n+\n+  private volatile DateTime startTime;\n+  private volatile Status status = Status.NOT_STARTED; // this is only ever set by the task runner thread (runThread)\n+  private volatile TaskToolbox toolbox;\n+  private volatile Thread runThread;\n+  private volatile Appenderator appenderator;\n+  private volatile StreamAppenderatorDriver driver;\n+  private volatile IngestionState ingestionState;\n+\n+  protected volatile boolean pauseRequested = false;\n+  private volatile long nextCheckpointTime;\n+\n+  private volatile CopyOnWriteArrayList<SequenceMetadata> sequences;\n+  private volatile Throwable backgroundThreadException;\n+\n+  public SeekableStreamIndexTaskRunner(\n+      final SeekableStreamIndexTask<PartitionType, SequenceType> task,\n+      final InputRowParser<ByteBuffer> parser,\n+      final AuthorizerMapper authorizerMapper,\n+      final Optional<ChatHandlerProvider> chatHandlerProvider,\n+      final CircularBuffer<Throwable> savedParseExceptions,\n+      final RowIngestionMetersFactory rowIngestionMetersFactory,\n+      final boolean isSkipSegmentLineageCheck\n+  )\n+  {\n+    this.task = task;\n+    this.ioConfig = task.getIOConfig();\n+    this.tuningConfig = task.getTuningConfig();\n+    this.parser = parser;\n+    this.authorizerMapper = authorizerMapper;\n+    this.chatHandlerProvider = chatHandlerProvider;\n+    this.savedParseExceptions = savedParseExceptions;\n+    this.stream = ioConfig.getStartPartitions().getStream();\n+    this.rowIngestionMeters = rowIngestionMetersFactory.createRowIngestionMeters();\n+    this.isSkipSegmentLineageCheck = isSkipSegmentLineageCheck;\n+\n+    this.endOffsets = new ConcurrentHashMap<>(ioConfig.getEndPartitions().getPartitionSequenceNumberMap());\n+    this.sequences = new CopyOnWriteArrayList<>();\n+    this.ingestionState = IngestionState.NOT_STARTED;\n+\n+    resetNextCheckpointTime();\n+  }\n+\n+\n+  public TaskStatus run(TaskToolbox toolbox)\n+  {\n+    try {\n+      return runInternal(toolbox);\n+    }\n+    catch (Exception e) {\n+      log.error(e, \"Encountered exception while running task.\");\n+      final String errorMsg = Throwables.getStackTraceAsString(e);\n+      toolbox.getTaskReportFileWriter().write(getTaskCompletionReports(errorMsg));\n+      return TaskStatus.failure(\n+          task.getId(),\n+          errorMsg\n+      );\n+    }\n+  }\n+\n+  private TaskStatus runInternal(TaskToolbox toolbox) throws Exception\n+  {\n+    log.info(\"SeekableStream indexing task starting up!\");\n+    startTime = DateTimes.nowUtc();\n+    status = Status.STARTING;\n+    this.toolbox = toolbox;\n+\n+\n+    if (!restoreSequences()) {\n+      final TreeMap<Integer, Map<PartitionType, SequenceType>> checkpoints = getCheckPointsFromContext(toolbox, task);\n+      if (checkpoints != null) {\n+        boolean exclusive = false;\n+        Iterator<Map.Entry<Integer, Map<PartitionType, SequenceType>>> sequenceOffsets = checkpoints.entrySet()\n+                                                                                                    .iterator();\n+        Map.Entry<Integer, Map<PartitionType, SequenceType>> previous = sequenceOffsets.next();\n+        while (sequenceOffsets.hasNext()) {\n+          Map.Entry<Integer, Map<PartitionType, SequenceType>> current = sequenceOffsets.next();\n+          sequences.add(createSequenceMetaData(\n+              previous.getKey(),\n+              StringUtils.format(\"%s_%s\", ioConfig.getBaseSequenceName(), previous.getKey()),\n+              previous.getValue(),\n+              current.getValue(),\n+              true,\n+              exclusive ? previous.getValue().keySet() : null\n+          ));\n+          previous = current;\n+          exclusive = true;\n+        }\n+        sequences.add(createSequenceMetaData(\n+            previous.getKey(),\n+            StringUtils.format(\"%s_%s\", ioConfig.getBaseSequenceName(), previous.getKey()),\n+            previous.getValue(),\n+            endOffsets,\n+            false,\n+            exclusive ? previous.getValue().keySet() : null\n+        ));\n+      } else {\n+        sequences.add(createSequenceMetaData(\n+            0,\n+            StringUtils.format(\"%s_%s\", ioConfig.getBaseSequenceName(), 0),\n+            ioConfig.getStartPartitions().getPartitionSequenceNumberMap(),\n+            endOffsets,\n+            false,\n+            null\n+        ));\n+      }\n+    }\n+\n+    log.info(\"Starting with sequences:  %s\", sequences);\n+\n+    if (chatHandlerProvider.isPresent()) {\n+      log.info(\"Found chat handler of class[%s]\", chatHandlerProvider.get().getClass().getName());\n+      chatHandlerProvider.get().register(task.getId(), this, false);\n+    } else {\n+      log.warn(\"No chat handler detected\");\n+    }\n+\n+    runThread = Thread.currentThread();\n+\n+    // Set up FireDepartmentMetrics\n+    final FireDepartment fireDepartmentForMetrics = new FireDepartment(\n+        task.getDataSchema(),\n+        new RealtimeIOConfig(null, null, null),\n+        null\n+    );\n+    FireDepartmentMetrics fireDepartmentMetrics = fireDepartmentForMetrics.getMetrics();\n+    toolbox.getMonitorScheduler()\n+           .addMonitor(TaskRealtimeMetricsMonitorBuilder.build(task, fireDepartmentForMetrics, rowIngestionMeters));\n+\n+    final String lookupTier = task.getContextValue(RealtimeIndexTask.CTX_KEY_LOOKUP_TIER);\n+    final LookupNodeService lookupNodeService = lookupTier == null ?\n+                                                toolbox.getLookupNodeService() :\n+                                                new LookupNodeService(lookupTier);\n+\n+    final DiscoveryDruidNode discoveryDruidNode = new DiscoveryDruidNode(\n+        toolbox.getDruidNode(),\n+        NodeType.PEON,\n+        ImmutableMap.of(\n+            toolbox.getDataNodeService().getName(), toolbox.getDataNodeService(),\n+            lookupNodeService.getName(), lookupNodeService\n+        )\n+    );\n+\n+    Throwable caughtExceptionOuter = null;\n+    try (final RecordSupplier<PartitionType, SequenceType> recordSupplier = task.newRecordSupplier()) {\n+      toolbox.getDataSegmentServerAnnouncer().announce();\n+      toolbox.getDruidNodeAnnouncer().announce(discoveryDruidNode);\n+\n+      appenderator = task.newAppenderator(fireDepartmentMetrics, toolbox);\n+      driver = task.newDriver(appenderator, toolbox, fireDepartmentMetrics);\n+\n+      final String stream = ioConfig.getStartPartitions().getStream();\n+\n+      // Start up, set up initial sequences.\n+      final Object restoredMetadata = driver.startJob();\n+      if (restoredMetadata == null) {\n+        // no persist has happened so far\n+        // so either this is a brand new task or replacement of a failed task\n+        Preconditions.checkState(sequences.get(0).startOffsets.entrySet().stream().allMatch(\n+            partitionOffsetEntry ->\n+                createSequenceNumber(partitionOffsetEntry.getValue()).compareTo(\n+                    createSequenceNumber(ioConfig.getStartPartitions()\n+                                                 .getPartitionSequenceNumberMap()\n+                                                 .get(partitionOffsetEntry.getKey())\n+                    )) >= 0\n+        ), \"Sequence sequences are not compatible with start sequences of task\");\n+        currOffsets.putAll(sequences.get(0).startOffsets);\n+      } else {\n+        @SuppressWarnings(\"unchecked\")\n+        final Map<String, Object> restoredMetadataMap = (Map) restoredMetadata;\n+        final SeekableStreamPartitions<PartitionType, SequenceType> restoredNextPartitions = createSeekableStreamPartitions(\n+            toolbox.getObjectMapper(),\n+            restoredMetadataMap.get(METADATA_NEXT_PARTITIONS)\n+        );\n+\n+        currOffsets.putAll(restoredNextPartitions.getPartitionSequenceNumberMap());\n+\n+        // Sanity checks.\n+        if (!restoredNextPartitions.getStream().equals(ioConfig.getStartPartitions().getStream())) {\n+          throw new ISE(\n+              \"WTF?! Restored stream[%s] but expected stream[%s]\",\n+              restoredNextPartitions.getStream(),\n+              ioConfig.getStartPartitions().getStream()\n+          );\n+        }\n+\n+        if (!currOffsets.keySet().equals(ioConfig.getStartPartitions().getPartitionSequenceNumberMap().keySet())) {\n+          throw new ISE(\n+              \"WTF?! Restored partitions[%s] but expected partitions[%s]\",\n+              currOffsets.keySet(),\n+              ioConfig.getStartPartitions().getPartitionSequenceNumberMap().keySet()\n+          );\n+        }\n+        // sequences size can be 0 only when all sequences got published and task stopped before it could finish\n+        // which is super rare\n+        if (sequences.size() == 0 || sequences.get(sequences.size() - 1).isCheckpointed()) {\n+          this.endOffsets.putAll(sequences.size() == 0\n+                                 ? currOffsets\n+                                 : sequences.get(sequences.size() - 1).getEndOffsets());\n+          log.info(\"End sequences changed to [%s]\", endOffsets);\n+        }\n+      }\n+\n+      // Filter out partitions with END_OF_SHARD markers since these partitions have already been fully read. This\n+      // should have been done by the supervisor already so this is defensive.\n+      int numPreFilterPartitions = currOffsets.size();\n+      if (currOffsets.entrySet().removeIf(x -> OrderedPartitionableRecord.END_OF_SHARD_MARKER.equals(x.getValue()))) {\n+        log.info(\n+            \"Removed [%d] partitions from assignment which have already been closed\",\n+            numPreFilterPartitions - currOffsets.size()\n+        );\n+      }\n+\n+      // Set up committer.\n+      final Supplier<Committer> committerSupplier = () -> {\n+        final Map<PartitionType, SequenceType> snapshot = ImmutableMap.copyOf(currOffsets);\n+        lastPersistedOffsets.clear();\n+        lastPersistedOffsets.putAll(snapshot);\n+\n+        return new Committer()\n+        {\n+          @Override\n+          public Object getMetadata()\n+          {\n+            return ImmutableMap.of(\n+                METADATA_NEXT_PARTITIONS, new SeekableStreamPartitions<>(\n+                    ioConfig.getStartPartitions().getStream(),\n+                    snapshot\n+                )\n+            );\n+          }\n+\n+          @Override\n+          public void run()\n+          {\n+            // Do nothing.\n+          }\n+        };\n+      };\n+\n+      // restart publishing of sequences (if any)\n+      maybePersistAndPublishSequences(committerSupplier);\n+\n+      Set<StreamPartition<PartitionType>> assignment = assignPartitions(recordSupplier);\n+      possiblyResetDataSourceMetadata(recordSupplier, assignment);\n+      seekToStartingSequence(recordSupplier, assignment);\n+\n+      ingestionState = IngestionState.BUILD_SEGMENTS;\n+\n+      // Main loop.\n+      // Could eventually support leader/follower mode (for keeping replicas more in sync)\n+      boolean stillReading = !assignment.isEmpty();\n+      status = Status.READING;\n+      Throwable caughtExceptionInner = null;\n+\n+      initialOffsetsSnapshot.putAll(currOffsets);\n+      exclusiveStartingPartitions.addAll(ioConfig.getExclusiveStartSequenceNumberPartitions());\n+\n+      try {\n+        while (stillReading) {\n+          if (possiblyPause()) {\n+            // The partition assignments may have changed while paused by a call to setEndOffsets() so reassign\n+            // partitions upon resuming. This is safe even if the end sequences have not been modified.\n+            assignment = assignPartitions(recordSupplier);\n+            possiblyResetDataSourceMetadata(recordSupplier, assignment);\n+            seekToStartingSequence(recordSupplier, assignment);\n+\n+            if (assignment.isEmpty()) {\n+              log.info(\"All partitions have been fully read\");\n+              publishOnStop.set(true);\n+              stopRequested.set(true);\n+            }\n+          }\n+\n+          // if stop is requested or task's end sequence is set by call to setEndOffsets method with finish set to true\n+          if (stopRequested.get() || sequences.get(sequences.size() - 1).isCheckpointed()) {\n+            status = Status.PUBLISHING;\n+          }\n+\n+          if (stopRequested.get()) {\n+            break;\n+          }\n+\n+          if (backgroundThreadException != null) {\n+            throw new RuntimeException(backgroundThreadException);\n+          }\n+\n+          checkPublishAndHandoffFailure();\n+\n+          maybePersistAndPublishSequences(committerSupplier);\n+\n+\n+          // calling getReocrd() ensures that excpetions specific to kafka/kinesis like OffsetOutOfRangeException\n+          // are handled in the subclasses\n+          List<OrderedPartitionableRecord<PartitionType, SequenceType>> records = getRecords(recordSupplier, toolbox);\n+\n+          stillReading = !assignment.isEmpty();\n+\n+          SequenceMetadata sequenceToCheckpoint = null;\n+          for (OrderedPartitionableRecord<PartitionType, SequenceType> record : records) {\n+\n+            // for Kafka, the end offsets are exclusive, so skip it\n+            if (getRunnerType() == Type.KAFKA && createSequenceNumber(record.getSequenceNumber()).equals(\n+                createSequenceNumber(endOffsets.get(record.getPartitionId())))) {\n+              continue;\n+            }\n+\n+            // for the first message we receive, check that we were given a message with a sequenceNumber that matches our\n+            // expected starting sequenceNumber\n+            if (!verifyInitialRecordAndSkipExclusiveParition(record, initialOffsetsSnapshot)) {\n+              continue;\n+            }\n+\n+            if (log.isTraceEnabled()) {\n+              log.trace(\n+                  \"Got stream[%s] partition[%s] sequence[%s].\",\n+                  record.getStream(),\n+                  record.getPartitionId(),\n+                  record.getSequenceNumber()\n+              );\n+            }\n+\n+            if (OrderedPartitionableRecord.END_OF_SHARD_MARKER.equals(record.getSequenceNumber())) {\n+              // shard is closed\n+              currOffsets.put(record.getPartitionId(), record.getSequenceNumber());\n+            } else if (createSequenceNumber(record.getSequenceNumber()).compareTo(\n+                createSequenceNumber(endOffsets.get(record.getPartitionId()))) <= 0) {\n+\n+\n+              if (!record.getSequenceNumber().equals(currOffsets.get(record.getPartitionId()))) {\n+                if (!ioConfig.isSkipOffsetGaps()) {\n+                  throw new ISE(\n+                      \"WTF?! Got sequence[%s] after sequence[%s] in partition[%s].\",\n+                      record.getSequenceNumber(),\n+                      currOffsets.get(record.getPartitionId()),\n+                      record.getPartitionId()\n+                  );\n+                }\n+              }\n+\n+              try {\n+                final List<byte[]> valueBytess = record.getData();\n+                final List<InputRow> rows;\n+                if (valueBytess == null || valueBytess.isEmpty()) {\n+                  rows = Utils.nullableListOf((InputRow) null);\n+                } else {\n+                  rows = new ArrayList<>();\n+                  for (byte[] valueBytes : valueBytess) {\n+                    rows.addAll(parser.parseBatch(ByteBuffer.wrap(valueBytes)));\n+                  }\n+                }\n+                boolean isPersistRequired = false;\n+\n+                final SequenceMetadata sequenceToUse = sequences\n+                    .stream()\n+                    .filter(sequenceMetadata -> sequenceMetadata.canHandle(record))\n+                    .findFirst()\n+                    .orElse(null);\n+\n+                if (sequenceToUse == null) {\n+                  throw new ISE(\n+                      \"WTH?! cannot find any valid sequence for record with partition [%d] and sequence [%d]. Current sequences: %s\",\n+                      record.getPartitionId(),\n+                      record.getSequenceNumber(),\n+                      sequences\n+                  );\n+                }\n+\n+                for (InputRow row : rows) {\n+                  if (row != null && task.withinMinMaxRecordTime(row)) {\n+                    final AppenderatorDriverAddResult addResult = driver.add(\n+                        row,\n+                        sequenceToUse.getSequenceName(),\n+                        committerSupplier,\n+                        // true for kafka, false for kinesis\n+                        isSkipSegmentLineageCheck,\n+                        // do not allow incremental persists to happen until all the rows from this batch\n+                        // of rows are indexed\n+                        false\n+                    );\n+\n+                    if (addResult.isOk()) {\n+                      // If the number of rows in the segment exceeds the threshold after adding a row,\n+                      // move the segment out from the active segments of BaseAppenderatorDriver to make a new segment.\n+                      if (addResult.isPushRequired(tuningConfig) && !sequenceToUse.isCheckpointed()) {\n+                        sequenceToCheckpoint = sequenceToUse;\n+                      }\n+                      isPersistRequired |= addResult.isPersistRequired();\n+                    } else {\n+                      // Failure to allocate segment puts determinism at risk, bail out to be safe.\n+                      // May want configurable behavior here at some point.\n+                      // If we allow continuing, then consider blacklisting the interval for a while to avoid constant checks.\n+                      throw new ISE(\"Could not allocate segment for row with timestamp[%s]\", row.getTimestamp());\n+                    }\n+\n+                    if (addResult.getParseException() != null) {\n+                      handleParseException(addResult.getParseException(), record);\n+                    } else {\n+                      rowIngestionMeters.incrementProcessed();\n+                    }\n+                  } else {\n+                    rowIngestionMeters.incrementThrownAway();\n+                  }\n+                }\n+                if (isPersistRequired) {\n+                  Futures.addCallback(\n+                      driver.persistAsync(committerSupplier.get()),\n+                      new FutureCallback<Object>()\n+                      {\n+                        @Override\n+                        public void onSuccess(@Nullable Object result)\n+                        {\n+                          log.info(\"Persist completed with metadata [%s]\", result);\n+                        }\n+\n+                        @Override\n+                        public void onFailure(@ParametersAreNonnullByDefault Throwable t)\n+                        {\n+                          log.error(\"Persist failed, dying\");\n+                          backgroundThreadException = t;\n+                        }\n+                      }\n+                  );\n+                }\n+              }\n+              catch (ParseException e) {\n+                handleParseException(e, record);\n+              }\n+\n+              // in kafka, we can easily get the next offset by adding 1, but for kinesis, there's no way\n+              // to get the next sequence number without having to make an expensive api call. So the behavior\n+              // here for kafka is to +1 while for kinesis we simply save the current sequence numberkkkkk\n+              currOffsets.put(record.getPartitionId(), getNextSequenceNumber(record.getSequenceNumber()));\n+            }\n+\n+            if ((currOffsets.get(record.getPartitionId()).equals(endOffsets.get(record.getPartitionId()))\n+                 || currOffsets.get(record.getPartitionId()).equals(OrderedPartitionableRecord.END_OF_SHARD_MARKER))\n+                && assignment.remove(record.getStreamPartition())) {\n+              log.info(\"Finished reading stream[%s], partition[%s].\", record.getStream(), record.getPartitionId());\n+              recordSupplier.assign(assignment);\n+              stillReading = !assignment.isEmpty();\n+            }\n+          }\n+\n+          if (System.currentTimeMillis() > nextCheckpointTime) {\n+            sequenceToCheckpoint = sequences.get(sequences.size() - 1);\n+          }\n+\n+          if (sequenceToCheckpoint != null && stillReading) {\n+            Preconditions.checkArgument(\n+                sequences.get(sequences.size() - 1)\n+                         .getSequenceName()\n+                         .equals(sequenceToCheckpoint.getSequenceName()),\n+                \"Cannot checkpoint a sequence [%s] which is not the latest one, sequences %s\",\n+                sequenceToCheckpoint,\n+                sequences\n+            );\n+            requestPause();\n+            final CheckPointDataSourceMetadataAction checkpointAction = new CheckPointDataSourceMetadataAction(\n+                task.getDataSource(),\n+                ioConfig.getTaskGroupId(),\n+                task.getIOConfig().getBaseSequenceName(),\n+                createDataSourceMetadata(new SeekableStreamPartitions<>(\n+                    stream,\n+                    sequenceToCheckpoint.getStartOffsets()\n+                )),\n+                createDataSourceMetadata(new SeekableStreamPartitions<>(stream, currOffsets))\n+            );\n+            if (!toolbox.getTaskActionClient().submit(checkpointAction)) {\n+              throw new ISE(\"Checkpoint request with sequences [%s] failed, dying\", currOffsets);\n+            }\n+          }\n+        }\n+        ingestionState = IngestionState.COMPLETED;\n+      }\n+      catch (Exception e) {\n+        // (1) catch all exceptions while reading from kafka\n+        caughtExceptionInner = e;\n+        log.error(e, \"Encountered exception in run() before persisting.\");\n+        throw e;\n+      }\n+      finally {\n+        log.info(\"Persisting all pending data\");\n+        try {\n+          driver.persist(committerSupplier.get()); // persist pending data\n+        }\n+        catch (Exception e) {\n+          if (caughtExceptionInner != null) {\n+            caughtExceptionInner.addSuppressed(e);\n+          } else {\n+            throw e;\n+          }\n+        }\n+      }\n+\n+      synchronized (statusLock) {\n+        if (stopRequested.get() && !publishOnStop.get()) {\n+          throw new InterruptedException(\"Stopping without publishing\");\n+        }\n+\n+        status = Status.PUBLISHING;\n+      }\n+\n+      for (SequenceMetadata sequenceMetadata : sequences) {\n+        if (!publishingSequences.contains(sequenceMetadata.getSequenceName())) {\n+          // this is done to prevent checks in sequence specific commit supplier from failing\n+          sequenceMetadata.setEndOffsets(currOffsets);\n+          sequenceMetadata.updateAssignments(currOffsets);\n+          publishingSequences.add(sequenceMetadata.getSequenceName());\n+          // persist already done in finally, so directly add to publishQueue\n+          publishAndRegisterHandoff(sequenceMetadata);\n+        }\n+      }\n+\n+      if (backgroundThreadException != null) {\n+        throw new RuntimeException(backgroundThreadException);\n+      }\n+\n+      // Wait for publish futures to complete.\n+      Futures.allAsList(publishWaitList).get();\n+\n+      // Wait for handoff futures to complete.\n+      // Note that every publishing task (created by calling AppenderatorDriver.publish()) has a corresponding\n+      // handoffFuture. handoffFuture can throw an exception if 1) the corresponding publishFuture failed or 2) it\n+      // failed to persist sequences. It might also return null if handoff failed, but was recoverable.\n+      // See publishAndRegisterHandoff() for details.\n+      List<SegmentsAndMetadata> handedOffList = Collections.emptyList();\n+      if (tuningConfig.getHandoffConditionTimeout() == 0) {\n+        handedOffList = Futures.allAsList(handOffWaitList).get();\n+      } else {\n+        try {\n+          handedOffList = Futures.allAsList(handOffWaitList)\n+                                 .get(tuningConfig.getHandoffConditionTimeout(), TimeUnit.MILLISECONDS);\n+        }\n+        catch (TimeoutException e) {\n+          // Handoff timeout is not an indexing failure, but coordination failure. We simply ignore timeout exception\n+          // here.\n+          log.makeAlert(\"Timed out after [%d] millis waiting for handoffs\", tuningConfig.getHandoffConditionTimeout())\n+             .addData(\"TaskId\", task.getId())\n+             .emit();\n+        }\n+      }\n+\n+      for (SegmentsAndMetadata handedOff : handedOffList) {\n+        log.info(\n+            \"Handoff completed for segments[%s] with metadata[%s].\",\n+            Joiner.on(\", \").join(\n+                handedOff.getSegments().stream().map(DataSegment::getIdentifier).collect(Collectors.toList())\n+            ),\n+            Preconditions.checkNotNull(handedOff.getCommitMetadata(), \"commitMetadata\")\n+        );\n+      }\n+\n+      appenderator.close();\n+      recordSupplier.close();\n+    }\n+    catch (InterruptedException | RejectedExecutionException e) {\n+      // (2) catch InterruptedException and RejectedExecutionException thrown for the whole ingestion steps including\n+      // the final publishing.\n+      caughtExceptionOuter = e;\n+      try {\n+        Futures.allAsList(publishWaitList).cancel(true);\n+        Futures.allAsList(handOffWaitList).cancel(true);\n+        if (appenderator != null) {\n+          appenderator.closeNow();\n+        }\n+      }\n+      catch (Exception e2) {\n+        e.addSuppressed(e2);\n+      }\n+\n+      // handle the InterruptedException that gets wrapped in a RejectedExecutionException\n+      if (e instanceof RejectedExecutionException\n+          && (e.getCause() == null || !(e.getCause() instanceof InterruptedException))) {\n+        throw e;\n+      }\n+\n+      // if we were interrupted because we were asked to stop, handle the exception and return success, else rethrow\n+      if (!stopRequested.get()) {\n+        Thread.currentThread().interrupt();\n+        throw e;\n+      }\n+\n+      log.info(\"The task was asked to stop before completing\");\n+    }\n+    catch (Exception e) {\n+      // (3) catch all other exceptions thrown for the whole ingestion steps including the final publishing.\n+      caughtExceptionOuter = e;\n+      try {\n+        Futures.allAsList(publishWaitList).cancel(true);\n+        Futures.allAsList(handOffWaitList).cancel(true);\n+        if (appenderator != null) {\n+          appenderator.closeNow();\n+        }\n+      }\n+      catch (Exception e2) {\n+        e.addSuppressed(e2);\n+      }\n+      throw e;\n+    }\n+    finally {\n+      try {\n+\n+        if (driver != null) {\n+          driver.close();\n+        }\n+        if (chatHandlerProvider.isPresent()) {\n+          chatHandlerProvider.get().unregister(task.getId());\n+        }\n+\n+        toolbox.getDruidNodeAnnouncer().unannounce(discoveryDruidNode);\n+        toolbox.getDataSegmentServerAnnouncer().unannounce();\n+      }\n+      catch (Exception e) {\n+        if (caughtExceptionOuter != null) {\n+          caughtExceptionOuter.addSuppressed(e);\n+        } else {\n+          throw e;\n+        }\n+      }\n+    }\n+\n+    toolbox.getTaskReportFileWriter().write(getTaskCompletionReports(null));\n+    return TaskStatus.success(task.getId());\n+  }\n+\n+  private void checkPublishAndHandoffFailure() throws ExecutionException, InterruptedException\n+  {\n+    // Check if any publishFuture failed.\n+    final List<ListenableFuture<SegmentsAndMetadata>> publishFinished = publishWaitList\n+        .stream()\n+        .filter(Future::isDone)\n+        .collect(Collectors.toList());\n+\n+    for (ListenableFuture<SegmentsAndMetadata> publishFuture : publishFinished) {\n+      // If publishFuture failed, the below line will throw an exception and catched by (1), and then (2) or (3).\n+      publishFuture.get();\n+    }\n+\n+    publishWaitList.removeAll(publishFinished);\n+\n+    // Check if any handoffFuture failed.\n+    final List<ListenableFuture<SegmentsAndMetadata>> handoffFinished = handOffWaitList\n+        .stream()\n+        .filter(Future::isDone)\n+        .collect(Collectors.toList());\n+\n+    for (ListenableFuture<SegmentsAndMetadata> handoffFuture : handoffFinished) {\n+      // If handoffFuture failed, the below line will throw an exception and catched by (1), and then (2) or (3).\n+      handoffFuture.get();\n+    }\n+\n+    handOffWaitList.removeAll(handoffFinished);\n+  }\n+\n+  private void publishAndRegisterHandoff(SequenceMetadata sequenceMetadata)\n+  {\n+    log.info(\"Publishing segments for sequence [%s]\", sequenceMetadata);\n+\n+    final ListenableFuture<SegmentsAndMetadata> publishFuture = Futures.transform(\n+        driver.publish(\n+            sequenceMetadata.createPublisher(toolbox, ioConfig.isUseTransaction()),\n+            sequenceMetadata.getCommitterSupplier(stream, lastPersistedOffsets).get(),\n+            Collections.singletonList(sequenceMetadata.getSequenceName())\n+        ),\n+        (Function<SegmentsAndMetadata, SegmentsAndMetadata>) publishedSegmentsAndMetadata -> {\n+          if (publishedSegmentsAndMetadata == null) {\n+            throw new ISE(\n+                \"Transaction failure publishing segments for sequence [%s]\",\n+                sequenceMetadata\n+            );\n+          } else {\n+            return publishedSegmentsAndMetadata;\n+          }\n+        }\n+    );\n+    publishWaitList.add(publishFuture);\n+\n+    // Create a handoffFuture for every publishFuture. The created handoffFuture must fail if publishFuture fails.\n+    final SettableFuture<SegmentsAndMetadata> handoffFuture = SettableFuture.create();\n+    handOffWaitList.add(handoffFuture);\n+\n+    Futures.addCallback(\n+        publishFuture,\n+        new FutureCallback<SegmentsAndMetadata>()\n+        {\n+          @Override\n+          public void onSuccess(SegmentsAndMetadata publishedSegmentsAndMetadata)\n+          {\n+            log.info(\n+                \"Published segments[%s] with metadata[%s].\",\n+                publishedSegmentsAndMetadata.getSegments()\n+                                            .stream()\n+                                            .map(DataSegment::getIdentifier)\n+                                            .collect(Collectors.toList()),\n+                Preconditions.checkNotNull(publishedSegmentsAndMetadata.getCommitMetadata(), \"commitMetadata\")\n+            );\n+\n+            sequences.remove(sequenceMetadata);\n+            publishingSequences.remove(sequenceMetadata.getSequenceName());\n+            try {\n+              persistSequences();\n+            }\n+            catch (IOException e) {\n+              log.error(e, \"Unable to persist state, dying\");\n+              handoffFuture.setException(e);\n+              throw new RuntimeException(e);\n+            }\n+\n+            Futures.transform(\n+                driver.registerHandoff(publishedSegmentsAndMetadata),\n+                new Function<SegmentsAndMetadata, Void>()\n+                {\n+                  @Nullable\n+                  @Override\n+                  public Void apply(@Nullable SegmentsAndMetadata handoffSegmentsAndMetadata)\n+                  {\n+                    if (handoffSegmentsAndMetadata == null) {\n+                      log.warn(\n+                          \"Failed to handoff segments[%s]\",\n+                          publishedSegmentsAndMetadata.getSegments()\n+                                                      .stream()\n+                                                      .map(DataSegment::getIdentifier)\n+                                                      .collect(Collectors.toList())\n+                      );\n+                    }\n+                    handoffFuture.set(handoffSegmentsAndMetadata);\n+                    return null;\n+                  }\n+                }\n+            );\n+          }\n+\n+          @Override\n+          public void onFailure(@ParametersAreNonnullByDefault Throwable t)\n+          {\n+            log.error(t, \"Error while publishing segments for sequence[%s]\", sequenceMetadata);\n+            handoffFuture.setException(t);\n+          }\n+        }\n+    );\n+  }\n+\n+  private static File getSequencesPersistFile(TaskToolbox toolbox)\n+  {\n+    return new File(toolbox.getPersistDir(), \"sequences.json\");\n+  }\n+\n+  private boolean restoreSequences() throws IOException\n+  {\n+    final File sequencesPersistFile = getSequencesPersistFile(toolbox);\n+    if (sequencesPersistFile.exists()) {\n+      sequences = new CopyOnWriteArrayList<>(\n+          toolbox.getObjectMapper().<List<SequenceMetadata>>readValue(\n+              sequencesPersistFile,\n+              new TypeReference<List<SequenceMetadata>>()\n+              {\n+              }\n+          )\n+      );\n+      return true;\n+    } else {\n+      return false;\n+    }\n+  }\n+\n+  private synchronized void persistSequences() throws IOException\n+  {\n+    log.info(\"Persisting Sequences Metadata [%s]\", sequences);\n+    toolbox.getObjectMapper().writerWithType(\n+        new TypeReference<List<SequenceMetadata>>()\n+        {\n+        }\n+    ).writeValue(getSequencesPersistFile(toolbox), sequences);\n+  }\n+\n+  private Map<String, TaskReport> getTaskCompletionReports(@Nullable String errorMsg)\n+  {\n+    return TaskReport.buildTaskReports(\n+        new IngestionStatsAndErrorsTaskReport(\n+            task.getId(),\n+            new IngestionStatsAndErrorsTaskReportData(\n+                ingestionState,\n+                getTaskCompletionUnparseableEvents(),\n+                getTaskCompletionRowStats(),\n+                errorMsg\n+            )\n+        )\n+    );\n+  }\n+\n+  private Map<String, Object> getTaskCompletionUnparseableEvents()\n+  {\n+    Map<String, Object> unparseableEventsMap = new HashMap<>();\n+    List<String> buildSegmentsParseExceptionMessages = IndexTaskUtils.getMessagesFromSavedParseExceptions(\n+        savedParseExceptions\n+    );\n+    if (buildSegmentsParseExceptionMessages != null) {\n+      unparseableEventsMap.put(RowIngestionMeters.BUILD_SEGMENTS, buildSegmentsParseExceptionMessages);\n+    }\n+    return unparseableEventsMap;\n+  }\n+\n+  private Map<String, Object> getTaskCompletionRowStats()\n+  {\n+    Map<String, Object> metrics = new HashMap<>();\n+    metrics.put(\n+        RowIngestionMeters.BUILD_SEGMENTS,\n+        rowIngestionMeters.getTotals()\n+    );\n+    return metrics;\n+  }\n+\n+\n+  private void maybePersistAndPublishSequences(Supplier<Committer> committerSupplier)\n+      throws InterruptedException\n+  {\n+    for (SequenceMetadata sequenceMetadata : sequences) {\n+      sequenceMetadata.updateAssignments(currOffsets);\n+      if (!sequenceMetadata.isOpen() && !publishingSequences.contains(sequenceMetadata.getSequenceName())) {\n+        publishingSequences.add(sequenceMetadata.getSequenceName());\n+        try {\n+          Object result = driver.persist(committerSupplier.get());\n+          log.info(\n+              \"Persist completed with results: [%s], adding sequence [%s] to publish queue\",\n+              result,\n+              sequenceMetadata\n+          );\n+          publishAndRegisterHandoff(sequenceMetadata);\n+        }\n+        catch (InterruptedException e) {\n+          log.warn(\"Interrupted while persisting sequence [%s]\", sequenceMetadata);\n+          throw e;\n+        }\n+      }\n+    }\n+  }\n+\n+  private Set<StreamPartition<PartitionType>> assignPartitions(\n+      RecordSupplier<PartitionType, SequenceType> recordSupplier\n+  )\n+  {\n+    final Set<StreamPartition<PartitionType>> assignment = new HashSet<>();\n+    for (Map.Entry<PartitionType, SequenceType> entry : currOffsets.entrySet()) {\n+      final SequenceType endOffset = endOffsets.get(entry.getKey());\n+      if (OrderedPartitionableRecord.END_OF_SHARD_MARKER.equals(endOffset)\n+          || SeekableStreamPartitions.NO_END_SEQUENCE_NUMBER.equals(endOffset)\n+          || createSequenceNumber(entry.getValue()).compareTo(createSequenceNumber(endOffset)) < 0) {\n+        assignment.add(StreamPartition.of(stream, entry.getKey()));\n+      } else if (entry.getValue().equals(endOffset)) {\n+        log.info(\"Finished reading partition[%s].\", entry.getKey());\n+      } else {\n+        throw new ISE(\n+            \"WTF?! Cannot start from sequence[%,d] > endOffset[%,d]\",\n+            entry.getValue(),\n+            endOffset\n+        );\n+      }\n+    }\n+\n+    recordSupplier.assign(assignment);\n+\n+    return assignment;\n+  }\n+\n+\n+  private void seekToStartingSequence(\n+      RecordSupplier<PartitionType, SequenceType> recordSupplier, Set<StreamPartition<PartitionType>> partitions\n+  )\n+  {\n+    for (final StreamPartition<PartitionType> partition : partitions) {\n+      final SequenceType sequence = currOffsets.get(partition.getPartitionId());\n+      log.info(\"Seeking partition[%s] to sequence[%s].\", partition.getPartitionId(), sequence);\n+      recordSupplier.seek(partition, sequence);\n+    }\n+  }\n+\n+  /**\n+   * Checks if the pauseRequested flag was set and if so blocks:\n+   * a) if pauseMillis == PAUSE_FOREVER, until pauseRequested is cleared\n+   * b) if pauseMillis != PAUSE_FOREVER, until pauseMillis elapses -or- pauseRequested is cleared\n+   * <p>\n+   * If pauseMillis is changed while paused, the new pause timeout will be applied. This allows adjustment of the\n+   * pause timeout (making a timed pause into an indefinite pause and vice versa is valid) without having to resume\n+   * and ensures that the loop continues to stay paused without ingesting any new events. You will need to signal\n+   * shouldResume after adjusting pauseMillis for the new value to take effect.\n+   * <p>\n+   * Sets paused = true and signals paused so callers can be notified when the pause command has been accepted.\n+   * <p>\n+   * Additionally, pauses if all partitions assignments have been read and pauseAfterRead flag is set.\n+   *\n+   * @return true if a pause request was handled, false otherwise\n+   */\n+  private boolean possiblyPause() throws InterruptedException\n+  {\n+    pauseLock.lockInterruptibly();\n+    try {\n+      if (pauseRequested) {\n+        status = Status.PAUSED;\n+        hasPaused.signalAll();\n+\n+        while (pauseRequested) {\n+          log.info(\"Pausing ingestion until resumed\");\n+          shouldResume.await();\n+        }\n+\n+        status = Status.READING;\n+        shouldResume.signalAll();\n+        log.info(\"Ingestion loop resumed\");\n+        return true;\n+      }\n+    }\n+    finally {\n+      pauseLock.unlock();\n+    }\n+\n+    return false;\n+  }\n+\n+  private void possiblyResetDataSourceMetadata(\n+      RecordSupplier<PartitionType, SequenceType> recordSupplier,\n+      Set<StreamPartition<PartitionType>> assignment\n+  )\n+  {\n+    for (final StreamPartition<PartitionType> streamPartition : assignment) {\n+      SequenceType sequence = currOffsets.get(streamPartition.getPartitionId());\n+      if (!tuningConfig.isSkipSequenceNumberAvailabilityCheck()) {\n+        SequenceType earliestSequenceNumber = recordSupplier.getEarliestSequenceNumber(streamPartition);\n+        /*\n+        if (earliestSequenceNumber == null) {\n+          log.warn(\n+              \"unable to verify sequence number[%s] availability, unable to fetch earliest sequence number\",\n+              sequence\n+          );\n+        }\n+        */\n+        if (earliestSequenceNumber == null\n+            || createSequenceNumber(earliestSequenceNumber).compareTo(createSequenceNumber(sequence)) > 0) {\n+          if (tuningConfig.isResetOffsetAutomatically()) {\n+            log.info(\"Attempting to reset sequences automatically for all partitions\");\n+            try {\n+              sendResetRequestAndWait(\n+                  assignment.stream()\n+                            .collect(Collectors.toMap(x -> x, x -> currOffsets.get(x.getPartitionId()))),\n+                  toolbox\n+              );\n+            }\n+            catch (IOException e) {\n+              throw new ISE(e, \"Exception while attempting to automatically reset sequences\");\n+            }\n+          } else {\n+            throw new ISE(\n+                \"Starting sequenceNumber [%s] is no longer available for partition [%s] (earliest: [%s]) and resetOffsetAutomatically is not enabled\",\n+                sequence,\n+                streamPartition.getPartitionId(),\n+                earliestSequenceNumber\n+            );\n+          }\n+        }\n+      }\n+    }\n+  }\n+\n+\n+  private void handleParseException(ParseException pe, OrderedPartitionableRecord record)\n+  {\n+    if (pe.isFromPartiallyValidRow()) {\n+      rowIngestionMeters.incrementProcessedWithError();\n+    } else {\n+      rowIngestionMeters.incrementUnparseable();\n+    }\n+\n+    if (tuningConfig.isLogParseExceptions()) {\n+      log.error(\n+          pe,\n+          \"Encountered parse exception on row from partition[%s] sequence[%s]\",\n+          record.getPartitionId(),\n+          record.getSequenceNumber()\n+      );\n+    }\n+\n+    if (savedParseExceptions != null) {\n+      savedParseExceptions.add(pe);\n+    }\n+\n+    if (rowIngestionMeters.getUnparseable() + rowIngestionMeters.getProcessedWithError()\n+        > tuningConfig.getMaxParseExceptions()) {\n+      log.error(\"Max parse exceptions exceeded, terminating task...\");\n+      throw new RuntimeException(\"Max parse exceptions exceeded, terminating task...\");\n+    }\n+  }\n+\n+  private boolean isPaused()\n+  {\n+    return status == Status.PAUSED;\n+  }\n+\n+  private void requestPause()\n+  {\n+    pauseRequested = true;\n+  }\n+\n+\n+  protected void sendResetRequestAndWait(\n+      Map<StreamPartition<PartitionType>, SequenceType> outOfRangePartitions,\n+      TaskToolbox taskToolbox\n+  )\n+      throws IOException\n+  {\n+    Map<PartitionType, SequenceType> partitionOffsetMap = outOfRangePartitions\n+        .entrySet().stream().collect(Collectors.toMap(x -> x.getKey().getPartitionId(), Map.Entry::getValue));\n+\n+    boolean result = taskToolbox\n+        .getTaskActionClient()\n+        .submit(\n+            new ResetDataSourceMetadataAction(\n+                task.getDataSource(),\n+                createDataSourceMetadata(\n+                    new SeekableStreamPartitions<>(\n+                        ioConfig.getStartPartitions().getStream(),\n+                        partitionOffsetMap\n+                    )\n+                )\n+            )\n+        );\n+\n+    if (result) {\n+      log.makeAlert(\"Resetting sequences for datasource [%s]\", task.getDataSource())\n+         .addData(\"partitions\", partitionOffsetMap.keySet())\n+         .emit();\n+\n+      requestPause();\n+    } else {\n+      log.makeAlert(\"Failed to send reset request for partitions [%s]\", partitionOffsetMap.keySet()).emit();\n+    }\n+  }\n+\n+  /**\n+   * Authorizes action to be performed on this task's datasource\n+   *\n+   * @return authorization result\n+   */\n+  private Access authorizationCheck(final HttpServletRequest req, Action action)\n+  {\n+    return IndexTaskUtils.datasourceAuthorizationCheck(req, action, task.getDataSource(), authorizerMapper);\n+  }\n+\n+  public Appenderator getAppenderator()\n+  {\n+    return appenderator;\n+  }\n \n   @VisibleForTesting\n-  Map<PartitionType, SequenceType> getCurrentOffsets();\n+  public RowIngestionMeters getRowIngestionMeters()\n+  {\n+    return rowIngestionMeters;\n+  }\n+\n+\n+  public void stopGracefully()\n+  {\n+    log.info(\"Stopping gracefully (status: [%s])\", status);\n+    stopRequested.set(true);\n+\n+    synchronized (statusLock) {\n+      if (status == Status.PUBLISHING) {\n+        runThread.interrupt();\n+        return;\n+      }\n+    }\n+\n+    try {\n+      if (pauseLock.tryLock(SeekableStreamIndexTask.LOCK_ACQUIRE_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {\n+        try {\n+          if (pauseRequested) {\n+            pauseRequested = false;\n+            shouldResume.signalAll();\n+          }\n+        }\n+        finally {\n+          pauseLock.unlock();\n+        }\n+      } else {\n+        log.warn(\"While stopping: failed to acquire pauseLock before timeout, interrupting run thread\");\n+        runThread.interrupt();\n+        return;\n+      }\n+\n+      if (pollRetryLock.tryLock(SeekableStreamIndexTask.LOCK_ACQUIRE_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {\n+        try {\n+          isAwaitingRetry.signalAll();\n+        }\n+        finally {\n+          pollRetryLock.unlock();\n+        }\n+      } else {\n+        log.warn(\"While stopping: failed to acquire pollRetryLock before timeout, interrupting run thread\");\n+        runThread.interrupt();\n+      }\n+    }\n+    catch (Exception e) {\n+      Throwables.propagate(e);\n+    }\n+  }\n+\n+  @POST\n+  @Path(\"/stop\")\n+  public Response stop(@Context final HttpServletRequest req)\n+  {\n+    authorizationCheck(req, Action.WRITE);\n+    stopGracefully();\n+    return Response.status(Response.Status.OK).build();\n+  }\n+\n+  @GET\n+  @Path(\"/status\")\n+  @Produces(MediaType.APPLICATION_JSON)\n+  public Status getStatusHTTP(@Context final HttpServletRequest req)\n+  {\n+    authorizationCheck(req, Action.READ);\n+    return status;\n+  }\n \n   @VisibleForTesting\n-  Map<PartitionType, SequenceType> getEndOffsets();\n+  public Status getStatus()\n+  {\n+    return status;\n+  }\n+\n+  @GET\n+  @Path(\"/offsets/current\")\n+  @Produces(MediaType.APPLICATION_JSON)\n+  public Map<PartitionType, SequenceType> getCurrentOffsets(@Context final HttpServletRequest req)\n+  {\n+    authorizationCheck(req, Action.READ);\n+    return getCurrentOffsets();\n+  }\n+\n+  public Map<PartitionType, SequenceType> getCurrentOffsets()\n+  {\n+    return currOffsets;\n+  }\n+\n+  @GET\n+  @Path(\"/offsets/end\")\n+  @Produces(MediaType.APPLICATION_JSON)\n+  public Map<PartitionType, SequenceType> getEndOffsetsHTTP(@Context final HttpServletRequest req)\n+  {\n+    authorizationCheck(req, Action.READ);\n+    return getEndOffsets();\n+  }\n+\n+  public Map<PartitionType, SequenceType> getEndOffsets()\n+  {\n+    return endOffsets;\n+  }\n+\n+  @POST\n+  @Path(\"/offsets/end\")\n+  @Consumes(MediaType.APPLICATION_JSON)\n+  @Produces(MediaType.APPLICATION_JSON)\n+  public Response setEndOffsetsHTTP(\n+      Map<PartitionType, SequenceType> sequences,\n+      @QueryParam(\"finish\") @DefaultValue(\"true\") final boolean finish,\n+      // this field is only for internal purposes, shouldn't be usually set by users\n+      @Context final HttpServletRequest req\n+  ) throws InterruptedException\n+  {\n+    authorizationCheck(req, Action.WRITE);\n+    return setEndOffsets(sequences, finish);\n+  }\n+\n+  @GET\n+  @Path(\"/rowStats\")\n+  @Produces(MediaType.APPLICATION_JSON)\n+  public Response getRowStats(\n+      @Context final HttpServletRequest req\n+  )\n+  {\n+    authorizationCheck(req, Action.READ);\n+    Map<String, Object> returnMap = new HashMap<>();\n+    Map<String, Object> totalsMap = new HashMap<>();\n+    Map<String, Object> averagesMap = new HashMap<>();\n+\n+    totalsMap.put(\n+        RowIngestionMeters.BUILD_SEGMENTS,\n+        rowIngestionMeters.getTotals()\n+    );\n+    averagesMap.put(\n+        RowIngestionMeters.BUILD_SEGMENTS,\n+        rowIngestionMeters.getMovingAverages()\n+    );\n+\n+    returnMap.put(\"movingAverages\", averagesMap);\n+    returnMap.put(\"totals\", totalsMap);\n+    return Response.ok(returnMap).build();\n+  }\n+\n+  @GET\n+  @Path(\"/unparseableEvents\")\n+  @Produces(MediaType.APPLICATION_JSON)\n+  public Response getUnparseableEvents(\n+      @Context final HttpServletRequest req\n+  )\n+  {\n+    authorizationCheck(req, Action.READ);\n+    List<String> events = IndexTaskUtils.getMessagesFromSavedParseExceptions(savedParseExceptions);\n+    return Response.ok(events).build();\n+  }\n \n   @VisibleForTesting\n-  Response setEndOffsets(\n-      Map<PartitionType, SequenceType> offsets,\n+  public Response setEndOffsets(\n+      Map<PartitionType, SequenceType> sequenceNumbers,\n       boolean finish // this field is only for internal purposes, shouldn't be usually set by users\n-  ) throws InterruptedException;\n+  ) throws InterruptedException\n+  {\n+    if (sequenceNumbers == null) {\n+      return Response.status(Response.Status.BAD_REQUEST)\n+                     .entity(\"Request body must contain a map of { partition:endOffset }\")\n+                     .build();\n+    } else if (!endOffsets.keySet().containsAll(sequenceNumbers.keySet())) {\n+      return Response.status(Response.Status.BAD_REQUEST)\n+                     .entity(\n+                         StringUtils.format(\n+                             \"Request contains partitions not being handled by this task, my partitions: %s\",\n+                             endOffsets.keySet()\n+                         )\n+                     )\n+                     .build();\n+    } else {\n+      try {\n+        pauseLock.lockInterruptibly();\n+        // Perform all sequence related checks before checking for isPaused()\n+        // and after acquiring pauseLock to correctly guard against duplicate requests\n+        Preconditions.checkState(sequenceNumbers.size() > 0, \"WTH?! No Sequences found to set end sequences\");\n+\n+        final SequenceMetadata latestSequence = sequences.get(sequences.size() - 1);\n+        // if a partition has not been read yet (contained in initialOffsetsSnapshot), then\n+        // do not mark the starting sequence number as exclusive\n+        Set<PartitionType> exclusivePartitions = sequenceNumbers.keySet()\n+                                                                .stream()\n+                                                                .filter(x -> !initialOffsetsSnapshot.containsKey(x)\n+                                                                             || ioConfig.getExclusiveStartSequenceNumberPartitions()\n+                                                                                        .contains(x))\n+                                                                .collect(Collectors.toSet());\n+\n+        if ((latestSequence.getStartOffsets().equals(sequenceNumbers) && latestSequence.exclusiveStartPartitions.equals(\n+            exclusivePartitions) && !finish) ||\n+            (latestSequence.getEndOffsets().equals(sequenceNumbers) && finish)) {\n+          log.warn(\"Ignoring duplicate request, end sequences already set for sequences [%s]\", sequenceNumbers);\n+          return Response.ok(sequenceNumbers).build();\n+        } else if (latestSequence.isCheckpointed()) {\n+          return Response.status(Response.Status.BAD_REQUEST)\n+                         .entity(StringUtils.format(\n+                             \"WTH?! Sequence [%s] has already endOffsets set, cannot set to [%s]\",\n+                             latestSequence,\n+                             sequenceNumbers\n+                         )).build();\n+        } else if (!isPaused()) {\n+          return Response.status(Response.Status.BAD_REQUEST)\n+                         .entity(\"Task must be paused before changing the end sequences\")\n+                         .build();\n+        }\n+\n+        for (Map.Entry<PartitionType, SequenceType> entry : sequenceNumbers.entrySet()) {\n+          if (createSequenceNumber(entry.getValue()).compareTo(createSequenceNumber(currOffsets.get(entry.getKey())))\n+              < 0) {\n+            return Response.status(Response.Status.BAD_REQUEST)\n+                           .entity(\n+                               StringUtils.format(\n+                                   \"End sequence must be >= current sequence for partition [%s] (current: %s)\",\n+                                   entry.getKey(),\n+                                   currOffsets.get(entry.getKey())\n+                               )\n+                           )\n+                           .build();\n+          }\n+        }\n+\n+        resetNextCheckpointTime();\n+        latestSequence.setEndOffsets(sequenceNumbers);\n+\n+        if (finish) {\n+          log.info(\"Updating endOffsets from [%s] to [%s]\", endOffsets, sequenceNumbers);\n+          endOffsets.putAll(sequenceNumbers);\n+        } else {\n+          exclusiveStartingPartitions.addAll(exclusivePartitions);\n+\n+          // create new sequence\n+          final SequenceMetadata newSequence = createSequenceMetaData(\n+              latestSequence.getSequenceId() + 1,\n+              StringUtils.format(\"%s_%d\", ioConfig.getBaseSequenceName(), latestSequence.getSequenceId() + 1),\n+              sequenceNumbers,\n+              endOffsets,\n+              false,\n+              exclusivePartitions\n+          );\n+          sequences.add(newSequence);\n+          initialOffsetsSnapshot.putAll(sequenceNumbers);\n+        }\n+        persistSequences();\n+      }\n+      catch (Exception e) {\n+        log.error(e, \"Unable to set end sequences, dying\");\n+        backgroundThreadException = e;\n+        // should resume to immediately finish kafka index task as failed\n+        resume();\n+        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)\n+                       .entity(Throwables.getStackTraceAsString(e))\n+                       .build();\n+      }\n+      finally {\n+        pauseLock.unlock();\n+      }\n+    }\n+\n+    resume();\n+\n+    return Response.ok(sequenceNumbers).build();\n+  }\n+\n+  private void resetNextCheckpointTime()\n+  {\n+    nextCheckpointTime = DateTimes.nowUtc().plus(tuningConfig.getIntermediateHandoffPeriod()).getMillis();\n+  }\n+\n+  @GET\n+  @Path(\"/checkpoints\")\n+  @Produces(MediaType.APPLICATION_JSON)\n+  public Map<Integer, Map<PartitionType, SequenceType>> getCheckpointsHTTP(@Context final HttpServletRequest req)\n+  {\n+    authorizationCheck(req, Action.READ);\n+    return getCheckpoints();\n+  }\n+\n+  private Map<Integer, Map<PartitionType, SequenceType>> getCheckpoints()\n+  {\n+    return new TreeMap<>(sequences.stream()\n+                                  .collect(Collectors.toMap(\n+                                      SequenceMetadata::getSequenceId,\n+                                      SequenceMetadata::getStartOffsets\n+                                  )));\n+  }\n+\n+  /**\n+   * Signals the ingestion loop to pause.\n+   *\n+   * @return one of the following Responses: 400 Bad Request if the task has started publishing; 202 Accepted if the\n+   * method has timed out and returned before the task has paused; 200 OK with a map of the current partition sequences\n+   * in the response body if the task successfully paused\n+   */\n+  @POST\n+  @Path(\"/pause\")\n+  @Produces(MediaType.APPLICATION_JSON)\n+  public Response pauseHTTP(\n+      @Context final HttpServletRequest req\n+  ) throws InterruptedException\n+  {\n+    authorizationCheck(req, Action.WRITE);\n+    return pause();\n+  }\n \n   @VisibleForTesting\n-  Response pause() throws InterruptedException;\n+  public Response pause() throws InterruptedException\n+  {\n+    if (!(status == Status.PAUSED || status == Status.READING)) {\n+      return Response.status(Response.Status.BAD_REQUEST)\n+                     .entity(StringUtils.format(\"Can't pause, task is not in a pausable state (state: [%s])\", status))\n+                     .build();\n+    }\n+\n+    pauseLock.lockInterruptibly();\n+    try {\n+      pauseRequested = true;\n+\n+      pollRetryLock.lockInterruptibly();\n+      try {\n+        isAwaitingRetry.signalAll();\n+      }\n+      finally {\n+        pollRetryLock.unlock();\n+      }\n+\n+      if (isPaused()) {\n+        shouldResume.signalAll(); // kick the monitor so it re-awaits with the new pauseMillis\n+      }\n+\n+      long nanos = TimeUnit.SECONDS.toNanos(2);\n+      while (!isPaused()) {\n+        if (nanos <= 0L) {\n+          return Response.status(Response.Status.ACCEPTED)\n+                         .entity(\"Request accepted but task has not yet paused\")\n+                         .build();\n+        }\n+        nanos = hasPaused.awaitNanos(nanos);\n+      }\n+ ","path":"indexing-service/src/main/java/org/apache/druid/indexing/seekablestream/SeekableStreamIndexTaskRunner.java","position":1689,"original_position":1690,"commit_id":"cc72cc9b52ba921cbcd48c93ed63b33db3aec54d","original_commit_id":"cc72cc9b52ba921cbcd48c93ed63b33db3aec54d","user":{"login":"dclim","id":11050882,"node_id":"MDQ6VXNlcjExMDUwODgy","avatar_url":"https://avatars2.githubusercontent.com/u/11050882?v=4","gravatar_id":"","url":"https://api.github.com/users/dclim","html_url":"https://github.com/dclim","followers_url":"https://api.github.com/users/dclim/followers","following_url":"https://api.github.com/users/dclim/following{/other_user}","gists_url":"https://api.github.com/users/dclim/gists{/gist_id}","starred_url":"https://api.github.com/users/dclim/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/dclim/subscriptions","organizations_url":"https://api.github.com/users/dclim/orgs","repos_url":"https://api.github.com/users/dclim/repos","events_url":"https://api.github.com/users/dclim/events{/privacy}","received_events_url":"https://api.github.com/users/dclim/received_events","type":"User","site_admin":false},"body":"Typo: 'exclusiveStartPartitions'","created_at":"2018-11-30T01:50:31Z","updated_at":"2018-11-30T01:57:50Z","html_url":"https://github.com/apache/incubator-druid/pull/6431#discussion_r237722857","pull_request_url":"https://api.github.com/repos/apache/incubator-druid/pulls/6431","author_association":"CONTRIBUTOR","_links":{"self":{"href":"https://api.github.com/repos/apache/incubator-druid/pulls/comments/237722857"},"html":{"href":"https://github.com/apache/incubator-druid/pull/6431#discussion_r237722857"},"pull_request":{"href":"https://api.github.com/repos/apache/incubator-druid/pulls/6431"}}},"pull_request":{"url":"https://api.github.com/repos/apache/incubator-druid/pulls/6431","id":221254181,"node_id":"MDExOlB1bGxSZXF1ZXN0MjIxMjU0MTgx","html_url":"https://github.com/apache/incubator-druid/pull/6431","diff_url":"https://github.com/apache/incubator-druid/pull/6431.diff","patch_url":"https://github.com/apache/incubator-druid/pull/6431.patch","issue_url":"https://api.github.com/repos/apache/incubator-druid/issues/6431","number":6431,"state":"open","locked":false,"title":"Add Kinesis Indexing Service to core Druid","user":{"login":"jsun98","id":11185501,"node_id":"MDQ6VXNlcjExMTg1NTAx","avatar_url":"https://avatars2.githubusercontent.com/u/11185501?v=4","gravatar_id":"","url":"https://api.github.com/users/jsun98","html_url":"https://github.com/jsun98","followers_url":"https://api.github.com/users/jsun98/followers","following_url":"https://api.github.com/users/jsun98/following{/other_user}","gists_url":"https://api.github.com/users/jsun98/gists{/gist_id}","starred_url":"https://api.github.com/users/jsun98/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/jsun98/subscriptions","organizations_url":"https://api.github.com/users/jsun98/orgs","repos_url":"https://api.github.com/users/jsun98/repos","events_url":"https://api.github.com/users/jsun98/events{/privacy}","received_events_url":"https://api.github.com/users/jsun98/received_events","type":"User","site_admin":false},"body":"## Motivation\r\nThe motivation for this PR is to add `kinesis-indexing-service` to core druid extensions and provide an abstraction `seekablestream` for streaming systems with the following characteristics:\r\n- **Seekable**: ability to seek to a specific point in the stream - so that we can store the offsets transactionally in an external system to ensure correctness and can return to a specific record if we need to retry after a failure\r\n- **Partition-able**: so that ingestion can be scaled out and handled by multiple indexing tasks\r\n- **Partition-ordered**: so that we have deterministic results from replica tasks that are independently reading the same partition\r\n\r\n## Major changes\r\n- Added `kinesis-indexing-service` to core druid extensions.\r\n- Created a number of abstract classes in `org.apache.druid.indexing.seekablestream` to serve as the parent classes for both Kafka and Kinesis\r\n- Grouped common logic between the Kinesis and Kafka indexing services into the seekablestream classes as much as possible, the child classes define operations specific to Kafka or Kinesis\r\n- Created `OrderedPartitionableRecord` as an abstraction for records that have an ordering within a partition in a stream\r\n- Created `OrderedSequenceNumber` as an abstraction for ordered, comparable sequence numbers\r\n- Created `StreamPartition` as an abstraction for partitions in a partition-able stream\r\n- Modified all classes in Kafka and Kinesis indexing service to extend their corresponding parent classes in seekablestream\r\n- unit test coverage for Kinesis Indexing Service\r\n\r\nThe logic in `KinesisIndexTask` and `KafkaIndexTask` has not been merged yet, due to Kinesis not yet supporting incremental handoff, but this will be implemented in a follow-up PR. The code in the two index tasks are left as is for now.\r\n\r\nThe unit tests for Kinesis depends on [LocalStack](https://github.com/localstack/localstack), a local AWS testing stack, which requires a **running Docker** instance\r\n\r\n## Definition of Abstractions\r\nThe following classes can be found in the `org.apache.druid.indexing.seekablestream` package\r\n\r\n### `SeekableStreamSupervisor` class\r\n- all logic are essentially the same as in `KafkaSupervisor` including lifecycle, `start()` and `stop()`\r\n- moved `runInternal()` and the methods it calls here\r\n- replaced all `Kafka` or `Kinesis` specific objects (e.g. `KafkaDataSourceMetadata`) with the corresponding `SeekableStream` version (e.g. `SeekableStreamDataSourceMetadata`)\r\n- the `protected abstract` methods defined at the end of the class are used to perform Kafka or Kinesis specific tasks, such as `checkSourceMetaDataMatch()` checks if the passed in metadata is an instance of Kafka/Kinesis datasource metadata\r\n- `KafkaConsumer` instances have been replaced by `RecordSupplier`, see below\r\n- incremental handoff / checkpointing is not yet implemented for Kinesis, but will be in a follow-up PR\r\n- Kinesis does not have the concept of `lag`, so something similar will be implemented in a follow-up PR\r\n\r\n### `RecordSupplier` interface\r\n- this is a wrapper interface for consuming records from ordered, partition-able streams. \r\n- Implemented by `KafkaRecordSupplier` and `KinesisRecordSupplier`. \r\n- Currently used in `SeekableStreamSupervisor` and will be used in `SeekableStreamIndexTask` in the follow-up PR. \r\n- It serves to provide a uniform interface between Kafka and Kinesis streams for providing records. It uses `StreamPartition` and `Record` classes to abstract the differences between Kafka and Kinesis partition / offset / sequence.\r\n- Defines methods to seek to the earliest/latest position in a given partition\r\n- Defines methods to seek to a specific sequence number, the sequence immediately following, and immediately before\r\n- methods usually take `StreamPartition` as input, and returns `Record`\r\n- `KafkaRecordSupplier` wraps the `KafkaConsumer` object\r\n- `KinesisRecordSupplier` uses a `AmazonKinesisClient` to get records from Kinesis stream.\r\n\r\n\r\n### `OrderedSequenceNumber` class\r\n- this is the wrapper class for Kafka/Kinesis sequence number / offset.\r\n- implements `Comparable<partitionType, sequenceType>`\r\n- implemented by `KafkaSequenceNumber` and `KinesisSequenceNumber`\r\n- its main purpose is to provide the ability to compare sequences / offsets and make sure that they come in the correct order\r\n\r\n### `OrderedPartitionableRecord` class\r\n- wrapper for a record within a partition-able, partition-ordered stream\r\n- provides a uniform interface to interact with `RecordSupplier` and the index task classes\r\n- defines stream, partition, and sequence the record belongs to, as well as the actual data in the record\r\n\r\n### `SeekableStreamPartitions` class\r\n- the `[Kafka/Kinesis]Paritions` classes were removed in favor of using this class\r\n- due to the use of generics, deserializing using Jackson requires constructing a specific TypeReference. Details see code\r\n- reason for defining redundant getters such as `getTopic()` and `getStream()` is for Jackson deserialization\r\n- creating separate `KafkaStreamPartitions` and `KinesisStreamPartitions` classes was considered, but ultimately I think it makes more sense to have 1 generic class instead of 3 separate classes\r\n\r\n### `SeekableStreamIndexTaskRunner` interface\r\n- this interface is basically `KafkaIndexTaskRunner` renamed\r\n- Kinesis index task currently does not separate the runner logic as Kafka does, so this interface is only implemented by the Kafka task runners\r\n- will be implemented by Kinesis tasks in a followup PR\r\n\r\n### `TaskReportData` class\r\n- moved this class from Kafka indexing service into SeekableStream\r\n\r\n## Compatibility with other streaming systems\r\nThis abstract design is specifically aimed at partition-able, partition-ordered stream systems such as Kafka and Kinesis. Systems that do not have partitions or do not offer ordering within partitions are not good fits under this abstraction. \r\n\r\n## Files not changed significantly\r\nThese are files that have been refactored to extend the SeekableStream super class, but their code has not changed much since the Kinesis and Kafka versions are similar enough\r\n- `[Kafka/Kinesis]SupervisorIOConfig`\r\n- `[Kafka/Kinesis]SupervisorReportPayload`\r\n- `[Kafka/Kinesis]SupervisorSpec`\r\n- `[Kafka/Kinesis]SupervisorTuningConfig`\r\n- `[Kafka/Kinesis]TaskReportData`\r\n- `[Kafka/Kinesis]DataSourceMetadata`\r\n- `[Kafka/Kinesis]IndexTask`\r\n- `[Kafka/Kinesis]IndexTaskClient`\r\n- `[Kafka/Kinesis]IndexTaskClientFactory`\r\n- `[Kafka/Kinesis]IOConfig`\r\n- `[Kafka/Kinesis]TuningConfig`","created_at":"2018-10-08T21:57:39Z","updated_at":"2018-11-30T01:57:50Z","closed_at":null,"merged_at":null,"merge_commit_sha":"06ba1612aea080d1facc3af5322f71e5c6c8ca25","assignee":{"login":"dclim","id":11050882,"node_id":"MDQ6VXNlcjExMDUwODgy","avatar_url":"https://avatars2.githubusercontent.com/u/11050882?v=4","gravatar_id":"","url":"https://api.github.com/users/dclim","html_url":"https://github.com/dclim","followers_url":"https://api.github.com/users/dclim/followers","following_url":"https://api.github.com/users/dclim/following{/other_user}","gists_url":"https://api.github.com/users/dclim/gists{/gist_id}","starred_url":"https://api.github.com/users/dclim/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/dclim/subscriptions","organizations_url":"https://api.github.com/users/dclim/orgs","repos_url":"https://api.github.com/users/dclim/repos","events_url":"https://api.github.com/users/dclim/events{/privacy}","received_events_url":"https://api.github.com/users/dclim/received_events","type":"User","site_admin":false},"assignees":[{"login":"dclim","id":11050882,"node_id":"MDQ6VXNlcjExMDUwODgy","avatar_url":"https://avatars2.githubusercontent.com/u/11050882?v=4","gravatar_id":"","url":"https://api.github.com/users/dclim","html_url":"https://github.com/dclim","followers_url":"https://api.github.com/users/dclim/followers","following_url":"https://api.github.com/users/dclim/following{/other_user}","gists_url":"https://api.github.com/users/dclim/gists{/gist_id}","starred_url":"https://api.github.com/users/dclim/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/dclim/subscriptions","organizations_url":"https://api.github.com/users/dclim/orgs","repos_url":"https://api.github.com/users/dclim/repos","events_url":"https://api.github.com/users/dclim/events{/privacy}","received_events_url":"https://api.github.com/users/dclim/received_events","type":"User","site_admin":false}],"requested_reviewers":[],"requested_teams":[],"labels":[{"id":698268891,"node_id":"MDU6TGFiZWw2OTgyNjg4OTE=","url":"https://api.github.com/repos/apache/incubator-druid/labels/Area%20-%20Extension","name":"Area - Extension","color":"fef2c0","default":false},{"id":219582906,"node_id":"MDU6TGFiZWwyMTk1ODI5MDY=","url":"https://api.github.com/repos/apache/incubator-druid/labels/Area%20-%20Indexing","name":"Area - Indexing","color":"fef2c0","default":false},{"id":690563043,"node_id":"MDU6TGFiZWw2OTA1NjMwNDM=","url":"https://api.github.com/repos/apache/incubator-druid/labels/Area%20-%20Kafka%20Indexing","name":"Area - Kafka Indexing","color":"fef2c0","default":false},{"id":592291319,"node_id":"MDU6TGFiZWw1OTIyOTEzMTk=","url":"https://api.github.com/repos/apache/incubator-druid/labels/Design%20Review","name":"Design Review","color":"f9d0c4","default":false},{"id":17287687,"node_id":"MDU6TGFiZWwxNzI4NzY4Nw==","url":"https://api.github.com/repos/apache/incubator-druid/labels/Feature","name":"Feature","color":"2ceefb","default":false}],"milestone":{"url":"https://api.github.com/repos/apache/incubator-druid/milestones/29","html_url":"https://github.com/apache/incubator-druid/milestone/29","labels_url":"https://api.github.com/repos/apache/incubator-druid/milestones/29/labels","id":3663294,"node_id":"MDk6TWlsZXN0b25lMzY2MzI5NA==","number":29,"title":"0.13.1","description":"","creator":{"login":"jon-wei","id":8729063,"node_id":"MDQ6VXNlcjg3MjkwNjM=","avatar_url":"https://avatars3.githubusercontent.com/u/8729063?v=4","gravatar_id":"","url":"https://api.github.com/users/jon-wei","html_url":"https://github.com/jon-wei","followers_url":"https://api.github.com/users/jon-wei/followers","following_url":"https://api.github.com/users/jon-wei/following{/other_user}","gists_url":"https://api.github.com/users/jon-wei/gists{/gist_id}","starred_url":"https://api.github.com/users/jon-wei/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/jon-wei/subscriptions","organizations_url":"https://api.github.com/users/jon-wei/orgs","repos_url":"https://api.github.com/users/jon-wei/repos","events_url":"https://api.github.com/users/jon-wei/events{/privacy}","received_events_url":"https://api.github.com/users/jon-wei/received_events","type":"User","site_admin":false},"open_issues":36,"closed_issues":40,"state":"open","created_at":"2018-09-17T20:58:12Z","updated_at":"2018-11-29T05:59:30Z","due_on":null,"closed_at":null},"commits_url":"https://api.github.com/repos/apache/incubator-druid/pulls/6431/commits","review_comments_url":"https://api.github.com/repos/apache/incubator-druid/pulls/6431/comments","review_comment_url":"https://api.github.com/repos/apache/incubator-druid/pulls/comments{/number}","comments_url":"https://api.github.com/repos/apache/incubator-druid/issues/6431/comments","statuses_url":"https://api.github.com/repos/apache/incubator-druid/statuses/cc72cc9b52ba921cbcd48c93ed63b33db3aec54d","head":{"label":"jsun98:seekablestream","ref":"seekablestream","sha":"cc72cc9b52ba921cbcd48c93ed63b33db3aec54d","user":{"login":"jsun98","id":11185501,"node_id":"MDQ6VXNlcjExMTg1NTAx","avatar_url":"https://avatars2.githubusercontent.com/u/11185501?v=4","gravatar_id":"","url":"https://api.github.com/users/jsun98","html_url":"https://github.com/jsun98","followers_url":"https://api.github.com/users/jsun98/followers","following_url":"https://api.github.com/users/jsun98/following{/other_user}","gists_url":"https://api.github.com/users/jsun98/gists{/gist_id}","starred_url":"https://api.github.com/users/jsun98/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/jsun98/subscriptions","organizations_url":"https://api.github.com/users/jsun98/orgs","repos_url":"https://api.github.com/users/jsun98/repos","events_url":"https://api.github.com/users/jsun98/events{/privacy}","received_events_url":"https://api.github.com/users/jsun98/received_events","type":"User","site_admin":false},"repo":{"id":146517920,"node_id":"MDEwOlJlcG9zaXRvcnkxNDY1MTc5MjA=","name":"druid","full_name":"jsun98/druid","private":false,"owner":{"login":"jsun98","id":11185501,"node_id":"MDQ6VXNlcjExMTg1NTAx","avatar_url":"https://avatars2.githubusercontent.com/u/11185501?v=4","gravatar_id":"","url":"https://api.github.com/users/jsun98","html_url":"https://github.com/jsun98","followers_url":"https://api.github.com/users/jsun98/followers","following_url":"https://api.github.com/users/jsun98/following{/other_user}","gists_url":"https://api.github.com/users/jsun98/gists{/gist_id}","starred_url":"https://api.github.com/users/jsun98/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/jsun98/subscriptions","organizations_url":"https://api.github.com/users/jsun98/orgs","repos_url":"https://api.github.com/users/jsun98/repos","events_url":"https://api.github.com/users/jsun98/events{/privacy}","received_events_url":"https://api.github.com/users/jsun98/received_events","type":"User","site_admin":false},"html_url":"https://github.com/jsun98/druid","description":"Apache Druid (Incubating) - Column oriented distributed data store ideal for powering interactive applications","fork":true,"url":"https://api.github.com/repos/jsun98/druid","forks_url":"https://api.github.com/repos/jsun98/druid/forks","keys_url":"https://api.github.com/repos/jsun98/druid/keys{/key_id}","collaborators_url":"https://api.github.com/repos/jsun98/druid/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/jsun98/druid/teams","hooks_url":"https://api.github.com/repos/jsun98/druid/hooks","issue_events_url":"https://api.github.com/repos/jsun98/druid/issues/events{/number}","events_url":"https://api.github.com/repos/jsun98/druid/events","assignees_url":"https://api.github.com/repos/jsun98/druid/assignees{/user}","branches_url":"https://api.github.com/repos/jsun98/druid/branches{/branch}","tags_url":"https://api.github.com/repos/jsun98/druid/tags","blobs_url":"https://api.github.com/repos/jsun98/druid/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/jsun98/druid/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/jsun98/druid/git/refs{/sha}","trees_url":"https://api.github.com/repos/jsun98/druid/git/trees{/sha}","statuses_url":"https://api.github.com/repos/jsun98/druid/statuses/{sha}","languages_url":"https://api.github.com/repos/jsun98/druid/languages","stargazers_url":"https://api.github.com/repos/jsun98/druid/stargazers","contributors_url":"https://api.github.com/repos/jsun98/druid/contributors","subscribers_url":"https://api.github.com/repos/jsun98/druid/subscribers","subscription_url":"https://api.github.com/repos/jsun98/druid/subscription","commits_url":"https://api.github.com/repos/jsun98/druid/commits{/sha}","git_commits_url":"https://api.github.com/repos/jsun98/druid/git/commits{/sha}","comments_url":"https://api.github.com/repos/jsun98/druid/comments{/number}","issue_comment_url":"https://api.github.com/repos/jsun98/druid/issues/comments{/number}","contents_url":"https://api.github.com/repos/jsun98/druid/contents/{+path}","compare_url":"https://api.github.com/repos/jsun98/druid/compare/{base}...{head}","merges_url":"https://api.github.com/repos/jsun98/druid/merges","archive_url":"https://api.github.com/repos/jsun98/druid/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/jsun98/druid/downloads","issues_url":"https://api.github.com/repos/jsun98/druid/issues{/number}","pulls_url":"https://api.github.com/repos/jsun98/druid/pulls{/number}","milestones_url":"https://api.github.com/repos/jsun98/druid/milestones{/number}","notifications_url":"https://api.github.com/repos/jsun98/druid/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/jsun98/druid/labels{/name}","releases_url":"https://api.github.com/repos/jsun98/druid/releases{/id}","deployments_url":"https://api.github.com/repos/jsun98/druid/deployments","created_at":"2018-08-28T23:25:08Z","updated_at":"2018-11-01T18:01:25Z","pushed_at":"2018-11-28T01:45:51Z","git_url":"git://github.com/jsun98/druid.git","ssh_url":"git@github.com:jsun98/druid.git","clone_url":"https://github.com/jsun98/druid.git","svn_url":"https://github.com/jsun98/druid","homepage":"http://druid.io","size":150158,"stargazers_count":1,"watchers_count":1,"language":"Java","has_issues":false,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"forks_count":1,"mirror_url":null,"archived":false,"open_issues_count":0,"license":{"key":"apache-2.0","name":"Apache License 2.0","spdx_id":"Apache-2.0","url":"https://api.github.com/licenses/apache-2.0","node_id":"MDc6TGljZW5zZTI="},"forks":1,"open_issues":0,"watchers":1,"default_branch":"master"}},"base":{"label":"apache:master","ref":"master","sha":"81c9a6177cc6958942eaa9ea294fe96c4a3708f4","user":{"login":"apache","id":47359,"node_id":"MDEyOk9yZ2FuaXphdGlvbjQ3MzU5","avatar_url":"https://avatars0.githubusercontent.com/u/47359?v=4","gravatar_id":"","url":"https://api.github.com/users/apache","html_url":"https://github.com/apache","followers_url":"https://api.github.com/users/apache/followers","following_url":"https://api.github.com/users/apache/following{/other_user}","gists_url":"https://api.github.com/users/apache/gists{/gist_id}","starred_url":"https://api.github.com/users/apache/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/apache/subscriptions","organizations_url":"https://api.github.com/users/apache/orgs","repos_url":"https://api.github.com/users/apache/repos","events_url":"https://api.github.com/users/apache/events{/privacy}","received_events_url":"https://api.github.com/users/apache/received_events","type":"Organization","site_admin":false},"repo":{"id":6358188,"node_id":"MDEwOlJlcG9zaXRvcnk2MzU4MTg4","name":"incubator-druid","full_name":"apache/incubator-druid","private":false,"owner":{"login":"apache","id":47359,"node_id":"MDEyOk9yZ2FuaXphdGlvbjQ3MzU5","avatar_url":"https://avatars0.githubusercontent.com/u/47359?v=4","gravatar_id":"","url":"https://api.github.com/users/apache","html_url":"https://github.com/apache","followers_url":"https://api.github.com/users/apache/followers","following_url":"https://api.github.com/users/apache/following{/other_user}","gists_url":"https://api.github.com/users/apache/gists{/gist_id}","starred_url":"https://api.github.com/users/apache/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/apache/subscriptions","organizations_url":"https://api.github.com/users/apache/orgs","repos_url":"https://api.github.com/users/apache/repos","events_url":"https://api.github.com/users/apache/events{/privacy}","received_events_url":"https://api.github.com/users/apache/received_events","type":"Organization","site_admin":false},"html_url":"https://github.com/apache/incubator-druid","description":"Apache Druid (Incubating) - Column oriented distributed data store ideal for powering interactive applications","fork":false,"url":"https://api.github.com/repos/apache/incubator-druid","forks_url":"https://api.github.com/repos/apache/incubator-druid/forks","keys_url":"https://api.github.com/repos/apache/incubator-druid/keys{/key_id}","collaborators_url":"https://api.github.com/repos/apache/incubator-druid/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/apache/incubator-druid/teams","hooks_url":"https://api.github.com/repos/apache/incubator-druid/hooks","issue_events_url":"https://api.github.com/repos/apache/incubator-druid/issues/events{/number}","events_url":"https://api.github.com/repos/apache/incubator-druid/events","assignees_url":"https://api.github.com/repos/apache/incubator-druid/assignees{/user}","branches_url":"https://api.github.com/repos/apache/incubator-druid/branches{/branch}","tags_url":"https://api.github.com/repos/apache/incubator-druid/tags","blobs_url":"https://api.github.com/repos/apache/incubator-druid/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/apache/incubator-druid/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/apache/incubator-druid/git/refs{/sha}","trees_url":"https://api.github.com/repos/apache/incubator-druid/git/trees{/sha}","statuses_url":"https://api.github.com/repos/apache/incubator-druid/statuses/{sha}","languages_url":"https://api.github.com/repos/apache/incubator-druid/languages","stargazers_url":"https://api.github.com/repos/apache/incubator-druid/stargazers","contributors_url":"https://api.github.com/repos/apache/incubator-druid/contributors","subscribers_url":"https://api.github.com/repos/apache/incubator-druid/subscribers","subscription_url":"https://api.github.com/repos/apache/incubator-druid/subscription","commits_url":"https://api.github.com/repos/apache/incubator-druid/commits{/sha}","git_commits_url":"https://api.github.com/repos/apache/incubator-druid/git/commits{/sha}","comments_url":"https://api.github.com/repos/apache/incubator-druid/comments{/number}","issue_comment_url":"https://api.github.com/repos/apache/incubator-druid/issues/comments{/number}","contents_url":"https://api.github.com/repos/apache/incubator-druid/contents/{+path}","compare_url":"https://api.github.com/repos/apache/incubator-druid/compare/{base}...{head}","merges_url":"https://api.github.com/repos/apache/incubator-druid/merges","archive_url":"https://api.github.com/repos/apache/incubator-druid/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/apache/incubator-druid/downloads","issues_url":"https://api.github.com/repos/apache/incubator-druid/issues{/number}","pulls_url":"https://api.github.com/repos/apache/incubator-druid/pulls{/number}","milestones_url":"https://api.github.com/repos/apache/incubator-druid/milestones{/number}","notifications_url":"https://api.github.com/repos/apache/incubator-druid/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/apache/incubator-druid/labels{/name}","releases_url":"https://api.github.com/repos/apache/incubator-druid/releases{/id}","deployments_url":"https://api.github.com/repos/apache/incubator-druid/deployments","created_at":"2012-10-23T19:08:07Z","updated_at":"2018-11-30T01:49:12Z","pushed_at":"2018-11-30T01:24:27Z","git_url":"git://github.com/apache/incubator-druid.git","ssh_url":"git@github.com:apache/incubator-druid.git","clone_url":"https://github.com/apache/incubator-druid.git","svn_url":"https://github.com/apache/incubator-druid","homepage":"http://druid.io","size":150917,"stargazers_count":7279,"watchers_count":7279,"language":"Java","has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"forks_count":1784,"mirror_url":null,"archived":false,"open_issues_count":1197,"license":{"key":"apache-2.0","name":"Apache License 2.0","spdx_id":"Apache-2.0","url":"https://api.github.com/licenses/apache-2.0","node_id":"MDc6TGljZW5zZTI="},"forks":1784,"open_issues":1197,"watchers":7279,"default_branch":"master"}},"_links":{"self":{"href":"https://api.github.com/repos/apache/incubator-druid/pulls/6431"},"html":{"href":"https://github.com/apache/incubator-druid/pull/6431"},"issue":{"href":"https://api.github.com/repos/apache/incubator-druid/issues/6431"},"comments":{"href":"https://api.github.com/repos/apache/incubator-druid/issues/6431/comments"},"review_comments":{"href":"https://api.github.com/repos/apache/incubator-druid/pulls/6431/comments"},"review_comment":{"href":"https://api.github.com/repos/apache/incubator-druid/pulls/comments{/number}"},"commits":{"href":"https://api.github.com/repos/apache/incubator-druid/pulls/6431/commits"},"statuses":{"href":"https://api.github.com/repos/apache/incubator-druid/statuses/cc72cc9b52ba921cbcd48c93ed63b33db3aec54d"}},"author_association":"CONTRIBUTOR"}}
{"actor":{"display_login":"dclim"}}