Yohahaha commented on code in PR #2548: URL: https://github.com/apache/fluss/pull/2548#discussion_r2776901940
########## fluss-spark/fluss-spark-common/src/main/scala/org/apache/fluss/spark/read/FlussMicroBatchStream.scala: ########## @@ -0,0 +1,347 @@ +/* + * 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.fluss.spark.read + +import org.apache.fluss.client.{Connection, ConnectionFactory} +import org.apache.fluss.client.admin.Admin +import org.apache.fluss.client.initializer.{BucketOffsetsRetrieverImpl, OffsetsInitializer} +import org.apache.fluss.config.Configuration +import org.apache.fluss.metadata.{PartitionInfo, TableBucket, TableInfo, TablePath} +import org.apache.fluss.utils.json.TableBucketOffsets + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.connector.read.{InputPartition, PartitionReaderFactory} +import org.apache.spark.sql.connector.read.streaming._ +import org.apache.spark.sql.types.StructType +import org.apache.spark.sql.util.CaseInsensitiveStringMap + +import java.util +import java.util.Optional + +import scala.collection.JavaConverters._ + +case class FlussSourceOffset(tableBucketOffsets: TableBucketOffsets) extends Offset { + override val json: String = new String(tableBucketOffsets.toJsonBytes, "utf-8") +} + +abstract class FlussMicroBatchStream( + val tablePath: TablePath, + tableInfo: TableInfo, + readSchema: StructType, + options: CaseInsensitiveStringMap, + flussConfig: Configuration, + checkpointLocation: String) + extends SupportsTriggerAvailableNow + with ReportsSourceMetrics + with MicroBatchStream + with Logging + with AutoCloseable { + + lazy val conn: Connection = ConnectionFactory.createConnection(flussConfig) + + lazy val admin: Admin = conn.getAdmin + + lazy val bucketOffsetsRetriever: BucketOffsetsRetrieverImpl = + new BucketOffsetsRetrieverImpl(admin, tableInfo.getTablePath) + + lazy val partitionInfos: util.List[PartitionInfo] = admin.listPartitionInfos(tablePath).get() + + private var allDataForTriggerAvailableNow: Option[TableBucketOffsets] = None + + val startOffsetsInitializer: OffsetsInitializer = + FlussOffsetInitializers.startOffsetsInitializer(options, flussConfig) + + val stoppingOffsetsInitializer: OffsetsInitializer = + FlussOffsetInitializers.stoppingOffsetsInitializer(false, options, flussConfig) + + protected def projection: Array[Int] = { + val columnNameToIndex = tableInfo.getSchema.getColumnNames.asScala.zipWithIndex.toMap + readSchema.fields.map { + field => + columnNameToIndex.getOrElse( + field.name, + throw new IllegalArgumentException(s"Invalid field name: ${field.name}")) + } + } + + override def close(): Unit = { + if (admin != null) { + admin.close() + } + if (conn != null) { + conn.close() + } + } + + override def latestOffset(): Offset = { + throw new UnsupportedOperationException( + "latestOffset(Offset, ReadLimit) should be called instead of this method") + } + + override def getDefaultReadLimit: ReadLimit = { + ReadLimit.allAvailable() + } + + override def initialOffset(): Offset = { + val initialTableBucketOffsets = getOrCreateInitialPartitionOffsets() + FlussSourceOffset(initialTableBucketOffsets) + } + + override def latestOffset(start: Offset, readLimit: ReadLimit): Offset = { + if (!readLimit.isInstanceOf[ReadAllAvailable]) { + throw new UnsupportedOperationException(s"Only ReadAllAvailable is supported, but $readLimit") + } + + val latestTableBucketOffsets = if (allDataForTriggerAvailableNow.isDefined) { + allDataForTriggerAvailableNow.get + } else { + fetchLatestOffsets().get + } + FlussSourceOffset(latestTableBucketOffsets) + } + + override def prepareForTriggerAvailableNow(): Unit = { + allDataForTriggerAvailableNow = fetchLatestOffsets() + } + + private def fetchLatestOffsets(): Option[TableBucketOffsets] = { + val buckets = (0 until tableInfo.getNumBuckets).toSeq + val offsetsInitializer = OffsetsInitializer.latest() + if (tableInfo.isPartitioned) { + val partitionOffsets = partitionInfos.asScala.map( + partitionInfo => + FlussMicroBatchStream.getLatestOffsets( + tableInfo, + offsetsInitializer, + bucketOffsetsRetriever, + buckets, + Some(partitionInfo))) + val mergedOffsets = partitionOffsets + .map(_.getOffsets) + .reduce((l, r) => (l.asScala ++ r.asScala).asJava) + Some(new TableBucketOffsets(tableInfo.getTableId, mergedOffsets)) + } else { + Some( + FlussMicroBatchStream + .getLatestOffsets(tableInfo, offsetsInitializer, bucketOffsetsRetriever, buckets, None)) + } + } + + // No need to notify fluss server + override def commit(end: Offset): Unit = {} + + override def stop(): Unit = close() + + override def deserializeOffset(json: String): Offset = { + FlussSourceOffset(TableBucketOffsets.fromJsonBytes(json.getBytes("utf-8"))) + } + + override def metrics(latestConsumedOffset: Optional[Offset]): util.Map[String, String] = { + // TODO add metrics + Map.empty[String, String].asJava + } + + private def getOrCreateInitialPartitionOffsets(): TableBucketOffsets = { + // TODO load from checkpoint dir Review Comment: done, thank you! -- 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]
