io.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. #pragma once
  2. ///
  3. /// @file yt/cpp/mapreduce/interface/io.h
  4. ///
  5. /// Header containing client interface for reading and writing tables and files.
  6. #include "fwd.h"
  7. #include "client_method_options.h"
  8. #include "common.h"
  9. #include "format.h"
  10. #include "node.h"
  11. #include "mpl.h"
  12. #include "skiff_row.h"
  13. #include <google/protobuf/message.h>
  14. #include <util/stream/input.h>
  15. #include <util/stream/output.h>
  16. #include <util/generic/yexception.h>
  17. #include <util/generic/maybe.h>
  18. namespace NYT {
  19. ////////////////////////////////////////////////////////////////////////////////
  20. ///
  21. /// @brief "Marker" type to use for several protobuf types in @ref NYT::TTableReader.
  22. ///
  23. /// @tparam Ts Possible types of rows to be read.
  24. template<class... TProtoRowTypes>
  25. class TProtoOneOf
  26. {
  27. public:
  28. static_assert(
  29. (TIsBaseOf<::google::protobuf::Message, TProtoRowTypes>::Value && ...),
  30. "Template parameters can only be protobuf types");
  31. TProtoOneOf() = delete;
  32. };
  33. ///
  34. /// @brief "Marker" type to use for several skiff row types in @ref NYT::TTableReader.
  35. ///
  36. /// @tparam Ts Possible types of rows to be read.
  37. template<class... TSkiffRowTypes>
  38. class TSkiffRowOneOf
  39. {
  40. public:
  41. static_assert(
  42. (TIsSkiffRow<TSkiffRowTypes>::value && ...),
  43. "Template parameters can only be SkiffRow types");
  44. TSkiffRowOneOf() = delete;
  45. };
  46. ////////////////////////////////////////////////////////////////////////////////
  47. /// @cond Doxygen_Suppress
  48. namespace NDetail {
  49. ////////////////////////////////////////////////////////////////////////////////
  50. template <class TTuple>
  51. struct TProtoOneOfFromTuple;
  52. template <class... Ts>
  53. struct TProtoOneOfFromTuple<std::tuple<Ts...>>
  54. {
  55. using TType = TProtoOneOf<Ts...>;
  56. };
  57. template <class... Ts>
  58. struct TProtoOneOfUnique
  59. {
  60. using TTuple = typename TUniqueTypes<std::tuple<>, std::tuple<Ts...>>::TType;
  61. using TType = typename TProtoOneOfFromTuple<TTuple>::TType;
  62. };
  63. ////////////////////////////////////////////////////////////////////////////////
  64. } // namespace NDetail
  65. /// @endcond
  66. ////////////////////////////////////////////////////////////////////////////////
  67. struct INodeReaderImpl;
  68. struct IYaMRReaderImpl;
  69. struct IProtoReaderImpl;
  70. struct ISkiffRowReaderImpl;
  71. struct INodeWriterImpl;
  72. struct IYaMRWriterImpl;
  73. struct IProtoWriterImpl;
  74. ////////////////////////////////////////////////////////////////////////////////
  75. /// Class of exceptions connected to reading or writing tables or files.
  76. class TIOException
  77. : public yexception
  78. { };
  79. ///////////////////////////////////////////////////////////////////////////////
  80. /// Interface representing YT file reader.
  81. class IFileReader
  82. : public TThrRefBase
  83. , public IInputStream
  84. { };
  85. /// Interface representing YT file writer.
  86. class IFileWriter
  87. : public TThrRefBase
  88. , public IOutputStream
  89. { };
  90. ////////////////////////////////////////////////////////////////////////////////
  91. /// Low-level interface to read YT table with retries.
  92. class TRawTableReader
  93. : public TThrRefBase
  94. , public IInputStream
  95. {
  96. public:
  97. /// @brief Retry table read starting from the specified `rangeIndex` and `rowIndex`.
  98. ///
  99. /// @param rangeIndex Index of first range to read
  100. /// @param rowIndex Index of first row to read; if `rowIndex == Nothing` entire request will be retried.
  101. ///
  102. /// @return `true` on successful request retry, `false` if no retry attempts are left (then `Retry()` shouldn't be called any more).
  103. ///
  104. /// `rowIndex` must be inside the range with index `rangeIndex` if the latter is specified.
  105. ///
  106. /// After successful retry the user should reset `rangeIndex` / `rowIndex` values and read new ones
  107. /// from the stream.
  108. virtual bool Retry(
  109. const TMaybe<ui32>& rangeIndex,
  110. const TMaybe<ui64>& rowIndex) = 0;
  111. /// Resets retry attempt count to the initial value (then `Retry()` can be called again).
  112. virtual void ResetRetries() = 0;
  113. /// @brief May the input stream contain table ranges?
  114. ///
  115. /// In the case when it is `true` the `TRawTableReader` user is responsible
  116. /// to track active range index in order to pass it to Retry().
  117. virtual bool HasRangeIndices() const = 0;
  118. };
  119. /// @brief Low-level interface to write YT table.
  120. ///
  121. /// Retries must be handled by implementation.
  122. class TRawTableWriter
  123. : public TThrRefBase
  124. , public IOutputStream
  125. {
  126. public:
  127. /// @brief Call this method after complete row representation is written to the stream.
  128. ///
  129. /// When this method is called `TRowTableWriter` can check its buffer
  130. /// and if it is full send data to YT.
  131. /// @note `TRawTableWriter` never sends partial records to YT (due to retries).
  132. virtual void NotifyRowEnd() = 0;
  133. /// @brief Try to abort writing process as soon as possible (makes sense for multi-threaded writers).
  134. ///
  135. /// By default it does nothing, but implementations are welcome to override this method.
  136. virtual void Abort()
  137. { }
  138. virtual size_t GetBufferMemoryUsage() const
  139. {
  140. return 0;
  141. }
  142. };
  143. /// @brief Interface to deal with multiple raw output streams.
  144. class IProxyOutput
  145. {
  146. public:
  147. virtual ~IProxyOutput()
  148. { }
  149. /// Get amount of managed streams.
  150. virtual size_t GetStreamCount() const = 0;
  151. /// Get stream corresponding to the specified table index.
  152. virtual IOutputStream* GetStream(size_t tableIndex) const = 0;
  153. /// This handler must be called right after the next row has been written.
  154. virtual void OnRowFinished(size_t tableIndex) = 0;
  155. /// @brief Try to abort writing process as soon as possible (makes sense for multi-threaded writers).
  156. ///
  157. /// By default it does nothing, but implementations are welcome to override this method.
  158. virtual void Abort()
  159. { }
  160. virtual size_t GetBufferMemoryUsage() const
  161. {
  162. return 0;
  163. }
  164. };
  165. ////////////////////////////////////////////////////////////////////////////////
  166. /// @brief Class template to read typed rows from YT tables.
  167. ///
  168. /// @tparam T Row type.
  169. ///
  170. /// Correct usage of this class usually looks like
  171. /// ```
  172. /// for (const auto& cursor : *reader) {
  173. /// const auto& row = cursor.GetRow();
  174. /// ...
  175. /// }
  176. /// ```
  177. /// or, more verbosely,
  178. /// ```
  179. /// for (; reader->IsValid(); reader->Next()) {
  180. /// const auto& row = reader->GetRow();
  181. /// ...
  182. /// }
  183. /// ```
  184. ///
  185. /// @note Actual (partial) specializations of this template may look a bit different,
  186. /// e.g. @ref NYT::TTableReader::GetRow, @ref NYT::TTableReader::MoveRow may be method templates.
  187. template <class T, class>
  188. class TTableReader
  189. : public TThrRefBase
  190. {
  191. public:
  192. /// Get current row.
  193. const T& GetRow() const;
  194. /// Extract current row; further calls to `GetRow` and `MoveRow` will fail.
  195. T MoveRow();
  196. /// Extract current row to `result`; further calls to `GetRow` and `MoveRow` will fail.
  197. void MoveRow(T* result);
  198. /// Check whether all the rows were read.
  199. bool IsValid() const;
  200. /// Move the cursor to the next row.
  201. void Next();
  202. /// Get table index of the current row.
  203. ui32 GetTableIndex() const;
  204. /// Get range index of the current row (zero if it is unknown or read request contains no ranges)
  205. ui32 GetRangeIndex() const;
  206. /// Get current row index (zero if it unknown).
  207. ui64 GetRowIndex() const;
  208. /// Get current tablet index (for ordered dynamic tables).
  209. i64 GetTabletIndex() const;
  210. /// Returns `true` if job consumed all the input and `false` otherwise.
  211. bool IsEndOfStream() const;
  212. /// Returns `true` if job raw input stream was closed and `false` otherwise.
  213. bool IsRawReaderExhausted() const;
  214. };
  215. /// @brief Iterator for use in range-based-for.
  216. ///
  217. /// @note Idiomatic usage:
  218. /// ```
  219. /// for (const auto& cursor : *reader) {
  220. /// const auto& row = cursor.GetRow();
  221. /// ...
  222. /// }
  223. /// ```
  224. template <class T>
  225. class TTableReaderIterator
  226. {
  227. public:
  228. /// Construct iterator from table reader (can be `nullptr`).
  229. explicit TTableReaderIterator<T>(TTableReader<T>* reader)
  230. {
  231. if (reader && reader->IsValid()) {
  232. Reader_ = reader;
  233. } else {
  234. Reader_ = nullptr;
  235. }
  236. }
  237. /// Equality operator.
  238. bool operator==(const TTableReaderIterator& it) const
  239. {
  240. return Reader_ == it.Reader_;
  241. }
  242. /// Inequality operator.
  243. bool operator!=(const TTableReaderIterator& it) const
  244. {
  245. return Reader_ != it.Reader_;
  246. }
  247. /// Dereference operator.
  248. TTableReader<T>& operator*()
  249. {
  250. return *Reader_;
  251. }
  252. /// Const dereference operator.
  253. const TTableReader<T>& operator*() const
  254. {
  255. return *Reader_;
  256. }
  257. /// Preincrement operator.
  258. TTableReaderIterator& operator++()
  259. {
  260. Reader_->Next();
  261. if (!Reader_->IsValid()) {
  262. Reader_ = nullptr;
  263. }
  264. return *this;
  265. }
  266. private:
  267. TTableReader<T>* Reader_;
  268. };
  269. /// @brief Function to facilitate range-based-for for @ref NYT::TTableReader.
  270. ///
  271. /// @see @ref NYT::TTableReaderIterator
  272. template <class T>
  273. TTableReaderIterator<T> begin(TTableReader<T>& reader)
  274. {
  275. return TTableReaderIterator<T>(&reader);
  276. }
  277. /// @brief Function to facilitate range-based-for for @ref NYT::TTableReader.
  278. ///
  279. /// @see @ref NYT::TTableReaderIterator
  280. template <class T>
  281. TTableReaderIterator<T> end(TTableReader<T>&)
  282. {
  283. return TTableReaderIterator<T>(nullptr);
  284. }
  285. ////////////////////////////////////////////////////////////////////////////////
  286. /// @brief Class to facilitate reading table rows sorted by key.
  287. ///
  288. /// Each reader returned from @ref NYT::TTableRangesReader::GetRange represents
  289. /// a range of rows with the same key.
  290. ///
  291. /// @note Idiomatic usage:
  292. /// ```
  293. /// for (; reader->IsValid(); reader->Next()) {
  294. /// auto& rangeReader = reader->GetRange();
  295. /// ...
  296. /// }
  297. /// ```
  298. template <class T, class>
  299. class TTableRangesReader
  300. : public TThrRefBase
  301. {
  302. public:
  303. /// Get reader for rows with the same key.
  304. TTableReader<T>& GetRange();
  305. /// Check whether all rows are read.
  306. bool IsValid() const;
  307. /// Move cursor to the next range.
  308. void Next();
  309. };
  310. ////////////////////////////////////////////////////////////////////////////////
  311. /// Class template to write typed rows to YT tables.
  312. template <class T, class>
  313. class TTableWriter
  314. : public TThrRefBase
  315. {
  316. public:
  317. /// @brief Submit a row for writing.
  318. ///
  319. /// The row may (and very probably will) *not* be written immediately.
  320. void AddRow(const T& row);
  321. /// Stop writing data as soon as possible (without flushing data, e.g. before aborting parent transaction).
  322. void Finish();
  323. size_t GetBufferMemoryUsage() const;
  324. };
  325. ////////////////////////////////////////////////////////////////////////////////
  326. /// @brief Type representing YaMR table row.
  327. ///
  328. /// @deprecated
  329. struct TYaMRRow
  330. {
  331. /// Key column.
  332. TStringBuf Key;
  333. /// Subkey column.
  334. TStringBuf SubKey;
  335. /// Value column.
  336. TStringBuf Value;
  337. };
  338. ////////////////////////////////////////////////////////////////////////////////
  339. /// Interface for creating table and file readers and writer.
  340. class IIOClient
  341. {
  342. public:
  343. virtual ~IIOClient() = default;
  344. /// Create a reader for file at `path`.
  345. virtual IFileReaderPtr CreateFileReader(
  346. const TRichYPath& path,
  347. const TFileReaderOptions& options = TFileReaderOptions()) = 0;
  348. /// Create a writer for file at `path`.
  349. virtual IFileWriterPtr CreateFileWriter(
  350. const TRichYPath& path,
  351. const TFileWriterOptions& options = TFileWriterOptions()) = 0;
  352. /// Create a typed reader for table at `path`.
  353. template <class T>
  354. TTableReaderPtr<T> CreateTableReader(
  355. const TRichYPath& path,
  356. const TTableReaderOptions& options = TTableReaderOptions());
  357. /// Create a typed writer for table at `path`.
  358. template <class T>
  359. TTableWriterPtr<T> CreateTableWriter(
  360. const TRichYPath& path,
  361. const TTableWriterOptions& options = TTableWriterOptions());
  362. /// Create a writer to write protobuf messages with specified descriptor.
  363. virtual TTableWriterPtr<::google::protobuf::Message> CreateTableWriter(
  364. const TRichYPath& path,
  365. const ::google::protobuf::Descriptor& descriptor,
  366. const TTableWriterOptions& options = TTableWriterOptions()) = 0;
  367. /// Create a reader to read a table using specified format.
  368. virtual TRawTableReaderPtr CreateRawReader(
  369. const TRichYPath& path,
  370. const TFormat& format,
  371. const TTableReaderOptions& options = TTableReaderOptions()) = 0;
  372. /// Create a reader to write a table using specified format.
  373. virtual TRawTableWriterPtr CreateRawWriter(
  374. const TRichYPath& path,
  375. const TFormat& format,
  376. const TTableWriterOptions& options = TTableWriterOptions()) = 0;
  377. ///
  378. /// @brief Create a reader for [blob table](https://docs.yandex-team.ru/docs/yt/description/storage/blobtables) at `path`.
  379. ///
  380. /// @param path Blob table path.
  381. /// @param blobId Key identifying the blob.
  382. /// @param options Optional parameters
  383. ///
  384. /// Blob table is a table that stores a number of blobs.
  385. /// Blobs are sliced into parts of the same size (maybe except of last part).
  386. /// Those parts are stored in the separate rows.
  387. ///
  388. /// Blob table have constraints on its schema.
  389. /// - There must be columns that identify blob (blob id columns). That columns might be of any type.
  390. /// - There must be a column of `int64` type that identify part inside the blob (this column is called `part index`).
  391. /// - There must be a column of `string` type that stores actual data (this column is called `data column`).
  392. virtual IFileReaderPtr CreateBlobTableReader(
  393. const TYPath& path,
  394. const TKey& blobId,
  395. const TBlobTableReaderOptions& options = TBlobTableReaderOptions()) = 0;
  396. private:
  397. virtual ::TIntrusivePtr<INodeReaderImpl> CreateNodeReader(
  398. const TRichYPath& path, const TTableReaderOptions& options) = 0;
  399. virtual ::TIntrusivePtr<IYaMRReaderImpl> CreateYaMRReader(
  400. const TRichYPath& path, const TTableReaderOptions& options) = 0;
  401. virtual ::TIntrusivePtr<IProtoReaderImpl> CreateProtoReader(
  402. const TRichYPath& path,
  403. const TTableReaderOptions& options,
  404. const ::google::protobuf::Message* prototype) = 0;
  405. virtual ::TIntrusivePtr<ISkiffRowReaderImpl> CreateSkiffRowReader(
  406. const TRichYPath& path,
  407. const TTableReaderOptions& options,
  408. const ISkiffRowSkipperPtr& skipper,
  409. const NSkiff::TSkiffSchemaPtr& schema) = 0;
  410. virtual ::TIntrusivePtr<INodeWriterImpl> CreateNodeWriter(
  411. const TRichYPath& path, const TTableWriterOptions& options) = 0;
  412. virtual ::TIntrusivePtr<IYaMRWriterImpl> CreateYaMRWriter(
  413. const TRichYPath& path, const TTableWriterOptions& options) = 0;
  414. virtual ::TIntrusivePtr<IProtoWriterImpl> CreateProtoWriter(
  415. const TRichYPath& path,
  416. const TTableWriterOptions& options,
  417. const ::google::protobuf::Message* prototype) = 0;
  418. };
  419. ////////////////////////////////////////////////////////////////////////////////
  420. ///
  421. /// @brief Create a protobuf table reader from a stream.
  422. ///
  423. /// @tparam T Protobuf message type to read (must be inherited from `Message`).
  424. ///
  425. /// @param stream Input stream in YT protobuf format.
  426. template <typename T>
  427. TTableReaderPtr<T> CreateTableReader(
  428. IInputStream* stream,
  429. const TTableReaderOptions& options = {});
  430. ///
  431. /// @brief Create a protobuf multi table reader from a stream.
  432. ///
  433. /// @tparam Ts Protobuf message types to read (must be inherited from `Message`).
  434. ///
  435. /// @param stream Input stream in YT protobuf format.
  436. template <class... Ts>
  437. TTableReaderPtr<typename NDetail::TProtoOneOfUnique<Ts...>::TType> CreateProtoMultiTableReader(
  438. IInputStream* stream,
  439. const TTableReaderOptions& options = {});
  440. ///
  441. /// @brief Create a homogenous protobuf multi table reader from a stream.
  442. ///
  443. /// @tparam T Protobuf message type to read (must be inherited from `Message`).
  444. ///
  445. /// @param stream Input stream in YT protobuf format.
  446. /// @param tableCount Number of tables in input stream.
  447. template <class T>
  448. TTableReaderPtr<T> CreateProtoMultiTableReader(
  449. IInputStream* stream,
  450. int tableCount,
  451. const TTableReaderOptions& options = {});
  452. /// Create a @ref NYT::TNode table reader from a stream.
  453. template <>
  454. TTableReaderPtr<TNode> CreateTableReader<TNode>(
  455. IInputStream* stream, const TTableReaderOptions& options);
  456. /// Create a @ref NYT::TYaMRRow table reader from a stream.
  457. template <>
  458. TTableReaderPtr<TYaMRRow> CreateTableReader<TYaMRRow>(
  459. IInputStream* stream, const TTableReaderOptions& options);
  460. namespace NDetail {
  461. /// Create a protobuf table reader from a stream.
  462. ::TIntrusivePtr<IProtoReaderImpl> CreateProtoReader(
  463. IInputStream* stream,
  464. const TTableReaderOptions& options,
  465. const ::google::protobuf::Descriptor* descriptor);
  466. /// Create a protobuf table reader from a stream that can contain table switches.
  467. ::TIntrusivePtr<IProtoReaderImpl> CreateProtoReader(
  468. IInputStream* stream,
  469. const TTableReaderOptions& options,
  470. TVector<const ::google::protobuf::Descriptor*> descriptors);
  471. } // namespace NDetail
  472. ////////////////////////////////////////////////////////////////////////////////
  473. /// Convert generic protobuf table reader to a concrete one (for certain type `T`).
  474. template <typename T>
  475. TTableReaderPtr<T> CreateConcreteProtobufReader(TTableReader<Message>* reader);
  476. /// Convert generic protobuf table reader to a concrete one (for certain type `T`).
  477. template <typename T>
  478. TTableReaderPtr<T> CreateConcreteProtobufReader(const TTableReaderPtr<Message>& reader);
  479. /// Convert a concrete (for certain type `T`) protobuf table reader to a generic one.
  480. template <typename T>
  481. TTableReaderPtr<Message> CreateGenericProtobufReader(TTableReader<T>* reader);
  482. /// Convert a concrete (for certain type `T`) protobuf table reader to a generic one.
  483. template <typename T>
  484. TTableReaderPtr<Message> CreateGenericProtobufReader(const TTableReaderPtr<T>& reader);
  485. ////////////////////////////////////////////////////////////////////////////////
  486. } // namespace NYT
  487. #define IO_INL_H_
  488. #include "io-inl.h"
  489. #undef IO_INL_H_