diff --git a/ckpts/universal/global_step80/zero/21.attention.dense.weight/fp32.pt b/ckpts/universal/global_step80/zero/21.attention.dense.weight/fp32.pt new file mode 100644 index 0000000000000000000000000000000000000000..26de4f30474ac3919dab6409906bf5531171ccc8 --- /dev/null +++ b/ckpts/universal/global_step80/zero/21.attention.dense.weight/fp32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:27f5af4eed6bfb1246378654bfd1efb455cf5fe6fe2fe2bc137f9b9ded569a45 +size 16778317 diff --git a/ckpts/universal/global_step80/zero/23.attention.query_key_value.weight/exp_avg_sq.pt b/ckpts/universal/global_step80/zero/23.attention.query_key_value.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..a378db06840e7256670a3ac3994ccd2d8ae6f1c8 --- /dev/null +++ b/ckpts/universal/global_step80/zero/23.attention.query_key_value.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e802d89a5be62321a3558a50151f10ca716555914e04d4b31e001db4ec0ae311 +size 50332843 diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/adapters/orc/adapter.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/adapters/orc/adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..4ffff81f355f1ddcdc19516746c61b8021477de4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/adapters/orc/adapter.h @@ -0,0 +1,323 @@ +// 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. + +#pragma once + +#include +#include +#include + +#include "arrow/adapters/orc/options.h" +#include "arrow/io/interfaces.h" +#include "arrow/memory_pool.h" +#include "arrow/record_batch.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace adapters { +namespace orc { + +/// \brief Information about an ORC stripe +struct StripeInformation { + /// \brief Offset of the stripe from the start of the file, in bytes + int64_t offset; + /// \brief Length of the stripe, in bytes + int64_t length; + /// \brief Number of rows in the stripe + int64_t num_rows; + /// \brief Index of the first row of the stripe + int64_t first_row_id; +}; + +/// \class ORCFileReader +/// \brief Read an Arrow Table or RecordBatch from an ORC file. +class ARROW_EXPORT ORCFileReader { + public: + ~ORCFileReader(); + + /// \brief Creates a new ORC reader + /// + /// \param[in] file the data source + /// \param[in] pool a MemoryPool to use for buffer allocations + /// \return the returned reader object + static Result> Open( + const std::shared_ptr& file, MemoryPool* pool); + + /// \brief Return the schema read from the ORC file + /// + /// \return the returned Schema object + Result> ReadSchema(); + + /// \brief Read the file as a Table + /// + /// The table will be composed of one record batch per stripe. + /// + /// \return the returned Table + Result> Read(); + + /// \brief Read the file as a Table + /// + /// The table will be composed of one record batch per stripe. + /// + /// \param[in] schema the Table schema + /// \return the returned Table + Result> Read(const std::shared_ptr& schema); + + /// \brief Read the file as a Table + /// + /// The table will be composed of one record batch per stripe. + /// + /// \param[in] include_indices the selected field indices to read + /// \return the returned Table + Result> Read(const std::vector& include_indices); + + /// \brief Read the file as a Table + /// + /// The table will be composed of one record batch per stripe. + /// + /// \param[in] include_names the selected field names to read + /// \return the returned Table + Result> Read(const std::vector& include_names); + + /// \brief Read the file as a Table + /// + /// The table will be composed of one record batch per stripe. + /// + /// \param[in] schema the Table schema + /// \param[in] include_indices the selected field indices to read + /// \return the returned Table + Result> Read(const std::shared_ptr& schema, + const std::vector& include_indices); + + /// \brief Read a single stripe as a RecordBatch + /// + /// \param[in] stripe the stripe index + /// \return the returned RecordBatch + Result> ReadStripe(int64_t stripe); + + /// \brief Read a single stripe as a RecordBatch + /// + /// \param[in] stripe the stripe index + /// \param[in] include_indices the selected field indices to read + /// \return the returned RecordBatch + Result> ReadStripe( + int64_t stripe, const std::vector& include_indices); + + /// \brief Read a single stripe as a RecordBatch + /// + /// \param[in] stripe the stripe index + /// \param[in] include_names the selected field names to read + /// \return the returned RecordBatch + Result> ReadStripe( + int64_t stripe, const std::vector& include_names); + + /// \brief Seek to designated row. Invoke NextStripeReader() after seek + /// will return stripe reader starting from designated row. + /// + /// \param[in] row_number the rows number to seek + Status Seek(int64_t row_number); + + /// \brief Get a stripe level record batch iterator. + /// + /// Each record batch will have up to `batch_size` rows. + /// NextStripeReader serves as a fine-grained alternative to ReadStripe + /// which may cause OOM issues by loading the whole stripe into memory. + /// + /// Note this will only read rows for the current stripe, not the entire + /// file. + /// + /// \param[in] batch_size the maximum number of rows in each record batch + /// \return the returned stripe reader + Result> NextStripeReader(int64_t batch_size); + + /// \brief Get a stripe level record batch iterator. + /// + /// Each record batch will have up to `batch_size` rows. + /// NextStripeReader serves as a fine-grained alternative to ReadStripe + /// which may cause OOM issues by loading the whole stripe into memory. + /// + /// Note this will only read rows for the current stripe, not the entire + /// file. + /// + /// \param[in] batch_size the maximum number of rows in each record batch + /// \param[in] include_indices the selected field indices to read + /// \return the stripe reader + Result> NextStripeReader( + int64_t batch_size, const std::vector& include_indices); + + /// \brief Get a record batch iterator for the entire file. + /// + /// Each record batch will have up to `batch_size` rows. + /// + /// \param[in] batch_size the maximum number of rows in each record batch + /// \param[in] include_names the selected field names to read, if not empty + /// (otherwise all fields are read) + /// \return the record batch iterator + Result> GetRecordBatchReader( + int64_t batch_size, const std::vector& include_names); + + /// \brief The number of stripes in the file + int64_t NumberOfStripes(); + + /// \brief The number of rows in the file + int64_t NumberOfRows(); + + /// \brief StripeInformation for each stripe. + StripeInformation GetStripeInformation(int64_t stripe); + + /// \brief Get the format version of the file. + /// Currently known values are 0.11 and 0.12. + /// + /// \return The FileVersion of the ORC file. + FileVersion GetFileVersion(); + + /// \brief Get the software instance and version that wrote this file. + /// + /// \return a user-facing string that specifies the software version + std::string GetSoftwareVersion(); + + /// \brief Get the compression kind of the file. + /// + /// \return The kind of compression in the ORC file. + Result GetCompression(); + + /// \brief Get the buffer size for the compression. + /// + /// \return Number of bytes to buffer for the compression codec. + int64_t GetCompressionSize(); + + /// \brief Get the number of rows per an entry in the row index. + /// \return the number of rows per an entry in the row index or 0 if there + /// is no row index. + int64_t GetRowIndexStride(); + + /// \brief Get ID of writer that generated the file. + /// + /// \return UNKNOWN_WRITER if the writer ID is undefined + WriterId GetWriterId(); + + /// \brief Get the writer id value when getWriterId() returns an unknown writer. + /// + /// \return the integer value of the writer ID. + int32_t GetWriterIdValue(); + + /// \brief Get the version of the writer. + /// + /// \return the version of the writer. + + WriterVersion GetWriterVersion(); + + /// \brief Get the number of stripe statistics in the file. + /// + /// \return the number of stripe statistics + int64_t GetNumberOfStripeStatistics(); + + /// \brief Get the length of the data stripes in the file. + /// + /// \return return the number of bytes in stripes + int64_t GetContentLength(); + + /// \brief Get the length of the file stripe statistics. + /// + /// \return the number of compressed bytes in the file stripe statistics + int64_t GetStripeStatisticsLength(); + + /// \brief Get the length of the file footer. + /// + /// \return the number of compressed bytes in the file footer + int64_t GetFileFooterLength(); + + /// \brief Get the length of the file postscript. + /// + /// \return the number of bytes in the file postscript + int64_t GetFilePostscriptLength(); + + /// \brief Get the total length of the file. + /// + /// \return the number of bytes in the file + int64_t GetFileLength(); + + /// \brief Get the serialized file tail. + /// Useful if another reader of the same file wants to avoid re-reading + /// the file tail. See ReadOptions.SetSerializedFileTail(). + /// + /// \return a string of bytes with the file tail + std::string GetSerializedFileTail(); + + /// \brief Return the metadata read from the ORC file + /// + /// \return A KeyValueMetadata object containing the ORC metadata + Result> ReadMetadata(); + + private: + class Impl; + std::unique_ptr impl_; + ORCFileReader(); +}; + +/// \class ORCFileWriter +/// \brief Write an Arrow Table or RecordBatch to an ORC file. +class ARROW_EXPORT ORCFileWriter { + public: + ~ORCFileWriter(); + /// \brief Creates a new ORC writer. + /// + /// \param[in] output_stream a pointer to the io::OutputStream to write into + /// \param[in] write_options the ORC writer options for Arrow + /// \return the returned writer object + static Result> Open( + io::OutputStream* output_stream, + const WriteOptions& write_options = WriteOptions()); + + /// \brief Write a table. This can be called multiple times. + /// + /// Tables passed in subsequent calls must match the schema of the table that was + /// written first. + /// + /// \param[in] table the Arrow table from which data is extracted. + /// \return Status + Status Write(const Table& table); + + /// \brief Write a RecordBatch. This can be called multiple times. + /// + /// RecordBatches passed in subsequent calls must match the schema of the + /// RecordBatch that was written first. + /// + /// \param[in] record_batch the Arrow RecordBatch from which data is extracted. + /// \return Status + Status Write(const RecordBatch& record_batch); + + /// \brief Close an ORC writer (orc::Writer) + /// + /// \return Status + Status Close(); + + private: + class Impl; + std::unique_ptr impl_; + + private: + ORCFileWriter(); +}; + +} // namespace orc +} // namespace adapters +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/adapters/orc/options.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/adapters/orc/options.h new file mode 100644 index 0000000000000000000000000000000000000000..3a300da678db98c24949203be7ab471a57502640 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/adapters/orc/options.h @@ -0,0 +1,120 @@ +// 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. + +#pragma once + +#include + +#include "arrow/io/interfaces.h" +#include "arrow/status.h" +#include "arrow/util/type_fwd.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +namespace adapters { + +namespace orc { + +enum class WriterId : int32_t { + kOrcJava = 0, + kOrcCpp = 1, + kPresto = 2, + kScritchleyGo = 3, + kTrino = 4, + kUnknown = INT32_MAX +}; + +enum class WriterVersion : int32_t { + kOriginal = 0, + kHive8732 = 1, + kHive4243 = 2, + kHive12055 = 3, + kHive13083 = 4, + kOrc101 = 5, + kOrc135 = 6, + kOrc517 = 7, + kOrc203 = 8, + kOrc14 = 9, + kMax = INT32_MAX +}; + +enum class CompressionStrategy : int32_t { kSpeed = 0, kCompression }; + +class ARROW_EXPORT FileVersion { + private: + int32_t major_version_; + int32_t minor_version_; + + public: + static const FileVersion& v_0_11(); + static const FileVersion& v_0_12(); + + FileVersion(int32_t major, int32_t minor) + : major_version_(major), minor_version_(minor) {} + + /** + * Get major version + */ + int32_t major_version() const { return this->major_version_; } + + /** + * Get minor version + */ + int32_t minor_version() const { return this->minor_version_; } + + bool operator==(const FileVersion& right) const { + return this->major_version() == right.major_version() && + this->minor_version() == right.minor_version(); + } + + bool operator!=(const FileVersion& right) const { return !(*this == right); } + + std::string ToString() const; +}; + +/// Options for the ORC Writer +struct ARROW_EXPORT WriteOptions { + /// Number of rows the ORC writer writes at a time, default 1024 + int64_t batch_size = 1024; + /// Which ORC file version to use, default FileVersion(0, 12) + FileVersion file_version = FileVersion(0, 12); + /// Size of each ORC stripe in bytes, default 64 MiB + int64_t stripe_size = 64 * 1024 * 1024; + /// The compression codec of the ORC file, there is no compression by default + Compression::type compression = Compression::UNCOMPRESSED; + /// The size of each compression block in bytes, default 64 KiB + int64_t compression_block_size = 64 * 1024; + /// The compression strategy i.e. speed vs size reduction, default + /// CompressionStrategy::kSpeed + CompressionStrategy compression_strategy = CompressionStrategy::kSpeed; + /// The number of rows per an entry in the row index, default 10000 + int64_t row_index_stride = 10000; + /// The padding tolerance, default 0.0 + double padding_tolerance = 0.0; + /// The dictionary key size threshold. 0 to disable dictionary encoding. + /// 1 to always enable dictionary encoding, default 0.0 + double dictionary_key_size_threshold = 0.0; + /// The array of columns that use the bloom filter, default empty + std::vector bloom_filter_columns; + /// The upper limit of the false-positive rate of the bloom filter, default 0.05 + double bloom_filter_fpp = 0.05; +}; + +} // namespace orc +} // namespace adapters +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/adapters/tensorflow/convert.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/adapters/tensorflow/convert.h new file mode 100644 index 0000000000000000000000000000000000000000..9d093eddf6b598150ddb55da0e84699a5b7ef4b8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/adapters/tensorflow/convert.h @@ -0,0 +1,128 @@ +// 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. + +#pragma once + +#include + +#include "tensorflow/core/framework/op.h" + +#include "arrow/type.h" + +// These utilities are supposed to be included in TensorFlow operators +// that need to be compiled separately from Arrow because of ABI issues. +// They therefore need to be header-only. + +namespace arrow { + +namespace adapters { + +namespace tensorflow { + +Status GetArrowType(::tensorflow::DataType dtype, std::shared_ptr* out) { + switch (dtype) { + case ::tensorflow::DT_BOOL: + *out = arrow::boolean(); + break; + case ::tensorflow::DT_FLOAT: + *out = arrow::float32(); + break; + case ::tensorflow::DT_DOUBLE: + *out = arrow::float64(); + break; + case ::tensorflow::DT_HALF: + *out = arrow::float16(); + break; + case ::tensorflow::DT_INT8: + *out = arrow::int8(); + break; + case ::tensorflow::DT_INT16: + *out = arrow::int16(); + break; + case ::tensorflow::DT_INT32: + *out = arrow::int32(); + break; + case ::tensorflow::DT_INT64: + *out = arrow::int64(); + break; + case ::tensorflow::DT_UINT8: + *out = arrow::uint8(); + break; + case ::tensorflow::DT_UINT16: + *out = arrow::uint16(); + break; + case ::tensorflow::DT_UINT32: + *out = arrow::uint32(); + break; + case ::tensorflow::DT_UINT64: + *out = arrow::uint64(); + break; + default: + return Status::TypeError("TensorFlow data type is not supported"); + } + return Status::OK(); +} + +Status GetTensorFlowType(std::shared_ptr dtype, ::tensorflow::DataType* out) { + switch (dtype->id()) { + case Type::BOOL: + *out = ::tensorflow::DT_BOOL; + break; + case Type::UINT8: + *out = ::tensorflow::DT_UINT8; + break; + case Type::INT8: + *out = ::tensorflow::DT_INT8; + break; + case Type::UINT16: + *out = ::tensorflow::DT_UINT16; + break; + case Type::INT16: + *out = ::tensorflow::DT_INT16; + break; + case Type::UINT32: + *out = ::tensorflow::DT_UINT32; + break; + case Type::INT32: + *out = ::tensorflow::DT_INT32; + break; + case Type::UINT64: + *out = ::tensorflow::DT_UINT64; + break; + case Type::INT64: + *out = ::tensorflow::DT_INT64; + break; + case Type::HALF_FLOAT: + *out = ::tensorflow::DT_HALF; + break; + case Type::FLOAT: + *out = ::tensorflow::DT_FLOAT; + break; + case Type::DOUBLE: + *out = ::tensorflow::DT_DOUBLE; + break; + default: + return Status::TypeError("Arrow data type is not supported"); + } + return arrow::Status::OK(); +} + +} // namespace tensorflow + +} // namespace adapters + +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/client.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/client.h new file mode 100644 index 0000000000000000000000000000000000000000..330fa8bad730db919cb14dfba187472d4a464546 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/client.h @@ -0,0 +1,436 @@ +// 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. + +/// \brief Implementation of Flight RPC client. API should be +/// considered experimental for now + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/ipc/options.h" +#include "arrow/ipc/reader.h" +#include "arrow/ipc/writer.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/cancel.h" + +#include "arrow/flight/type_fwd.h" +#include "arrow/flight/types.h" // IWYU pragma: keep +#include "arrow/flight/visibility.h" + +namespace arrow { + +class RecordBatch; +class Schema; + +namespace flight { + +/// \brief A duration type for Flight call timeouts. +typedef std::chrono::duration TimeoutDuration; + +/// \brief Hints to the underlying RPC layer for Arrow Flight calls. +class ARROW_FLIGHT_EXPORT FlightCallOptions { + public: + /// Create a default set of call options. + FlightCallOptions(); + + /// \brief An optional timeout for this call. Negative durations + /// mean an implementation-defined default behavior will be used + /// instead. This is the default value. + TimeoutDuration timeout; + + /// \brief IPC reader options, if applicable for the call. + ipc::IpcReadOptions read_options; + + /// \brief IPC writer options, if applicable for the call. + ipc::IpcWriteOptions write_options; + + /// \brief Headers for client to add to context. + std::vector> headers; + + /// \brief A token to enable interactive user cancellation of long-running requests. + StopToken stop_token; + + /// \brief An optional memory manager to control where to allocate incoming data. + std::shared_ptr memory_manager; +}; + +/// \brief Indicate that the client attempted to write a message +/// larger than the soft limit set via write_size_limit_bytes. +class ARROW_FLIGHT_EXPORT FlightWriteSizeStatusDetail : public arrow::StatusDetail { + public: + explicit FlightWriteSizeStatusDetail(int64_t limit, int64_t actual) + : limit_(limit), actual_(actual) {} + const char* type_id() const override; + std::string ToString() const override; + int64_t limit() const { return limit_; } + int64_t actual() const { return actual_; } + + /// \brief Extract this status detail from a status, or return + /// nullptr if the status doesn't contain this status detail. + static std::shared_ptr UnwrapStatus( + const arrow::Status& status); + + private: + int64_t limit_; + int64_t actual_; +}; + +struct ARROW_FLIGHT_EXPORT FlightClientOptions { + /// \brief Root certificates to use for validating server + /// certificates. + std::string tls_root_certs; + /// \brief Override the hostname checked by TLS. Use with caution. + std::string override_hostname; + /// \brief The client certificate to use if using Mutual TLS + std::string cert_chain; + /// \brief The private key associated with the client certificate for Mutual TLS + std::string private_key; + /// \brief A list of client middleware to apply. + std::vector> middleware; + /// \brief A soft limit on the number of bytes to write in a single + /// batch when sending Arrow data to a server. + /// + /// Used to help limit server memory consumption. Only enabled if + /// positive. When enabled, FlightStreamWriter.Write* may yield a + /// IOError with error detail FlightWriteSizeStatusDetail. + int64_t write_size_limit_bytes = 0; + + /// \brief Generic connection options, passed to the underlying + /// transport; interpretation is implementation-dependent. + std::vector>> generic_options; + + /// \brief Use TLS without validating the server certificate. Use with caution. + bool disable_server_verification = false; + + /// \brief Get default options. + static FlightClientOptions Defaults(); +}; + +/// \brief A RecordBatchReader exposing Flight metadata and cancel +/// operations. +class ARROW_FLIGHT_EXPORT FlightStreamReader : public MetadataRecordBatchReader { + public: + /// \brief Try to cancel the call. + virtual void Cancel() = 0; + + using MetadataRecordBatchReader::ToRecordBatches; + /// \brief Consume entire stream as a vector of record batches + virtual arrow::Result>> ToRecordBatches( + const StopToken& stop_token) = 0; + + using MetadataRecordBatchReader::ToTable; + /// \brief Consume entire stream as a Table + arrow::Result> ToTable(const StopToken& stop_token); +}; + +// Silence warning +// "non dll-interface class RecordBatchReader used as base for dll-interface class" +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4275) +#endif + +/// \brief A RecordBatchWriter that also allows sending +/// application-defined metadata via the Flight protocol. +class ARROW_FLIGHT_EXPORT FlightStreamWriter : public MetadataRecordBatchWriter { + public: + /// \brief Indicate that the application is done writing to this stream. + /// + /// The application may not write to this stream after calling + /// this. This differs from closing the stream because this writer + /// may represent only one half of a readable and writable stream. + virtual Status DoneWriting() = 0; +}; + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +/// \brief A reader for application-specific metadata sent back to the +/// client during an upload. +class ARROW_FLIGHT_EXPORT FlightMetadataReader { + public: + virtual ~FlightMetadataReader(); + /// \brief Read a message from the server. + virtual Status ReadMetadata(std::shared_ptr* out) = 0; +}; + +/// \brief Client class for Arrow Flight RPC services. +/// API experimental for now +class ARROW_FLIGHT_EXPORT FlightClient { + public: + ~FlightClient(); + + /// \brief Connect to an unauthenticated flight service + /// \param[in] location the URI + /// \return Arrow result with the created FlightClient, OK status may not indicate that + /// the connection was successful + static arrow::Result> Connect(const Location& location); + + /// \brief Connect to an unauthenticated flight service + /// \param[in] location the URI + /// \param[in] options Other options for setting up the client + /// \return Arrow result with the created FlightClient, OK status may not indicate that + /// the connection was successful + static arrow::Result> Connect( + const Location& location, const FlightClientOptions& options); + + /// \brief Authenticate to the server using the given handler. + /// \param[in] options Per-RPC options + /// \param[in] auth_handler The authentication mechanism to use + /// \return Status OK if the client authenticated successfully + Status Authenticate(const FlightCallOptions& options, + std::unique_ptr auth_handler); + + /// \brief Authenticate to the server using basic HTTP style authentication. + /// \param[in] options Per-RPC options + /// \param[in] username Username to use + /// \param[in] password Password to use + /// \return Arrow result with bearer token and status OK if client authenticated + /// successfully + arrow::Result> AuthenticateBasicToken( + const FlightCallOptions& options, const std::string& username, + const std::string& password); + + /// \brief Perform the indicated action, returning an iterator to the stream + /// of results, if any + /// \param[in] options Per-RPC options + /// \param[in] action the action to be performed + /// \return Arrow result with an iterator object for reading the returned results + arrow::Result> DoAction(const FlightCallOptions& options, + const Action& action); + arrow::Result> DoAction(const Action& action) { + return DoAction({}, action); + } + + /// \brief Perform the CancelFlightInfo action, returning a + /// CancelFlightInfoResult + /// + /// \param[in] options Per-RPC options + /// \param[in] request The CancelFlightInfoRequest + /// \return Arrow result with a CancelFlightInfoResult + arrow::Result CancelFlightInfo( + const FlightCallOptions& options, const CancelFlightInfoRequest& request); + arrow::Result CancelFlightInfo( + const CancelFlightInfoRequest& request) { + return CancelFlightInfo({}, request); + } + + /// \brief Perform the RenewFlightEndpoint action, returning a renewed + /// FlightEndpoint + /// + /// \param[in] options Per-RPC options + /// \param[in] request The RenewFlightEndpointRequest + /// \return Arrow result with a renewed FlightEndpoint + arrow::Result RenewFlightEndpoint( + const FlightCallOptions& options, const RenewFlightEndpointRequest& request); + arrow::Result RenewFlightEndpoint( + const RenewFlightEndpointRequest& request) { + return RenewFlightEndpoint({}, request); + } + + /// \brief Retrieve a list of available Action types + /// \param[in] options Per-RPC options + /// \return Arrow result with the available actions + arrow::Result> ListActions(const FlightCallOptions& options); + arrow::Result> ListActions() { + return ListActions(FlightCallOptions()); + } + + /// \brief Request access plan for a single flight, which may be an existing + /// dataset or a command to be executed + /// \param[in] options Per-RPC options + /// \param[in] descriptor the dataset request, whether a named dataset or + /// command + /// \return Arrow result with the FlightInfo describing where to access the dataset + arrow::Result> GetFlightInfo( + const FlightCallOptions& options, const FlightDescriptor& descriptor); + arrow::Result> GetFlightInfo( + const FlightDescriptor& descriptor) { + return GetFlightInfo({}, descriptor); + } + + /// \brief Asynchronous GetFlightInfo. + /// \param[in] options Per-RPC options + /// \param[in] descriptor the dataset request + /// \param[in] listener Callbacks for response and RPC completion + /// + /// This API is EXPERIMENTAL. + void GetFlightInfoAsync(const FlightCallOptions& options, + const FlightDescriptor& descriptor, + std::shared_ptr> listener); + void GetFlightInfoAsync(const FlightDescriptor& descriptor, + std::shared_ptr> listener) { + return GetFlightInfoAsync({}, descriptor, std::move(listener)); + } + + /// \brief Asynchronous GetFlightInfo returning a Future. + /// \param[in] options Per-RPC options + /// \param[in] descriptor the dataset request + /// + /// This API is EXPERIMENTAL. + arrow::Future GetFlightInfoAsync(const FlightCallOptions& options, + const FlightDescriptor& descriptor); + arrow::Future GetFlightInfoAsync(const FlightDescriptor& descriptor) { + return GetFlightInfoAsync({}, descriptor); + } + + /// \brief Request and poll a long running query + /// \param[in] options Per-RPC options + /// \param[in] descriptor the dataset request or a descriptor returned by a + /// prior PollFlightInfo call + /// \return Arrow result with the PollInfo describing the status of + /// the requested query + arrow::Result> PollFlightInfo( + const FlightCallOptions& options, const FlightDescriptor& descriptor); + arrow::Result> PollFlightInfo( + const FlightDescriptor& descriptor) { + return PollFlightInfo({}, descriptor); + } + + /// \brief Request schema for a single flight, which may be an existing + /// dataset or a command to be executed + /// \param[in] options Per-RPC options + /// \param[in] descriptor the dataset request, whether a named dataset or + /// command + /// \return Arrow result with the SchemaResult describing the dataset schema + arrow::Result> GetSchema( + const FlightCallOptions& options, const FlightDescriptor& descriptor); + + arrow::Result> GetSchema( + const FlightDescriptor& descriptor) { + return GetSchema({}, descriptor); + } + + /// \brief List all available flights known to the server + /// \return Arrow result with an iterator that returns a FlightInfo for each flight + arrow::Result> ListFlights(); + + /// \brief List available flights given indicated filter criteria + /// \param[in] options Per-RPC options + /// \param[in] criteria the filter criteria (opaque) + /// \return Arrow result with an iterator that returns a FlightInfo for each flight + arrow::Result> ListFlights( + const FlightCallOptions& options, const Criteria& criteria); + + /// \brief Given a flight ticket and schema, request to be sent the + /// stream. Returns record batch stream reader + /// \param[in] options Per-RPC options + /// \param[in] ticket The flight ticket to use + /// \return Arrow result with the returned RecordBatchReader + arrow::Result> DoGet( + const FlightCallOptions& options, const Ticket& ticket); + arrow::Result> DoGet(const Ticket& ticket) { + return DoGet({}, ticket); + } + + /// \brief DoPut return value + struct DoPutResult { + /// \brief a writer to write record batches to + std::unique_ptr writer; + /// \brief a reader for application metadata from the server + std::unique_ptr reader; + }; + /// \brief Upload data to a Flight described by the given + /// descriptor. The caller must call Close() on the returned stream + /// once they are done writing. + /// + /// The reader and writer are linked; closing the writer will also + /// close the reader. Use \a DoneWriting to only close the write + /// side of the channel. + /// + /// \param[in] options Per-RPC options + /// \param[in] descriptor the descriptor of the stream + /// \param[in] schema the schema for the data to upload + /// \return Arrow result with a DoPutResult struct holding a reader and a writer + arrow::Result DoPut(const FlightCallOptions& options, + const FlightDescriptor& descriptor, + const std::shared_ptr& schema); + + arrow::Result DoPut(const FlightDescriptor& descriptor, + const std::shared_ptr& schema) { + return DoPut({}, descriptor, schema); + } + + struct DoExchangeResult { + std::unique_ptr writer; + std::unique_ptr reader; + }; + arrow::Result DoExchange(const FlightCallOptions& options, + const FlightDescriptor& descriptor); + arrow::Result DoExchange(const FlightDescriptor& descriptor) { + return DoExchange({}, descriptor); + } + + /// \brief Set server session option(s) by name/value. Sessions are generally + /// persisted via HTTP cookies. + /// \param[in] options Per-RPC options + /// \param[in] request The server session options to set + ::arrow::Result SetSessionOptions( + const FlightCallOptions& options, const SetSessionOptionsRequest& request); + + /// \brief Get the current server session options. The session is generally + /// accessed via an HTTP cookie. + /// \param[in] options Per-RPC options + /// \param[in] request The (empty) GetSessionOptions request object. + ::arrow::Result GetSessionOptions( + const FlightCallOptions& options, const GetSessionOptionsRequest& request); + + /// \brief Close/invalidate the current server session. The session is generally + /// accessed via an HTTP cookie. + /// \param[in] options Per-RPC options + /// \param[in] request The (empty) CloseSession request object. + ::arrow::Result CloseSession(const FlightCallOptions& options, + const CloseSessionRequest& request); + + /// \brief Explicitly shut down and clean up the client. + /// + /// For backwards compatibility, this will be implicitly called by + /// the destructor if not already called, but this gives the + /// application no chance to handle errors, so it is recommended to + /// explicitly close the client. + /// + /// \since 8.0.0 + Status Close(); + + /// \brief Whether this client supports asynchronous methods. + bool supports_async() const; + + /// \brief Check whether this client supports asynchronous methods. + /// + /// This is like supports_async(), except that a detailed error message + /// is returned if async support is not available. If async support is + /// available, this function returns successfully. + Status CheckAsyncSupport() const; + + private: + FlightClient(); + Status CheckOpen() const; + std::unique_ptr transport_; + bool closed_; + int64_t write_size_limit_bytes_; +}; + +} // namespace flight +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/client_auth.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/client_auth.h new file mode 100644 index 0000000000000000000000000000000000000000..9dad36aa0948906ebb2447c0030cf117c8549c2c --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/client_auth.h @@ -0,0 +1,62 @@ +// 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. + +#pragma once + +#include + +#include "arrow/flight/visibility.h" +#include "arrow/status.h" + +namespace arrow { + +namespace flight { + +/// \brief A reader for messages from the server during an +/// authentication handshake. +class ARROW_FLIGHT_EXPORT ClientAuthReader { + public: + virtual ~ClientAuthReader() = default; + virtual Status Read(std::string* response) = 0; +}; + +/// \brief A writer for messages to the server during an +/// authentication handshake. +class ARROW_FLIGHT_EXPORT ClientAuthSender { + public: + virtual ~ClientAuthSender() = default; + virtual Status Write(const std::string& token) = 0; +}; + +/// \brief An authentication implementation for a Flight service. +/// Authentication includes both an initial negotiation and a per-call +/// token validation. Implementations may choose to use either or both +/// mechanisms. +class ARROW_FLIGHT_EXPORT ClientAuthHandler { + public: + virtual ~ClientAuthHandler() = default; + /// \brief Authenticate the client on initial connection. The client + /// can send messages to/read responses from the server at any time. + /// \return Status OK if authenticated successfully + virtual Status Authenticate(ClientAuthSender* outgoing, ClientAuthReader* incoming) = 0; + /// \brief Get a per-call token. + /// \param[out] token The token to send to the server. + virtual Status GetToken(std::string* token) = 0; +}; + +} // namespace flight +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/client_tracing_middleware.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/client_tracing_middleware.h new file mode 100644 index 0000000000000000000000000000000000000000..3a8b665ed6c0f0021abedea1917a4b4501157179 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/client_tracing_middleware.h @@ -0,0 +1,34 @@ +// 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. + +// Middleware implementation for propagating OpenTelemetry spans. + +#pragma once + +#include + +#include "arrow/flight/client_middleware.h" + +namespace arrow { +namespace flight { + +/// \brief Returns a ClientMiddlewareFactory that handles sending OpenTelemetry spans. +ARROW_FLIGHT_EXPORT std::shared_ptr +MakeTracingClientMiddlewareFactory(); + +} // namespace flight +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/pch.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/pch.h new file mode 100644 index 0000000000000000000000000000000000000000..fff107fa8fcf4b3871cf48266ac858db33e5f5c2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/pch.h @@ -0,0 +1,26 @@ +// 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. + +// Often-used headers, for precompiling. +// If updating this header, please make sure you check compilation speed +// before checking in. Adding headers which are not used extremely often +// may incur a slowdown, since it makes the precompiled header heavier to load. + +#include "arrow/flight/client.h" +#include "arrow/flight/server.h" +#include "arrow/flight/types.h" +#include "arrow/pch.h" diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/platform.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..8f8db2d2dc8051058516818acbc1a94c8dd11abb --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/platform.h @@ -0,0 +1,31 @@ +// 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. + +// Internal header. Platform-specific definitions for Flight. + +#pragma once + +#ifdef _MSC_VER + +// The protobuf documentation says that C4251 warnings when using the +// library are spurious and suppressed when the build the library and +// compiler, but must be also suppressed in downstream projects +#pragma warning(disable : 4251) + +#endif // _MSC_VER + +#include "arrow/util/config.h" // IWYU pragma: keep diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server_auth.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server_auth.h new file mode 100644 index 0000000000000000000000000000000000000000..93d3352ba2006f71e699b86a669a21f04274994f --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server_auth.h @@ -0,0 +1,125 @@ +// 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. + +/// \brief Server-side APIs to implement authentication for Flight. + +#pragma once + +#include + +#include "arrow/flight/type_fwd.h" +#include "arrow/flight/visibility.h" +#include "arrow/status.h" + +namespace arrow { + +namespace flight { + +/// \brief A reader for messages from the client during an +/// authentication handshake. +class ARROW_FLIGHT_EXPORT ServerAuthReader { + public: + virtual ~ServerAuthReader() = default; + virtual Status Read(std::string* token) = 0; +}; + +/// \brief A writer for messages to the client during an +/// authentication handshake. +class ARROW_FLIGHT_EXPORT ServerAuthSender { + public: + virtual ~ServerAuthSender() = default; + virtual Status Write(const std::string& message) = 0; +}; + +/// \brief An authentication implementation for a Flight service. +/// Authentication includes both an initial negotiation and a per-call +/// token validation. Implementations may choose to use either or both +/// mechanisms. +/// An implementation may need to track some state, e.g. a mapping of +/// client tokens to authenticated identities. +class ARROW_FLIGHT_EXPORT ServerAuthHandler { + public: + virtual ~ServerAuthHandler(); + /// \brief Authenticate the client on initial connection. The server + /// can send and read responses from the client at any time. + /// \param[in] context The call context. + /// \param[in] outgoing The writer for messages to the client. + /// \param[in] incoming The reader for messages from the client. + /// \return Status OK if this authentication is succeeded. + virtual Status Authenticate(const ServerCallContext& context, + ServerAuthSender* outgoing, ServerAuthReader* incoming) { + // TODO: We can make this pure virtual function when we remove + // the deprecated version. + ARROW_SUPPRESS_DEPRECATION_WARNING + return Authenticate(outgoing, incoming); + ARROW_UNSUPPRESS_DEPRECATION_WARNING + } + /// \brief Authenticate the client on initial connection. The server + /// can send and read responses from the client at any time. + /// \param[in] outgoing The writer for messages to the client. + /// \param[in] incoming The reader for messages from the client. + /// \return Status OK if this authentication is succeeded. + /// \deprecated Deprecated in 13.0.0. Implement the Authentication() + /// with ServerCallContext version instead. + ARROW_DEPRECATED("Deprecated in 13.0.0. Use ServerCallContext overload instead.") + virtual Status Authenticate(ServerAuthSender* outgoing, ServerAuthReader* incoming) { + return Status::NotImplemented(typeid(this).name(), + "::Authenticate() isn't implemented"); + } + /// \brief Validate a per-call client token. + /// \param[in] context The call context. + /// \param[in] token The client token. May be the empty string if + /// the client does not provide a token. + /// \param[out] peer_identity The identity of the peer, if this + /// authentication method supports it. + /// \return Status OK if the token is valid, any other status if + /// validation failed + virtual Status IsValid(const ServerCallContext& context, const std::string& token, + std::string* peer_identity) { + // TODO: We can make this pure virtual function when we remove + // the deprecated version. + ARROW_SUPPRESS_DEPRECATION_WARNING + return IsValid(token, peer_identity); + ARROW_UNSUPPRESS_DEPRECATION_WARNING + } + /// \brief Validate a per-call client token. + /// \param[in] token The client token. May be the empty string if + /// the client does not provide a token. + /// \param[out] peer_identity The identity of the peer, if this + /// authentication method supports it. + /// \return Status OK if the token is valid, any other status if + /// validation failed + /// \deprecated Deprecated in 13.0.0. Implement the IsValid() + /// with ServerCallContext version instead. + ARROW_DEPRECATED("Deprecated in 13.0.0. Use ServerCallContext overload instead.") + virtual Status IsValid(const std::string& token, std::string* peer_identity) { + return Status::NotImplemented(typeid(this).name(), "::IsValid() isn't implemented"); + } +}; + +/// \brief An authentication mechanism that does nothing. +class ARROW_FLIGHT_EXPORT NoOpAuthHandler : public ServerAuthHandler { + public: + ~NoOpAuthHandler() override; + Status Authenticate(const ServerCallContext& context, ServerAuthSender* outgoing, + ServerAuthReader* incoming) override; + Status IsValid(const ServerCallContext& context, const std::string& token, + std::string* peer_identity) override; +}; + +} // namespace flight +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server_middleware.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server_middleware.h new file mode 100644 index 0000000000000000000000000000000000000000..030f1a17c21000fe5c11763c4878e87646d07663 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server_middleware.h @@ -0,0 +1,105 @@ +// 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. + +// Interfaces for defining middleware for Flight servers. Currently +// experimental. + +#pragma once + +#include +#include + +#include "arrow/flight/middleware.h" +#include "arrow/flight/type_fwd.h" +#include "arrow/flight/visibility.h" // IWYU pragma: keep +#include "arrow/status.h" + +namespace arrow { +namespace flight { + +/// \brief Server-side middleware for a call, instantiated per RPC. +/// +/// Middleware should be fast and must be infallible: there is no way +/// to reject the call or report errors from the middleware instance. +class ARROW_FLIGHT_EXPORT ServerMiddleware { + public: + virtual ~ServerMiddleware() = default; + + /// \brief Unique name of middleware, used as alternative to RTTI + /// \return the string name of the middleware + virtual std::string name() const = 0; + + /// \brief A callback before headers are sent. Extra headers can be + /// added, but existing ones cannot be read. + virtual void SendingHeaders(AddCallHeaders* outgoing_headers) = 0; + + /// \brief A callback after the call has completed. + virtual void CallCompleted(const Status& status) = 0; +}; + +/// \brief A factory for new middleware instances. +/// +/// If added to a server, this will be called for each RPC (including +/// Handshake) to give the opportunity to intercept the call. +/// +/// It is guaranteed that all server middleware methods are called +/// from the same thread that calls the RPC method implementation. +class ARROW_FLIGHT_EXPORT ServerMiddlewareFactory { + public: + virtual ~ServerMiddlewareFactory() = default; + + /// \brief A callback for the start of a new call. + /// + /// Return a non-OK status to reject the call with the given status. + /// + /// \param[in] info Information about the call. + /// \param[in] context The call context. + /// \param[out] middleware The middleware instance for this call. If + /// null, no middleware will be added to this call instance from + /// this factory. + /// \return Status A non-OK status will reject the call with the + /// given status. Middleware previously in the chain will have + /// their CallCompleted callback called. Other middleware + /// factories will not be called. + virtual Status StartCall(const CallInfo& info, const ServerCallContext& context, + std::shared_ptr* middleware); + + /// \brief A callback for the start of a new call. + /// + /// Return a non-OK status to reject the call with the given status. + /// + /// \param info Information about the call. + /// \param incoming_headers Headers sent by the client for this call. + /// Do not retain a reference to this object. + /// \param[out] middleware The middleware instance for this call. If + /// null, no middleware will be added to this call instance from + /// this factory. + /// \return Status A non-OK status will reject the call with the + /// given status. Middleware previously in the chain will have + /// their CallCompleted callback called. Other middleware + /// factories will not be called. + /// \deprecated Deprecated in 13.0.0. Implement the StartCall() + /// with ServerCallContext version instead. + ARROW_DEPRECATED("Deprecated in 13.0.0. Use ServerCallContext overload instead.") + virtual Status StartCall(const CallInfo& info, const CallHeaders& incoming_headers, + std::shared_ptr* middleware) { + return Status::NotImplemented(typeid(this).name(), "::StartCall() isn't implemented"); + } +}; + +} // namespace flight +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server_tracing_middleware.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server_tracing_middleware.h new file mode 100644 index 0000000000000000000000000000000000000000..581c8354368cf1d87d10cb87a76d162fe7be2d7b --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server_tracing_middleware.h @@ -0,0 +1,68 @@ +// 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. + +// Middleware implementation for propagating OpenTelemetry spans. + +#pragma once + +#include +#include +#include + +#include "arrow/flight/server_middleware.h" +#include "arrow/flight/visibility.h" +#include "arrow/status.h" + +namespace arrow { +namespace flight { + +/// \brief Returns a ServerMiddlewareFactory that handles receiving OpenTelemetry spans. +ARROW_FLIGHT_EXPORT std::shared_ptr +MakeTracingServerMiddlewareFactory(); + +/// \brief A server middleware that provides access to the +/// OpenTelemetry context, if present. +/// +/// Used to make the OpenTelemetry span available in Python. +class ARROW_FLIGHT_EXPORT TracingServerMiddleware : public ServerMiddleware { + public: + ~TracingServerMiddleware(); + + static constexpr char const kMiddlewareName[] = + "arrow::flight::TracingServerMiddleware"; + + std::string name() const override { return kMiddlewareName; } + void SendingHeaders(AddCallHeaders*) override; + void CallCompleted(const Status&) override; + + struct TraceKey { + std::string key; + std::string value; + }; + /// \brief Get the trace context. + std::vector GetTraceContext() const; + + private: + class Impl; + friend class TracingServerMiddlewareFactory; + + explicit TracingServerMiddleware(std::unique_ptr impl); + std::unique_ptr impl_; +}; + +} // namespace flight +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/test_util.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/test_util.h new file mode 100644 index 0000000000000000000000000000000000000000..c0b42d9b90c5a1f4c211c78d3685a31000d76f57 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/test_util.h @@ -0,0 +1,264 @@ +// 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. + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "arrow/status.h" +#include "arrow/testing/gtest_util.h" +#include "arrow/testing/util.h" + +#include "arrow/flight/client.h" +#include "arrow/flight/client_auth.h" +#include "arrow/flight/server.h" +#include "arrow/flight/server_auth.h" +#include "arrow/flight/types.h" +#include "arrow/flight/visibility.h" + +namespace boost { +namespace process { + +class child; + +} // namespace process +} // namespace boost + +namespace arrow { +namespace flight { + +// ---------------------------------------------------------------------- +// Helpers to compare values for equality + +inline void AssertEqual(const FlightInfo& expected, const FlightInfo& actual) { + ipc::DictionaryMemo expected_memo; + ipc::DictionaryMemo actual_memo; + ASSERT_OK_AND_ASSIGN(auto ex_schema, expected.GetSchema(&expected_memo)); + ASSERT_OK_AND_ASSIGN(auto actual_schema, actual.GetSchema(&actual_memo)); + + AssertSchemaEqual(*ex_schema, *actual_schema); + ASSERT_EQ(expected.total_records(), actual.total_records()); + ASSERT_EQ(expected.total_bytes(), actual.total_bytes()); + + ASSERT_EQ(expected.descriptor(), actual.descriptor()); + ASSERT_THAT(actual.endpoints(), ::testing::ContainerEq(expected.endpoints())); +} + +// ---------------------------------------------------------------------- +// Fixture to use for running test servers + +class ARROW_FLIGHT_EXPORT TestServer { + public: + explicit TestServer(const std::string& executable_name) + : executable_name_(executable_name), port_(::arrow::GetListenPort()) {} + TestServer(const std::string& executable_name, int port) + : executable_name_(executable_name), port_(port) {} + TestServer(const std::string& executable_name, const std::string& unix_sock) + : executable_name_(executable_name), unix_sock_(unix_sock) {} + + void Start(const std::vector& extra_args); + void Start() { Start({}); } + + int Stop(); + + bool IsRunning(); + + int port() const; + const std::string& unix_sock() const; + + private: + std::string executable_name_; + int port_; + std::string unix_sock_; + std::shared_ptr<::boost::process::child> server_process_; +}; + +/// \brief Create a simple Flight server for testing +ARROW_FLIGHT_EXPORT +std::unique_ptr ExampleTestServer(); + +// Helper to initialize a server and matching client with callbacks to +// populate options. +template +Status MakeServer(const Location& location, std::unique_ptr* server, + std::unique_ptr* client, + std::function make_server_options, + std::function make_client_options, + Args&&... server_args) { + *server = std::make_unique(std::forward(server_args)...); + FlightServerOptions server_options(location); + RETURN_NOT_OK(make_server_options(&server_options)); + RETURN_NOT_OK((*server)->Init(server_options)); + std::string uri = + location.scheme() + "://127.0.0.1:" + std::to_string((*server)->port()); + ARROW_ASSIGN_OR_RAISE(auto real_location, Location::Parse(uri)); + FlightClientOptions client_options = FlightClientOptions::Defaults(); + RETURN_NOT_OK(make_client_options(&client_options)); + return FlightClient::Connect(real_location, client_options).Value(client); +} + +// Helper to initialize a server and matching client with callbacks to +// populate options. +template +Status MakeServer(std::unique_ptr* server, + std::unique_ptr* client, + std::function make_server_options, + std::function make_client_options, + Args&&... server_args) { + ARROW_ASSIGN_OR_RAISE(auto location, Location::ForGrpcTcp("localhost", 0)); + return MakeServer(location, server, client, std::move(make_server_options), + std::move(make_client_options), + std::forward(server_args)...); +} + +// ---------------------------------------------------------------------- +// A FlightDataStream that numbers the record batches +/// \brief A basic implementation of FlightDataStream that will provide +/// a sequence of FlightData messages to be written to a stream +class ARROW_FLIGHT_EXPORT NumberingStream : public FlightDataStream { + public: + explicit NumberingStream(std::unique_ptr stream); + + std::shared_ptr schema() override; + arrow::Result GetSchemaPayload() override; + arrow::Result Next() override; + + private: + int counter_; + std::shared_ptr stream_; +}; + +// ---------------------------------------------------------------------- +// Example data for test-server and unit tests + +ARROW_FLIGHT_EXPORT +std::shared_ptr ExampleIntSchema(); + +ARROW_FLIGHT_EXPORT +std::shared_ptr ExampleStringSchema(); + +ARROW_FLIGHT_EXPORT +std::shared_ptr ExampleDictSchema(); + +ARROW_FLIGHT_EXPORT +std::shared_ptr ExampleLargeSchema(); + +ARROW_FLIGHT_EXPORT +Status ExampleIntBatches(RecordBatchVector* out); + +ARROW_FLIGHT_EXPORT +Status ExampleFloatBatches(RecordBatchVector* out); + +ARROW_FLIGHT_EXPORT +Status ExampleDictBatches(RecordBatchVector* out); + +ARROW_FLIGHT_EXPORT +Status ExampleNestedBatches(RecordBatchVector* out); + +ARROW_FLIGHT_EXPORT +Status ExampleLargeBatches(RecordBatchVector* out); + +ARROW_FLIGHT_EXPORT +arrow::Result> VeryLargeBatch(); + +ARROW_FLIGHT_EXPORT +std::vector ExampleFlightInfo(); + +ARROW_FLIGHT_EXPORT +std::vector ExampleActionTypes(); + +ARROW_FLIGHT_EXPORT +FlightInfo MakeFlightInfo(const Schema& schema, const FlightDescriptor& descriptor, + const std::vector& endpoints, + int64_t total_records, int64_t total_bytes, bool ordered, + std::string app_metadata); + +// ---------------------------------------------------------------------- +// A pair of authentication handlers that check for a predefined password +// and set the peer identity to a predefined username. + +class ARROW_FLIGHT_EXPORT TestServerAuthHandler : public ServerAuthHandler { + public: + explicit TestServerAuthHandler(const std::string& username, + const std::string& password); + ~TestServerAuthHandler() override; + Status Authenticate(const ServerCallContext& context, ServerAuthSender* outgoing, + ServerAuthReader* incoming) override; + Status IsValid(const ServerCallContext& context, const std::string& token, + std::string* peer_identity) override; + + private: + std::string username_; + std::string password_; +}; + +class ARROW_FLIGHT_EXPORT TestServerBasicAuthHandler : public ServerAuthHandler { + public: + explicit TestServerBasicAuthHandler(const std::string& username, + const std::string& password); + ~TestServerBasicAuthHandler() override; + Status Authenticate(const ServerCallContext& context, ServerAuthSender* outgoing, + ServerAuthReader* incoming) override; + Status IsValid(const ServerCallContext& context, const std::string& token, + std::string* peer_identity) override; + + private: + BasicAuth basic_auth_; +}; + +class ARROW_FLIGHT_EXPORT TestClientAuthHandler : public ClientAuthHandler { + public: + explicit TestClientAuthHandler(const std::string& username, + const std::string& password); + ~TestClientAuthHandler() override; + Status Authenticate(ClientAuthSender* outgoing, ClientAuthReader* incoming) override; + Status GetToken(std::string* token) override; + + private: + std::string username_; + std::string password_; +}; + +class ARROW_FLIGHT_EXPORT TestClientBasicAuthHandler : public ClientAuthHandler { + public: + explicit TestClientBasicAuthHandler(const std::string& username, + const std::string& password); + ~TestClientBasicAuthHandler() override; + Status Authenticate(ClientAuthSender* outgoing, ClientAuthReader* incoming) override; + Status GetToken(std::string* token) override; + + private: + BasicAuth basic_auth_; + std::string token_; +}; + +ARROW_FLIGHT_EXPORT +Status ExampleTlsCertificates(std::vector* out); + +ARROW_FLIGHT_EXPORT +Status ExampleTlsCertificateRoot(CertKeyPair* out); + +} // namespace flight +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/transport_server.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/transport_server.h new file mode 100644 index 0000000000000000000000000000000000000000..8e5fe3e710c139d53dee896e42dd9475ee4f52c1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/transport_server.h @@ -0,0 +1,133 @@ +// 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. + +#pragma once + +#include +#include + +#include "arrow/flight/transport.h" +#include "arrow/flight/type_fwd.h" +#include "arrow/flight/visibility.h" +#include "arrow/type_fwd.h" + +namespace arrow { +namespace ipc { +class Message; +} +namespace flight { +namespace internal { + +/// \brief A transport-specific interface for reading/writing Arrow +/// data for a server. +class ARROW_FLIGHT_EXPORT ServerDataStream : public TransportDataStream { + public: + /// \brief Attempt to write a non-data message. + /// + /// Only implemented for DoPut; mutually exclusive with + /// WriteData(const FlightPayload&). + virtual Status WritePutMetadata(const Buffer& payload); +}; + +/// \brief An implementation of a Flight server for a particular +/// transport. +/// +/// This class (the transport implementation) implements the underlying +/// server and handles connections/incoming RPC calls. It should forward RPC +/// calls to the RPC handlers defined on this class, which work in terms of +/// the generic interfaces above. The RPC handlers here then forward calls +/// to the underlying FlightServerBase instance that contains the actual +/// application RPC method handlers. +/// +/// Used by FlightServerBase to manage the server lifecycle. +class ARROW_FLIGHT_EXPORT ServerTransport { + public: + ServerTransport(FlightServerBase* base, std::shared_ptr memory_manager) + : base_(base), memory_manager_(std::move(memory_manager)) {} + virtual ~ServerTransport() = default; + + /// \name Server Lifecycle Methods + /// Transports implement these methods to start/shutdown the underlying + /// server. + /// @{ + /// \brief Initialize the server. + /// + /// This method should launch the server in a background thread, i.e. it + /// should not block. Once this returns, the server should be active. + virtual Status Init(const FlightServerOptions& options, + const arrow::util::Uri& uri) = 0; + /// \brief Shutdown the server. + /// + /// This should wait for active RPCs to finish. Once this returns, the + /// server is no longer listening. + virtual Status Shutdown() = 0; + /// \brief Shutdown the server with a deadline. + /// + /// This should wait for active RPCs to finish, or for the deadline to + /// expire. Once this returns, the server is no longer listening. + virtual Status Shutdown(const std::chrono::system_clock::time_point& deadline) = 0; + /// \brief Wait for the server to shutdown (but do not shut down the server). + /// + /// Once this returns, the server is no longer listening. + virtual Status Wait() = 0; + /// \brief Get the address the server is listening on, else an empty Location. + virtual Location location() const = 0; + ///@} + + /// \name RPC Handlers + /// Implementations of RPC handlers for Flight methods using the common + /// interfaces here. Transports should call these methods from their + /// server implementation to handle the actual RPC calls. + ///@{ + /// \brief Get the FlightServerBase. + /// + /// Intended as an escape hatch for now since not all methods have been + /// factored into a transport-agnostic interface. + FlightServerBase* base() const { return base_; } + /// \brief Implement DoGet in terms of a transport-level stream. + /// + /// \param[in] context The server context. + /// \param[in] request The request payload. + /// \param[in] stream The transport-specific data stream + /// implementation. Must implement WriteData(const + /// FlightPayload&). + Status DoGet(const ServerCallContext& context, const Ticket& request, + ServerDataStream* stream); + /// \brief Implement DoPut in terms of a transport-level stream. + /// + /// \param[in] context The server context. + /// \param[in] stream The transport-specific data stream + /// implementation. Must implement ReadData(FlightData*) + /// and WritePutMetadata(const Buffer&). + Status DoPut(const ServerCallContext& context, ServerDataStream* stream); + /// \brief Implement DoExchange in terms of a transport-level stream. + /// + /// \param[in] context The server context. + /// \param[in] stream The transport-specific data stream + /// implementation. Must implement ReadData(FlightData*) + /// and WriteData(const FlightPayload&). + Status DoExchange(const ServerCallContext& context, ServerDataStream* stream); + ///@} + + protected: + FlightServerBase* base_; + std::shared_ptr memory_manager_; +}; + +} // namespace internal +} // namespace flight +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/type_fwd.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/type_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..2f22bbea36dbbf1e3da7ce10975a9584accb989e --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/type_fwd.h @@ -0,0 +1,65 @@ +// 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. + +#pragma once + +namespace arrow { +namespace internal { +class Uri; +} +namespace flight { +struct Action; +struct ActionType; +template +class AsyncListener; +class AsyncListenerBase; +class AsyncRpc; +struct BasicAuth; +class ClientAuthHandler; +class ClientMiddleware; +class ClientMiddlewareFactory; +struct Criteria; +class FlightCallOptions; +struct FlightClientOptions; +struct FlightDescriptor; +struct FlightEndpoint; +class FlightInfo; +class PollInfo; +class FlightListing; +class FlightMetadataReader; +class FlightMetadataWriter; +struct FlightPayload; +class FlightServerBase; +class FlightServerOptions; +class FlightStreamReader; +class FlightStreamWriter; +struct Location; +struct Result; +class ResultStream; +struct SchemaResult; +class ServerCallContext; +class ServerMiddleware; +class ServerMiddlewareFactory; +struct Ticket; +namespace internal { +class AsyncRpc; +class ClientTransport; +struct FlightData; +class ServerTransport; +} // namespace internal +} // namespace flight +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/visibility.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/visibility.h new file mode 100644 index 0000000000000000000000000000000000000000..bdee8b751d8a33bff8f2c2a4348ad47b752de84c --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/flight/visibility.h @@ -0,0 +1,48 @@ +// 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. + +#pragma once + +#if defined(_WIN32) || defined(__CYGWIN__) +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4251) +#else +#pragma GCC diagnostic ignored "-Wattributes" +#endif + +#ifdef ARROW_FLIGHT_STATIC +#define ARROW_FLIGHT_EXPORT +#elif defined(ARROW_FLIGHT_EXPORTING) +#define ARROW_FLIGHT_EXPORT __declspec(dllexport) +#else +#define ARROW_FLIGHT_EXPORT __declspec(dllimport) +#endif + +#define ARROW_FLIGHT_NO_EXPORT +#else // Not Windows +#ifndef ARROW_FLIGHT_EXPORT +#define ARROW_FLIGHT_EXPORT __attribute__((visibility("default"))) +#endif +#ifndef ARROW_FLIGHT_NO_EXPORT +#define ARROW_FLIGHT_NO_EXPORT __attribute__((visibility("hidden"))) +#endif +#endif // Non-Windows + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/api.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/api.h new file mode 100644 index 0000000000000000000000000000000000000000..a0b13d6d13013cfd0f5f0af9c6a6dcea6ceeaafd --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/api.h @@ -0,0 +1,30 @@ +// 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. + +#pragma once + +#include "arrow/python/arrow_to_pandas.h" +#include "arrow/python/common.h" +#include "arrow/python/datetime.h" +#include "arrow/python/deserialize.h" +#include "arrow/python/helpers.h" +#include "arrow/python/inference.h" +#include "arrow/python/io.h" +#include "arrow/python/numpy_convert.h" +#include "arrow/python/numpy_to_arrow.h" +#include "arrow/python/python_to_arrow.h" +#include "arrow/python/serialize.h" diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/arrow_to_pandas.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/arrow_to_pandas.h new file mode 100644 index 0000000000000000000000000000000000000000..82e0a600513d4abd9bb956053a2a7e94a1033f39 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/arrow_to_pandas.h @@ -0,0 +1,146 @@ +// 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. + +// Functions for converting between pandas's NumPy-based data representation +// and Arrow data structures + +#pragma once + +#include "arrow/python/platform.h" + +#include +#include +#include + +#include "arrow/memory_pool.h" +#include "arrow/python/visibility.h" + +namespace arrow { + +class Array; +class ChunkedArray; +class Column; +class DataType; +class MemoryPool; +class Status; +class Table; + +namespace py { + +enum class MapConversionType { + DEFAULT, // convert arrow maps to assoc lists (list of kev-value tuples) in Pandas + LOSSY, // report warnings when lossiness is encountered due to duplicate keys + STRICT_, // raise a Python exception when lossiness is encountered due to duplicate + // keys +}; + +struct PandasOptions { + /// arrow::MemoryPool to use for memory allocations + MemoryPool* pool = default_memory_pool(); + + /// If true, we will convert all string columns to categoricals + bool strings_to_categorical = false; + bool zero_copy_only = false; + bool integer_object_nulls = false; + bool date_as_object = false; + bool timestamp_as_object = false; + bool use_threads = false; + + /// Coerce all date and timestamp to datetime64[ns] + bool coerce_temporal_nanoseconds = false; + + /// Used to maintain backwards compatibility for + /// timezone bugs (see ARROW-9528). Should be removed + /// after Arrow 2.0 release. + bool ignore_timezone = false; + + /// \brief If true, do not create duplicate PyObject versions of equal + /// objects. This only applies to immutable objects like strings or datetime + /// objects + bool deduplicate_objects = false; + + /// \brief For certain data types, a cast is needed in order to store the + /// data in a pandas DataFrame or Series (e.g. timestamps are always stored + /// as nanoseconds in pandas). This option controls whether it is a safe + /// cast or not. + bool safe_cast = true; + + /// \brief If true, create one block per column rather than consolidated + /// blocks (1 per data type). Do zero-copy wrapping when there are no + /// nulls. pandas currently will consolidate the blocks on its own, causing + /// increased memory use, so keep this in mind if you are working on a + /// memory-constrained situation. + bool split_blocks = false; + + /// \brief If true, allow non-writable zero-copy views to be created for + /// single column blocks. This option is also used to provide zero copy for + /// Series data + bool allow_zero_copy_blocks = false; + + /// \brief If true, attempt to deallocate buffers in passed Arrow object if + /// it is the only remaining shared_ptr copy of it. See ARROW-3789 for + /// original context for this feature. Only currently implemented for Table + /// conversions + bool self_destruct = false; + + /// \brief The default behavior (DEFAULT), is to convert Arrow Map arrays to + /// Python association lists (list-of-tuples) in the same order as the Arrow + /// Map, as in [(key1, value1), (key2, value2), ...] + /// If LOSSY or STRICT, convert Arrow Map arrays to native Python dicts. + /// This can change the ordering of (key, value) pairs, and will deduplicate + /// multiple keys, resulting in a possible loss of data. + /// If 'lossy', this key deduplication results in a warning printed + /// when detected. If 'strict', this instead results in an exception + /// being raised when detected. + MapConversionType maps_as_pydicts = MapConversionType::DEFAULT; + + // Used internally for nested arrays. + bool decode_dictionaries = false; + + // Columns that should be casted to categorical + std::unordered_set categorical_columns; + + // Columns that should be passed through to be converted to + // ExtensionArray/Block + std::unordered_set extension_columns; + + // Used internally to decipher between to_numpy() and to_pandas() when + // the expected output differs + bool to_numpy = false; +}; + +ARROW_PYTHON_EXPORT +Status ConvertArrayToPandas(const PandasOptions& options, std::shared_ptr arr, + PyObject* py_ref, PyObject** out); + +ARROW_PYTHON_EXPORT +Status ConvertChunkedArrayToPandas(const PandasOptions& options, + std::shared_ptr col, PyObject* py_ref, + PyObject** out); + +// Convert a whole table as efficiently as possible to a pandas.DataFrame. +// +// The returned Python object is a list of tuples consisting of the exact 2D +// BlockManager structure of the pandas.DataFrame used as of pandas 0.19.x. +// +// tuple item: (indices: ndarray[int32], block: ndarray[TYPE, ndim=2]) +ARROW_PYTHON_EXPORT +Status ConvertTableToPandas(const PandasOptions& options, std::shared_ptr table, + PyObject** out); + +} // namespace py +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/async.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/async.h new file mode 100644 index 0000000000000000000000000000000000000000..1568d21938e6e79e724d957120e68a7576ba9c2a --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/async.h @@ -0,0 +1,60 @@ +// 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. + +#pragma once + +#include + +#include "arrow/python/common.h" +#include "arrow/status.h" +#include "arrow/util/future.h" + +namespace arrow::py { + +/// \brief Bind a Python callback to an arrow::Future. +/// +/// If the Future finishes successfully, py_wrapper is called with its +/// result value and should return a PyObject*. If py_wrapper is successful, +/// py_cb is called with its return value. +/// +/// If either the Future or py_wrapper fails, py_cb is called with the +/// associated Python exception. +/// +/// \param future The future to bind to. +/// \param py_cb The Python callback function. Will be passed the result of +/// py_wrapper, or a Python exception if the future failed or one was +/// raised by py_wrapper. +/// \param py_wrapper A function (likely defined in Cython) to convert the C++ +/// result of the future to a Python object. +template +void BindFuture(Future future, PyObject* py_cb, PyWrapper py_wrapper) { + Py_INCREF(py_cb); + OwnedRefNoGIL cb_ref(py_cb); + + auto future_cb = [cb_ref = std::move(cb_ref), + py_wrapper = std::move(py_wrapper)](Result result) { + SafeCallIntoPythonVoid([&]() { + OwnedRef py_value_or_exc{WrapResult(std::move(result), std::move(py_wrapper))}; + Py_XDECREF( + PyObject_CallFunctionObjArgs(cb_ref.obj(), py_value_or_exc.obj(), NULLPTR)); + ARROW_WARN_NOT_OK(CheckPyError(), "Internal error in async call"); + }); + }; + future.AddCallback(std::move(future_cb)); +} + +} // namespace arrow::py diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/benchmark.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/benchmark.h new file mode 100644 index 0000000000000000000000000000000000000000..8060dd33722a08eb0935687ea5cb306dbd38a9f0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/benchmark.h @@ -0,0 +1,36 @@ +// 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. + +#pragma once + +#include "arrow/python/platform.h" + +#include "arrow/python/visibility.h" + +namespace arrow { +namespace py { +namespace benchmark { + +// Micro-benchmark routines for use from ASV + +// Run PandasObjectIsNull() once over every object in *list* +ARROW_PYTHON_EXPORT +void Benchmark_PandasObjectIsNull(PyObject* list); + +} // namespace benchmark +} // namespace py +} // namespace arrow diff --git a/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/common.h b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/common.h new file mode 100644 index 0000000000000000000000000000000000000000..4a7886695eadbd70fa6442b1cae88c695f9cd602 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pyarrow/include/arrow/python/common.h @@ -0,0 +1,458 @@ +// 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. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/python/pyarrow.h" +#include "arrow/python/visibility.h" +#include "arrow/result.h" +#include "arrow/util/macros.h" + +namespace arrow { + +class MemoryPool; +template +class Result; + +namespace py { + +// Convert current Python error to a Status. The Python error state is cleared +// and can be restored with RestorePyError(). +ARROW_PYTHON_EXPORT Status ConvertPyError(StatusCode code = StatusCode::UnknownError); +// Query whether the given Status is a Python error (as wrapped by ConvertPyError()). +ARROW_PYTHON_EXPORT bool IsPyError(const Status& status); +// Restore a Python error wrapped in a Status. +ARROW_PYTHON_EXPORT void RestorePyError(const Status& status); + +// Catch a pending Python exception and return the corresponding Status. +// If no exception is pending, Status::OK() is returned. +inline Status CheckPyError(StatusCode code = StatusCode::UnknownError) { + if (ARROW_PREDICT_TRUE(!PyErr_Occurred())) { + return Status::OK(); + } else { + return ConvertPyError(code); + } +} + +#define RETURN_IF_PYERROR() ARROW_RETURN_NOT_OK(CheckPyError()) + +#define PY_RETURN_IF_ERROR(CODE) ARROW_RETURN_NOT_OK(CheckPyError(CODE)) + +// For Cython, as you can't define template C++ functions in Cython, only use them. +// This function can set a Python exception. It assumes that T has a (cheap) +// default constructor. +template +T GetResultValue(Result result) { + if (ARROW_PREDICT_TRUE(result.ok())) { + return *std::move(result); + } else { + int r = internal::check_status(result.status()); // takes the GIL + assert(r == -1); // should have errored out + ARROW_UNUSED(r); + return {}; + } +} + +/// \brief Wrap a Result and return the corresponding Python object. +/// +/// If the Result is successful, py_wrapper is called with its result value +/// and should return a PyObject*. If py_wrapper is successful (returns +/// a non-NULL value), its return value is returned. +/// +/// If either the Result or py_wrapper fails, the associated Python exception +/// is raised and NULL is returned. +// +/// \param result The Result whose value to wrap in a Python object. +/// \param py_wrapper A function (likely defined in Cython) to convert the C++ +/// value of the Result to a Python object. +/// \return A new Python reference, or NULL if an exception occurred +template +PyObject* WrapResult(Result result, PyWrapper&& py_wrapper) { + static_assert(std::is_same_v()))>, + "PyWrapper argument to WrapResult should return a PyObject* " + "when called with a T*"); + Status st = result.status(); + if (st.ok()) { + PyObject* py_value = py_wrapper(result.MoveValueUnsafe()); + st = CheckPyError(); + if (st.ok()) { + return py_value; + } + Py_XDECREF(py_value); // should be null, but who knows + } + // Status is an error, convert it to an exception. + return internal::convert_status(st); +} + +// A RAII-style helper that ensures the GIL is acquired inside a lexical block. +class ARROW_PYTHON_EXPORT PyAcquireGIL { + public: + PyAcquireGIL() : acquired_gil_(false) { acquire(); } + + ~PyAcquireGIL() { release(); } + + void acquire() { + if (!acquired_gil_) { + state_ = PyGILState_Ensure(); + acquired_gil_ = true; + } + } + + // idempotent + void release() { + if (acquired_gil_) { + PyGILState_Release(state_); + acquired_gil_ = false; + } + } + + private: + bool acquired_gil_; + PyGILState_STATE state_; + ARROW_DISALLOW_COPY_AND_ASSIGN(PyAcquireGIL); +}; + +// A RAII-style helper that releases the GIL until the end of a lexical block +class ARROW_PYTHON_EXPORT PyReleaseGIL { + public: + PyReleaseGIL() : ptr_(PyEval_SaveThread(), &unique_ptr_deleter) {} + + private: + static void unique_ptr_deleter(PyThreadState* state) { + if (state) { + PyEval_RestoreThread(state); + } + } + std::unique_ptr ptr_; +}; + +// A helper to call safely into the Python interpreter from arbitrary C++ code. +// The GIL is acquired, and the current thread's error status is preserved. +template +auto SafeCallIntoPython(Function&& func) -> decltype(func()) { + PyAcquireGIL lock; + PyObject* exc_type; + PyObject* exc_value; + PyObject* exc_traceback; + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + auto maybe_status = std::forward(func)(); + // If the return Status is a "Python error", the current Python error status + // describes the error and shouldn't be clobbered. + if (!IsPyError(::arrow::internal::GenericToStatus(maybe_status)) && + exc_type != NULLPTR) { + PyErr_Restore(exc_type, exc_value, exc_traceback); + } + return maybe_status; +} + +template +auto SafeCallIntoPythonVoid(Function&& func) -> decltype(func()) { + PyAcquireGIL lock; + PyObject* exc_type; + PyObject* exc_value; + PyObject* exc_traceback; + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + func(); + if (exc_type != NULLPTR) { + PyErr_Restore(exc_type, exc_value, exc_traceback); + } +} + +// A RAII primitive that DECREFs the underlying PyObject* when it +// goes out of scope. +class ARROW_PYTHON_EXPORT OwnedRef { + public: + OwnedRef() : obj_(NULLPTR) {} + OwnedRef(OwnedRef&& other) : OwnedRef(other.detach()) {} + explicit OwnedRef(PyObject* obj) : obj_(obj) {} + + OwnedRef& operator=(OwnedRef&& other) { + obj_ = other.detach(); + return *this; + } + + ~OwnedRef() { + // GH-38626: destructor may be called after the Python interpreter is finalized. + if (Py_IsInitialized()) { + reset(); + } + } + + void reset(PyObject* obj) { + Py_XDECREF(obj_); + obj_ = obj; + } + + void reset() { reset(NULLPTR); } + + PyObject* detach() { + PyObject* result = obj_; + obj_ = NULLPTR; + return result; + } + + PyObject* obj() const { return obj_; } + + PyObject** ref() { return &obj_; } + + operator bool() const { return obj_ != NULLPTR; } + + private: + ARROW_DISALLOW_COPY_AND_ASSIGN(OwnedRef); + + PyObject* obj_; +}; + +// Same as OwnedRef, but ensures the GIL is taken when it goes out of scope. +// This is for situations where the GIL is not always known to be held +// (e.g. if it is released in the middle of a function for performance reasons) +class ARROW_PYTHON_EXPORT OwnedRefNoGIL : public OwnedRef { + public: + OwnedRefNoGIL() : OwnedRef() {} + OwnedRefNoGIL(OwnedRefNoGIL&& other) : OwnedRef(other.detach()) {} + explicit OwnedRefNoGIL(PyObject* obj) : OwnedRef(obj) {} + + ~OwnedRefNoGIL() { + // GH-38626: destructor may be called after the Python interpreter is finalized. + if (Py_IsInitialized() && obj() != NULLPTR) { + PyAcquireGIL lock; + reset(); + } + } +}; + +template