<commit_before>/*
 * 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.beam.runners.spark.structuredstreaming.translation.batch;

import static com.google.common.base.Preconditions.checkArgument;
import static scala.collection.JavaConversions.asScalaBuffer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.beam.runners.core.construction.PipelineOptionsSerializationUtils;
import org.apache.beam.runners.core.construction.SerializablePipelineOptions;
import org.apache.beam.runners.core.serialization.Base64Serializer;
import org.apache.beam.runners.spark.structuredstreaming.SparkPipelineOptions;
import org.apache.beam.sdk.io.BoundedSource;
import org.apache.beam.sdk.io.BoundedSource.BoundedReader;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.ContinuousReadSupport;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
import org.apache.spark.sql.sources.v2.DataSourceV2;
import org.apache.spark.sql.sources.v2.ReadSupport;
import org.apache.spark.sql.sources.v2.reader.DataSourceReader;
import org.apache.spark.sql.sources.v2.reader.InputPartition;
import org.apache.spark.sql.sources.v2.reader.InputPartitionReader;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.Metadata;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;

/**
 * This is a spark structured streaming {@link DataSourceV2} implementation. As Continuous streaming
 * is tagged experimental in spark, this class does no implement {@link ContinuousReadSupport}.
 */
public class DatasetSourceBatch implements DataSourceV2, ReadSupport {

  static final String BEAM_SOURCE_OPTION = "beam-source";
  static final String DEFAULT_PARALLELISM = "default-parallelism";
  static final String PIPELINE_OPTIONS = "pipeline-options";

  public DatasetSourceBatch() {
  }

  @SuppressWarnings("unchecked")
  @Override
  public DataSourceReader createReader(DataSourceOptions options) {
    return new DatasetReader<>(options);
  }

  /** This class is mapped to Beam {@link BoundedSource}. */
  private static class DatasetReader<T> implements DataSourceReader, Serializable {

    private int numPartitions;
    private BoundedSource<T> source;
    private SerializablePipelineOptions serializablePipelineOptions;

    private DatasetReader(DataSourceOptions options) {
      if (!options.get(BEAM_SOURCE_OPTION).isPresent()){
        throw new RuntimeException("Beam source was not set in DataSource options");
      }
      this.source = Base64Serializer
          .deserializeUnchecked(options.get(BEAM_SOURCE_OPTION).get(), BoundedSource.class);

      if (!options.get(DEFAULT_PARALLELISM).isPresent()){
        throw new RuntimeException("Spark default parallelism was not set in DataSource options");
      }
      this.numPartitions = Integer.parseInt(options.get(DEFAULT_PARALLELISM).get());
      checkArgument(numPartitions > 0, "Number of partitions must be greater than zero.");

      if (!options.get(PIPELINE_OPTIONS).isPresent()){
        throw new RuntimeException("Beam pipelineOptions were not set in DataSource options");
      }
      SparkPipelineOptions sparkPipelineOptions = PipelineOptionsSerializationUtils
          .deserializeFromJson(options.get(PIPELINE_OPTIONS).get()).as(SparkPipelineOptions.class);
      this.serializablePipelineOptions = new SerializablePipelineOptions(sparkPipelineOptions);
    }

    @Override
    public StructType readSchema() {
      // TODO: find a way to extend schema with a WindowedValue schema
      StructField[] array = new StructField[1];
      StructField binaryStructField = StructField
          .apply("binaryStructField", DataTypes.BinaryType, true, Metadata.empty());
      array[0] = binaryStructField;
      return new StructType(array);
    }

    @Override
    public List<InputPartition<InternalRow>> planInputPartitions() {<commit_msg>[BEAM-8470] Comment schema choices<commit_after>/*
 * 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.beam.runners.spark.structuredstreaming.translation.batch;

import static com.google.common.base.Preconditions.checkArgument;
import static scala.collection.JavaConversions.asScalaBuffer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.beam.runners.core.construction.PipelineOptionsSerializationUtils;
import org.apache.beam.runners.core.construction.SerializablePipelineOptions;
import org.apache.beam.runners.core.serialization.Base64Serializer;
import org.apache.beam.runners.spark.structuredstreaming.SparkPipelineOptions;
import org.apache.beam.sdk.io.BoundedSource;
import org.apache.beam.sdk.io.BoundedSource.BoundedReader;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.ContinuousReadSupport;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
import org.apache.spark.sql.sources.v2.DataSourceV2;
import org.apache.spark.sql.sources.v2.ReadSupport;
import org.apache.spark.sql.sources.v2.reader.DataSourceReader;
import org.apache.spark.sql.sources.v2.reader.InputPartition;
import org.apache.spark.sql.sources.v2.reader.InputPartitionReader;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.Metadata;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;

/**
 * This is a spark structured streaming {@link DataSourceV2} implementation. As Continuous streaming
 * is tagged experimental in spark, this class does no implement {@link ContinuousReadSupport}.
 */
public class DatasetSourceBatch implements DataSourceV2, ReadSupport {

  static final String BEAM_SOURCE_OPTION = "beam-source";
  static final String DEFAULT_PARALLELISM = "default-parallelism";
  static final String PIPELINE_OPTIONS = "pipeline-options";

  public DatasetSourceBatch() {
  }

  @SuppressWarnings("unchecked")
  @Override
  public DataSourceReader createReader(DataSourceOptions options) {
    return new DatasetReader<>(options);
  }

  /** This class is mapped to Beam {@link BoundedSource}. */
  private static class DatasetReader<T> implements DataSourceReader, Serializable {

    private int numPartitions;
    private BoundedSource<T> source;
    private SerializablePipelineOptions serializablePipelineOptions;

    private DatasetReader(DataSourceOptions options) {
      if (!options.get(BEAM_SOURCE_OPTION).isPresent()){
        throw new RuntimeException("Beam source was not set in DataSource options");
      }
      this.source = Base64Serializer
          .deserializeUnchecked(options.get(BEAM_SOURCE_OPTION).get(), BoundedSource.class);

      if (!options.get(DEFAULT_PARALLELISM).isPresent()){
        throw new RuntimeException("Spark default parallelism was not set in DataSource options");
      }
      this.numPartitions = Integer.parseInt(options.get(DEFAULT_PARALLELISM).get());
      checkArgument(numPartitions > 0, "Number of partitions must be greater than zero.");

      if (!options.get(PIPELINE_OPTIONS).isPresent()){
        throw new RuntimeException("Beam pipelineOptions were not set in DataSource options");
      }
      SparkPipelineOptions sparkPipelineOptions = PipelineOptionsSerializationUtils
          .deserializeFromJson(options.get(PIPELINE_OPTIONS).get()).as(SparkPipelineOptions.class);
      this.serializablePipelineOptions = new SerializablePipelineOptions(sparkPipelineOptions);
    }

    @Override
    public StructType readSchema() {
      // TODO: find a way to extend schema with a WindowedValue schema
      // we use a binary schema for now because:
        // using a empty schema raises a indexOutOfBoundsException
        // using a NullType schema stores null in the elements
      StructField[] array = new StructField[1];
      StructField binaryStructField = StructField
          .apply("binaryStructField", DataTypes.BinaryType, true, Metadata.empty());
      array[0] = binaryStructField;
      return new StructType(array);
    }

    @Override
    public List<InputPartition<InternalRow>> planInputPartitions() {
{'fraction_non_alphanumeric': 0.08872421389945924, 'fraction_numerical': 0.004606449028640096, 'mean_word_length': 4.706857142857143, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '540716', 'n_tokens_mistral': 2735, 'n_tokens_neox': 2655, 'n_words': 725}