46f40731bc4d3dd443d0077977bbac4f4754473b
[folly.git] / folly / io / test / CompressionTest.cpp
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 #include <folly/io/Compression.h>
18
19 #include <random>
20 #include <set>
21 #include <thread>
22 #include <unordered_map>
23
24 #include <boost/noncopyable.hpp>
25 #include <glog/logging.h>
26
27 #include <folly/Benchmark.h>
28 #include <folly/Hash.h>
29 #include <folly/Random.h>
30 #include <folly/Varint.h>
31 #include <folly/io/IOBufQueue.h>
32 #include <folly/portability/GTest.h>
33
34 namespace folly { namespace io { namespace test {
35
36 class DataHolder : private boost::noncopyable {
37  public:
38   uint64_t hash(size_t size) const;
39   ByteRange data(size_t size) const;
40
41  protected:
42   explicit DataHolder(size_t sizeLog2);
43   const size_t size_;
44   std::unique_ptr<uint8_t[]> data_;
45   mutable std::unordered_map<uint64_t, uint64_t> hashCache_;
46 };
47
48 DataHolder::DataHolder(size_t sizeLog2)
49   : size_(size_t(1) << sizeLog2),
50     data_(new uint8_t[size_]) {
51 }
52
53 uint64_t DataHolder::hash(size_t size) const {
54   CHECK_LE(size, size_);
55   auto p = hashCache_.find(size);
56   if (p != hashCache_.end()) {
57     return p->second;
58   }
59
60   uint64_t h = folly::hash::fnv64_buf(data_.get(), size);
61   hashCache_[size] = h;
62   return h;
63 }
64
65 ByteRange DataHolder::data(size_t size) const {
66   CHECK_LE(size, size_);
67   return ByteRange(data_.get(), size);
68 }
69
70 uint64_t hashIOBuf(const IOBuf* buf) {
71   uint64_t h = folly::hash::FNV_64_HASH_START;
72   for (auto& range : *buf) {
73     h = folly::hash::fnv64_buf(range.data(), range.size(), h);
74   }
75   return h;
76 }
77
78 class RandomDataHolder : public DataHolder {
79  public:
80   explicit RandomDataHolder(size_t sizeLog2);
81 };
82
83 RandomDataHolder::RandomDataHolder(size_t sizeLog2)
84   : DataHolder(sizeLog2) {
85   constexpr size_t numThreadsLog2 = 3;
86   constexpr size_t numThreads = size_t(1) << numThreadsLog2;
87
88   uint32_t seed = randomNumberSeed();
89
90   std::vector<std::thread> threads;
91   threads.reserve(numThreads);
92   for (size_t t = 0; t < numThreads; ++t) {
93     threads.emplace_back(
94         [this, seed, t, numThreadsLog2, sizeLog2] () {
95           std::mt19937 rng(seed + t);
96           size_t countLog2 = sizeLog2 - numThreadsLog2;
97           size_t start = size_t(t) << countLog2;
98           for (size_t i = 0; i < countLog2; ++i) {
99             this->data_[start + i] = rng();
100           }
101         });
102   }
103
104   for (auto& t : threads) {
105     t.join();
106   }
107 }
108
109 class ConstantDataHolder : public DataHolder {
110  public:
111   explicit ConstantDataHolder(size_t sizeLog2);
112 };
113
114 ConstantDataHolder::ConstantDataHolder(size_t sizeLog2)
115   : DataHolder(sizeLog2) {
116   memset(data_.get(), 'a', size_);
117 }
118
119 constexpr size_t dataSizeLog2 = 27;  // 128MiB
120 RandomDataHolder randomDataHolder(dataSizeLog2);
121 ConstantDataHolder constantDataHolder(dataSizeLog2);
122
123 TEST(CompressionTestNeedsUncompressedLength, Simple) {
124   EXPECT_FALSE(getCodec(CodecType::NO_COMPRESSION)->needsUncompressedLength());
125   EXPECT_TRUE(getCodec(CodecType::LZ4)->needsUncompressedLength());
126   EXPECT_FALSE(getCodec(CodecType::SNAPPY)->needsUncompressedLength());
127   EXPECT_FALSE(getCodec(CodecType::ZLIB)->needsUncompressedLength());
128   EXPECT_FALSE(getCodec(CodecType::LZ4_VARINT_SIZE)->needsUncompressedLength());
129   EXPECT_TRUE(getCodec(CodecType::LZMA2)->needsUncompressedLength());
130   EXPECT_FALSE(getCodec(CodecType::LZMA2_VARINT_SIZE)
131     ->needsUncompressedLength());
132   EXPECT_FALSE(getCodec(CodecType::ZSTD)->needsUncompressedLength());
133   EXPECT_FALSE(getCodec(CodecType::GZIP)->needsUncompressedLength());
134 }
135
136 class CompressionTest
137     : public testing::TestWithParam<std::tr1::tuple<int, int, CodecType>> {
138  protected:
139   void SetUp() override {
140     auto tup = GetParam();
141     uncompressedLength_ = uint64_t(1) << std::tr1::get<0>(tup);
142     chunks_ = std::tr1::get<1>(tup);
143     codec_ = getCodec(std::tr1::get<2>(tup));
144   }
145
146   void runSimpleIOBufTest(const DataHolder& dh);
147
148   void runSimpleStringTest(const DataHolder& dh);
149
150  private:
151   std::unique_ptr<IOBuf> split(std::unique_ptr<IOBuf> data) const;
152
153   uint64_t uncompressedLength_;
154   size_t chunks_;
155   std::unique_ptr<Codec> codec_;
156 };
157
158 void CompressionTest::runSimpleIOBufTest(const DataHolder& dh) {
159   const auto original = split(IOBuf::wrapBuffer(dh.data(uncompressedLength_)));
160   const auto compressed = split(codec_->compress(original.get()));
161   if (!codec_->needsUncompressedLength()) {
162     auto uncompressed = codec_->uncompress(compressed.get());
163     EXPECT_EQ(uncompressedLength_, uncompressed->computeChainDataLength());
164     EXPECT_EQ(dh.hash(uncompressedLength_), hashIOBuf(uncompressed.get()));
165   }
166   {
167     auto uncompressed = codec_->uncompress(compressed.get(),
168                                            uncompressedLength_);
169     EXPECT_EQ(uncompressedLength_, uncompressed->computeChainDataLength());
170     EXPECT_EQ(dh.hash(uncompressedLength_), hashIOBuf(uncompressed.get()));
171   }
172 }
173
174 void CompressionTest::runSimpleStringTest(const DataHolder& dh) {
175   const auto original = std::string(
176       reinterpret_cast<const char*>(dh.data(uncompressedLength_).data()),
177       uncompressedLength_);
178   const auto compressed = codec_->compress(original);
179   if (!codec_->needsUncompressedLength()) {
180     auto uncompressed = codec_->uncompress(compressed);
181     EXPECT_EQ(uncompressedLength_, uncompressed.length());
182     EXPECT_EQ(uncompressed, original);
183   }
184   {
185     auto uncompressed = codec_->uncompress(compressed, uncompressedLength_);
186     EXPECT_EQ(uncompressedLength_, uncompressed.length());
187     EXPECT_EQ(uncompressed, original);
188   }
189 }
190
191 // Uniformly split data into (potentially empty) chunks.
192 std::unique_ptr<IOBuf> CompressionTest::split(
193     std::unique_ptr<IOBuf> data) const {
194   if (data->isChained()) {
195     data->coalesce();
196   }
197
198   const size_t size = data->computeChainDataLength();
199
200   std::multiset<size_t> splits;
201   for (size_t i = 1; i < chunks_; ++i) {
202     splits.insert(Random::rand64(size));
203   }
204
205   folly::IOBufQueue result;
206
207   size_t offset = 0;
208   for (size_t split : splits) {
209     result.append(IOBuf::copyBuffer(data->data() + offset, split - offset));
210     offset = split;
211   }
212   result.append(IOBuf::copyBuffer(data->data() + offset, size - offset));
213
214   return result.move();
215 }
216
217 TEST_P(CompressionTest, RandomData) {
218   runSimpleIOBufTest(randomDataHolder);
219 }
220
221 TEST_P(CompressionTest, ConstantData) {
222   runSimpleIOBufTest(constantDataHolder);
223 }
224
225 TEST_P(CompressionTest, RandomDataString) {
226   runSimpleStringTest(randomDataHolder);
227 }
228
229 TEST_P(CompressionTest, ConstantDataString) {
230   runSimpleStringTest(constantDataHolder);
231 }
232
233 INSTANTIATE_TEST_CASE_P(
234     CompressionTest,
235     CompressionTest,
236     testing::Combine(
237         testing::Values(0, 1, 12, 22, 25, 27),
238         testing::Values(1, 2, 3, 8, 65),
239         testing::Values(
240             CodecType::NO_COMPRESSION,
241             CodecType::LZ4,
242             CodecType::SNAPPY,
243             CodecType::ZLIB,
244             CodecType::LZ4_VARINT_SIZE,
245             CodecType::LZMA2,
246             CodecType::LZMA2_VARINT_SIZE,
247             CodecType::ZSTD,
248             CodecType::GZIP)));
249
250 class CompressionVarintTest
251     : public testing::TestWithParam<std::tr1::tuple<int, CodecType>> {
252  protected:
253   void SetUp() override {
254     auto tup = GetParam();
255     uncompressedLength_ = uint64_t(1) << std::tr1::get<0>(tup);
256     codec_ = getCodec(std::tr1::get<1>(tup));
257   }
258
259   void runSimpleTest(const DataHolder& dh);
260
261   uint64_t uncompressedLength_;
262   std::unique_ptr<Codec> codec_;
263 };
264
265 inline uint64_t oneBasedMsbPos(uint64_t number) {
266   uint64_t pos = 0;
267   for (; number > 0; ++pos, number >>= 1) {
268   }
269   return pos;
270 }
271
272 void CompressionVarintTest::runSimpleTest(const DataHolder& dh) {
273   auto original = IOBuf::wrapBuffer(dh.data(uncompressedLength_));
274   auto compressed = codec_->compress(original.get());
275   auto breakPoint =
276       1UL +
277       Random::rand64(
278           std::max(uint64_t(9), oneBasedMsbPos(uncompressedLength_)) / 9UL);
279   auto tinyBuf = IOBuf::copyBuffer(compressed->data(),
280                                    std::min(compressed->length(), breakPoint));
281   compressed->trimStart(breakPoint);
282   tinyBuf->prependChain(std::move(compressed));
283   compressed = std::move(tinyBuf);
284
285   auto uncompressed = codec_->uncompress(compressed.get());
286
287   EXPECT_EQ(uncompressedLength_, uncompressed->computeChainDataLength());
288   EXPECT_EQ(dh.hash(uncompressedLength_), hashIOBuf(uncompressed.get()));
289 }
290
291 TEST_P(CompressionVarintTest, RandomData) {
292   runSimpleTest(randomDataHolder);
293 }
294
295 TEST_P(CompressionVarintTest, ConstantData) {
296   runSimpleTest(constantDataHolder);
297 }
298
299 INSTANTIATE_TEST_CASE_P(
300     CompressionVarintTest,
301     CompressionVarintTest,
302     testing::Combine(
303         testing::Values(0, 1, 12, 22, 25, 27),
304         testing::Values(
305             CodecType::LZ4_VARINT_SIZE,
306             CodecType::LZMA2_VARINT_SIZE)));
307
308 class CompressionCorruptionTest : public testing::TestWithParam<CodecType> {
309  protected:
310   void SetUp() override { codec_ = getCodec(GetParam()); }
311
312   void runSimpleTest(const DataHolder& dh);
313
314   std::unique_ptr<Codec> codec_;
315 };
316
317 void CompressionCorruptionTest::runSimpleTest(const DataHolder& dh) {
318   constexpr uint64_t uncompressedLength = 42;
319   auto original = IOBuf::wrapBuffer(dh.data(uncompressedLength));
320   auto compressed = codec_->compress(original.get());
321
322   if (!codec_->needsUncompressedLength()) {
323     auto uncompressed = codec_->uncompress(compressed.get());
324     EXPECT_EQ(uncompressedLength, uncompressed->computeChainDataLength());
325     EXPECT_EQ(dh.hash(uncompressedLength), hashIOBuf(uncompressed.get()));
326   }
327   {
328     auto uncompressed = codec_->uncompress(compressed.get(),
329                                            uncompressedLength);
330     EXPECT_EQ(uncompressedLength, uncompressed->computeChainDataLength());
331     EXPECT_EQ(dh.hash(uncompressedLength), hashIOBuf(uncompressed.get()));
332   }
333
334   EXPECT_THROW(codec_->uncompress(compressed.get(), uncompressedLength + 1),
335                std::runtime_error);
336
337   // Corrupt the first character
338   ++(compressed->writableData()[0]);
339
340   if (!codec_->needsUncompressedLength()) {
341     EXPECT_THROW(codec_->uncompress(compressed.get()),
342                  std::runtime_error);
343   }
344
345   EXPECT_THROW(codec_->uncompress(compressed.get(), uncompressedLength),
346                std::runtime_error);
347 }
348
349 TEST_P(CompressionCorruptionTest, RandomData) {
350   runSimpleTest(randomDataHolder);
351 }
352
353 TEST_P(CompressionCorruptionTest, ConstantData) {
354   runSimpleTest(constantDataHolder);
355 }
356
357 INSTANTIATE_TEST_CASE_P(
358     CompressionCorruptionTest,
359     CompressionCorruptionTest,
360     testing::Values(
361         // NO_COMPRESSION can't detect corruption
362         // LZ4 can't detect corruption reliably (sigh)
363         CodecType::SNAPPY,
364         CodecType::ZLIB));
365
366 }}}  // namespaces
367
368 int main(int argc, char *argv[]) {
369   testing::InitGoogleTest(&argc, argv);
370   gflags::ParseCommandLineFlags(&argc, &argv, true);
371
372   auto ret = RUN_ALL_TESTS();
373   if (!ret) {
374     folly::runBenchmarksOnFlag();
375   }
376   return ret;
377 }