apply clang-tidy modernize-use-override
[folly.git] / folly / io / RecordIO.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * RecordIO: self-synchronizing stream of variable length records
19  *
20  * RecordIO gives you the ability to write a stream of variable length records
21  * and read them later even in the face of data corruption -- randomly inserted
22  * or deleted chunks of the file, or modified data.  When reading, you may lose
23  * corrupted records, but the stream will resynchronize automatically.
24  */
25
26 #pragma once
27 #define FOLLY_IO_RECORDIO_H_
28
29 #include <atomic>
30 #include <memory>
31 #include <mutex>
32
33 #include <folly/File.h>
34 #include <folly/Range.h>
35 #include <folly/MemoryMapping.h>
36 #include <folly/io/IOBuf.h>
37
38 namespace folly {
39
40 /**
41  * Class to write a stream of RecordIO records to a file.
42  *
43  * RecordIOWriter is thread-safe
44  */
45 class RecordIOWriter {
46  public:
47   /**
48    * Create a RecordIOWriter around a file; will append to the end of
49    * file if it exists.
50    *
51    * Each file must have a non-zero file id, which is embedded in all
52    * record headers.  Readers will only return records with the requested
53    * file id (or, if the reader is created with fileId=0 in the constructor,
54    * the reader will return all records).  File ids are only used to allow
55    * resynchronization if you store RecordIO records (with headers) inside
56    * other RecordIO records (for example, if a record consists of a fragment
57    * from another RecordIO file).  If you're not planning to do that,
58    * the defaults are fine.
59    */
60   explicit RecordIOWriter(File file, uint32_t fileId = 1);
61
62   /**
63    * Write a record.  We will use at most headerSize() bytes of headroom,
64    * you might want to arrange that before copying your data into it.
65    */
66   void write(std::unique_ptr<IOBuf> buf);
67
68   /**
69    * Return the position in the file where the next byte will be written.
70    * Conservative, as stuff can be written at any time from another thread.
71    */
72   off_t filePos() const { return filePos_; }
73
74  private:
75   File file_;
76   uint32_t fileId_;
77   std::unique_lock<File> writeLock_;
78   std::atomic<off_t> filePos_;
79 };
80
81 /**
82  * Class to read from a RecordIO file.  Will skip invalid records.
83  */
84 class RecordIOReader {
85  public:
86   class Iterator;
87
88   /**
89    * RecordIOReader is iterable, returning pairs of ByteRange (record content)
90    * and position in file where the record (including header) begins.
91    * Note that the position includes the header, that is, it can be passed back
92    * to seek().
93    */
94   typedef Iterator iterator;
95   typedef Iterator const_iterator;
96   typedef std::pair<ByteRange, off_t> value_type;
97   typedef value_type& reference;
98   typedef const value_type& const_reference;
99
100   /**
101    * A record reader with a fileId of 0 will return all records.
102    * A record reader with a non-zero fileId will only return records where
103    * the fileId matches.
104    */
105   explicit RecordIOReader(File file, uint32_t fileId = 0);
106
107   Iterator cbegin() const;
108   Iterator begin() const;
109   Iterator cend() const;
110   Iterator end() const;
111
112   /**
113    * Create an iterator to the first valid record after pos.
114    */
115   Iterator seek(off_t pos) const;
116
117  private:
118   MemoryMapping map_;
119   uint32_t fileId_;
120 };
121
122 namespace recordio_helpers {
123
124 // We're exposing the guts of the RecordIO implementation for two reasons:
125 // 1. It makes unit testing easier, and
126 // 2. It allows you to build different RecordIO readers / writers that use
127 // different storage systems underneath (not standard files)
128
129 /**
130  * Header size.
131  */
132 constexpr size_t headerSize();  // defined in RecordIO-inl.h
133
134 /**
135  * Write a header in the buffer.  We will prepend the header to the front
136  * of the chain.  Do not write the buffer if empty (we don't allow empty
137  * records).  Returns the total length, including header (0 if empty)
138  * (same as buf->computeChainDataLength(), but likely faster)
139  *
140  * The fileId should be unique per stream and allows you to have RecordIO
141  * headers stored inside the data (for example, have an entire RecordIO
142  * file stored as a record inside another RecordIO file).  The fileId may
143  * not be 0.
144  */
145 size_t prependHeader(std::unique_ptr<IOBuf>& buf, uint32_t fileId = 1);
146
147 /**
148  * Search for the first valid record that begins in searchRange (which must be
149  * a subrange of wholeRange).  Returns the record data (not the header) if
150  * found, ByteRange() otherwise.
151  *
152  * The fileId may be 0, in which case we'll return the first valid record for
153  * *any* fileId, or non-zero, in which case we'll only look for records with
154  * the requested fileId.
155  */
156 struct RecordInfo {
157   uint32_t fileId;
158   ByteRange record;
159 };
160 RecordInfo findRecord(ByteRange searchRange,
161                       ByteRange wholeRange,
162                       uint32_t fileId);
163
164 /**
165  * Search for the first valid record in range.
166  */
167 RecordInfo findRecord(ByteRange range, uint32_t fileId);
168
169 /**
170  * Check if there is a valid record at the beginning of range.  Returns the
171  * record data (not the header) if the record is valid, ByteRange() otherwise.
172  */
173 RecordInfo validateRecord(ByteRange range, uint32_t fileId);
174
175 }  // namespace recordio_helpers
176
177 }  // namespaces
178
179 #include <folly/io/RecordIO-inl.h>