anishshri-db commented on code in PR #53159:
URL: https://github.com/apache/spark/pull/53159#discussion_r2656012668


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/transformwithstate/testing/InMemoryStatefulProcessorHandle.scala:
##########
@@ -0,0 +1,332 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package 
org.apache.spark.sql.execution.streaming.operators.stateful.transformwithstate.testing
+
+import java.time.{Clock, Instant}
+import java.util.UUID
+
+import scala.collection.mutable
+import scala.reflect.ClassTag
+
+import org.apache.spark.sql.Encoder
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.transformwithstate.statefulprocessor.ImplicitGroupingKeyTracker
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.transformwithstate.statefulprocessor.QueryInfoImpl
+import org.apache.spark.sql.streaming.{ListState, MapState, QueryInfo, 
StatefulProcessorHandle, TimeMode, TTLConfig, ValueState}
+
+/** Helper to track expired keys. */
+class TtlTracker(val clock: Clock, ttl: TTLConfig) {
+  require(!ttl.ttlDuration.isNegative())
+  private val keyToLastUpdatedTime = mutable.Map[Any, Instant]()
+
+  def isKeyExpired(): Boolean = {
+    if (ttl.ttlDuration.isZero()) {
+      return false
+    }
+    val key = ImplicitGroupingKeyTracker.getImplicitKeyOption.get
+    if (!keyToLastUpdatedTime.contains(key)) {
+      return false
+    }
+    val expiration: Instant = 
keyToLastUpdatedTime.get(key).get.plus(ttl.ttlDuration)
+    return expiration.isBefore(clock.instant())
+  }
+
+  def onKeyUpdated(): Unit = {
+    val key = ImplicitGroupingKeyTracker.getImplicitKeyOption.get
+    keyToLastUpdatedTime.put(key, clock.instant())
+  }
+}
+
+/** In-memory implementation of ValueState. */
+class InMemoryValueState[T](clock: Clock, ttl: TTLConfig) extends 
ValueState[T] {
+  private val keyToStateValue = mutable.Map[Any, T]()
+  private val ttlTracker = new TtlTracker(clock, ttl)
+
+  private def getValue: Option[T] = {
+    if (ttlTracker.isKeyExpired()) {
+      return None
+    }
+    keyToStateValue.get(ImplicitGroupingKeyTracker.getImplicitKeyOption.get)
+  }
+  override def exists(): Boolean = getValue.isDefined
+
+  override def get(): T = getValue.getOrElse(null.asInstanceOf[T])
+
+  override def update(newState: T): Unit = {
+    ttlTracker.onKeyUpdated()
+    keyToStateValue.put(ImplicitGroupingKeyTracker.getImplicitKeyOption.get, 
newState)
+  }
+
+  override def clear(): Unit =
+    keyToStateValue.remove(ImplicitGroupingKeyTracker.getImplicitKeyOption.get)
+}
+
+/** In-memory implementation of ListState. */
+class InMemoryListState[T](clock: Clock, ttl: TTLConfig) extends ListState[T] {
+  private val keyToStateValue = mutable.Map[Any, mutable.ArrayBuffer[T]]()
+  private val ttlTracker = new TtlTracker(clock, ttl)
+
+  private def getList: Option[mutable.ArrayBuffer[T]] = {
+    if (ttlTracker.isKeyExpired()) {
+      return None
+    }
+    keyToStateValue.get(ImplicitGroupingKeyTracker.getImplicitKeyOption.get)
+  }
+
+  override def exists(): Boolean = getList.isDefined
+
+  override def get(): Iterator[T] = {
+    getList.orElse(Some(mutable.ArrayBuffer.empty[T])).get.iterator
+  }
+
+  override def put(newState: Array[T]): Unit = {
+    ttlTracker.onKeyUpdated()
+    keyToStateValue.put(
+      ImplicitGroupingKeyTracker.getImplicitKeyOption.get,
+      mutable.ArrayBuffer.empty[T] ++ newState
+    )
+  }
+
+  override def appendValue(newState: T): Unit = {
+    ttlTracker.onKeyUpdated()
+    if (!exists()) {
+      keyToStateValue.put(
+        ImplicitGroupingKeyTracker.getImplicitKeyOption.get,
+        mutable.ArrayBuffer.empty[T]
+      )
+    }
+    keyToStateValue(ImplicitGroupingKeyTracker.getImplicitKeyOption.get) += 
newState
+  }
+
+  override def appendList(newState: Array[T]): Unit = {
+    ttlTracker.onKeyUpdated()
+    if (!exists()) {
+      keyToStateValue.put(
+        ImplicitGroupingKeyTracker.getImplicitKeyOption.get,
+        mutable.ArrayBuffer.empty[T]
+      )
+    }
+    keyToStateValue(ImplicitGroupingKeyTracker.getImplicitKeyOption.get) ++= 
newState
+  }
+
+  override def clear(): Unit = {
+    keyToStateValue.remove(ImplicitGroupingKeyTracker.getImplicitKeyOption.get)
+  }
+}
+
+/** In-memory implementation of MapState. */
+class InMemoryMapState[K, V](clock: Clock, ttl: TTLConfig) extends MapState[K, 
V] {
+  private val keyToStateValue = mutable.Map[Any, mutable.HashMap[K, V]]()
+  private val ttlTracker = new TtlTracker(clock, ttl)
+
+  private def getMap: Option[mutable.HashMap[K, V]] = {
+    if (ttlTracker.isKeyExpired()) {
+      return None
+    }
+    keyToStateValue.get(ImplicitGroupingKeyTracker.getImplicitKeyOption.get)
+  }
+
+  override def exists(): Boolean = getMap.isDefined
+
+  override def getValue(key: K): V = {
+    getMap.flatMap(_.get(key)).getOrElse(null.asInstanceOf[V])
+  }
+
+  override def containsKey(key: K): Boolean = {
+    getMap.exists(_.contains(key))
+  }
+
+  override def updateValue(key: K, value: V): Unit = {
+    ttlTracker.onKeyUpdated()
+    if (!exists()) {
+      keyToStateValue.put(
+        ImplicitGroupingKeyTracker.getImplicitKeyOption.get,
+        mutable.HashMap.empty[K, V]
+      )
+    }
+
+    keyToStateValue(ImplicitGroupingKeyTracker.getImplicitKeyOption.get) += 
(key -> value)
+  }
+
+  override def iterator(): Iterator[(K, V)] = {
+    getMap.map(_.iterator).getOrElse(Iterator.empty)
+  }
+
+  override def keys(): Iterator[K] = {
+    getMap.map(_.keys.iterator).getOrElse(Iterator.empty)
+  }
+
+  override def values(): Iterator[V] = {
+    getMap.map(_.values.iterator).getOrElse(Iterator.empty)
+  }
+
+  override def removeKey(key: K): Unit = {
+    getMap.foreach(_.remove(key))
+  }
+
+  override def clear(): Unit = {
+    keyToStateValue.remove(ImplicitGroupingKeyTracker.getImplicitKeyOption.get)
+  }
+}
+
+/** In-memory timers. */
+class InMemoryTimers {
+  private val keyToTimers = mutable.Map[Any, mutable.TreeSet[Long]]()
+
+  def registerTimer(expiryTimestampMs: Long): Unit = {
+    val groupingKey = ImplicitGroupingKeyTracker.getImplicitKeyOption.get
+    if (!keyToTimers.contains(groupingKey)) {
+      keyToTimers.put(groupingKey, mutable.TreeSet[Long]())
+    }
+    keyToTimers(groupingKey).add(expiryTimestampMs)
+  }
+
+  def deleteTimer(expiryTimestampMs: Long): Unit = {
+    val groupingKey = ImplicitGroupingKeyTracker.getImplicitKeyOption.get
+    if (keyToTimers.contains(groupingKey)) {
+      keyToTimers(groupingKey).remove(expiryTimestampMs)
+      if (keyToTimers(groupingKey).isEmpty) {
+        keyToTimers.remove(groupingKey)
+      }
+    }
+  }
+
+  def listTimers(): Iterator[Long] = {
+    val groupingKey = ImplicitGroupingKeyTracker.getImplicitKeyOption.get
+    keyToTimers.get(groupingKey) match {
+      case Some(timers) => timers.iterator
+      case None => Iterator.empty
+    }
+  }
+
+  def getAllKeysWithTimers[K](): Iterator[K] = {
+    keyToTimers.keys.iterator.map(_.asInstanceOf[K])
+  }
+}
+
+/**
+ * In-memory implementation of StatefulProcessorHandle.

Review Comment:
   can we add some comments to explain how this is implemented internally



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to