summaryrefslogtreecommitdiff
path: root/src/core/CacheEntry.cpp
blob: fb1c1e3c18dfb21ce5628da0c100d1ee0168c41c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright (C) 2022-2023 Joel Rosdahl and other contributors
//
// See doc/AUTHORS.adoc for a complete list of contributors.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

#include "CacheEntry.hpp"

#include <Logging.hpp>
#include <ccache.hpp>
#include <core/CacheEntryDataReader.hpp>
#include <core/CacheEntryDataWriter.hpp>
#include <core/Result.hpp>
#include <core/exceptions.hpp>
#include <core/types.hpp>
#include <fmtmacros.hpp>
#include <util/TimePoint.hpp>
#include <util/expected.hpp>
#include <util/file.hpp>
#include <util/zstd.hpp>

#include <cstring>

namespace {

const size_t k_static_header_fields_size =
  sizeof(core::CacheEntry::Header::magic)
  + sizeof(core::CacheEntry::Header::entry_format_version)
  + sizeof(core::CacheEntry::Header::entry_type)
  + sizeof(core::CacheEntry::Header::compression_type)
  + sizeof(core::CacheEntry::Header::compression_level)
  + sizeof(core::CacheEntry::Header::self_contained)
  + sizeof(core::CacheEntry::Header::creation_time)
  + sizeof(core::CacheEntry::Header::entry_size)
  // ccache_version length field:
  + 1
  // namespace_ length field:
  + 1;

const size_t k_epilogue_fields_size = sizeof(uint64_t) + sizeof(uint64_t);

core::CacheEntryType
cache_entry_type_from_int(const uint8_t entry_type)
{
  switch (entry_type) {
  case 0:
    return core::CacheEntryType::result;
    break;
  case 1:
    return core::CacheEntryType::manifest;
    break;
  default:
    throw core::Error(FMT("Unknown entry type: {}", entry_type));
  }
}

} // namespace

namespace core {

// Version 0:
//   - First version.
// Version 1:
//   - Added self_contained field.
//   - The checksum is now for the (potentially) compressed payload instead of
//     the uncompressed payload, and the checksum is now always stored
//     uncompressed.
const uint8_t CacheEntry::k_format_version = 1;

CacheEntry::Header::Header(const Config& config,
                           core::CacheEntryType entry_type_)
  : magic(k_ccache_magic),
    entry_format_version(k_format_version),
    entry_type(entry_type_),
    compression_type(compression_type_from_config(config)),
    compression_level(compression_level_from_config(config)),
    self_contained(entry_type != CacheEntryType::result
                   || !core::Result::Serializer::use_raw_files(config)),
    creation_time(util::TimePoint::now().sec()),
    ccache_version(CCACHE_VERSION),
    namespace_(config.namespace_()),
    entry_size(0)
{
  if (compression_level == 0) {
    compression_level = default_compression_level;
    LOG("Using default compression level {}", compression_level);
  }
}

CacheEntry::Header::Header(nonstd::span<const uint8_t> data)
{
  parse(data);
}

CacheEntry::Header::Header(const std::string& path)
{
  const auto data = util::read_file_part<util::Bytes>(path, 0, 1000);
  if (!data) {
    throw core::Error(data.error());
  }
  parse(*data);
}

std::string
CacheEntry::Header::inspect() const
{
  std::string result;
  result += FMT("Magic: {:04x}\n", magic);
  result += FMT("Entry format version: {}\n", entry_format_version);
  result += FMT("Entry type: {} ({})\n",
                static_cast<uint8_t>(entry_type),
                to_string(entry_type));
  result += FMT("Compression type: {}\n", to_string(compression_type));
  result += FMT("Compression level: {}\n", compression_level);
  result += FMT("Self-contained: {}\n", self_contained ? "yes" : "no");
  result += FMT("Creation time: {}\n", creation_time);
  result += FMT("Ccache version: {}\n", ccache_version);
  result += FMT("Namespace: {}\n", namespace_);
  result += FMT("Entry size: {}\n", entry_size);
  return result;
}

void
CacheEntry::Header::parse(nonstd::span<const uint8_t> data)
{
  CacheEntryDataReader reader(data);
  reader.read_int(magic);
  if (magic != core::k_ccache_magic) {
    throw core::Error(FMT("Bad magic value: 0x{:04x}", magic));
  }

  reader.read_int(entry_format_version);
  if (entry_format_version != k_format_version) {
    throw core::Error(
      FMT("Unknown entry format version: {}", entry_format_version));
  }

  entry_type = cache_entry_type_from_int(reader.read_int<uint8_t>());
  compression_type = compression_type_from_int(reader.read_int<uint8_t>());
  reader.read_int(compression_level);
  self_contained = bool(reader.read_int<uint8_t>());
  reader.read_int(creation_time);
  ccache_version = reader.read_str(reader.read_int<uint8_t>());
  namespace_ = reader.read_str(reader.read_int<uint8_t>());
  reader.read_int(entry_size);
}

size_t
CacheEntry::Header::serialized_size() const
{
  return k_static_header_fields_size + ccache_version.length()
         + namespace_.length();
}

void
CacheEntry::Header::serialize(util::Bytes& output) const
{
  core::CacheEntryDataWriter writer(output);
  writer.write_int(magic);
  writer.write_int(entry_format_version);
  writer.write_int(static_cast<uint8_t>(entry_type));
  writer.write_int(static_cast<uint8_t>(compression_type));
  writer.write_int(compression_level);
  writer.write_int<uint8_t>(self_contained);
  writer.write_int(creation_time);
  writer.write_int<uint8_t>(ccache_version.length());
  writer.write_str(ccache_version);
  writer.write_int<uint8_t>(namespace_.length());
  writer.write_str(namespace_);
  writer.write_int(entry_size);
}

uint32_t
CacheEntry::Header::uncompressed_payload_size() const
{
  return entry_size - serialized_size() - k_epilogue_fields_size;
}

CacheEntry::CacheEntry(nonstd::span<const uint8_t> data) : m_header(data)
{
  const size_t non_payload_size =
    m_header.serialized_size() + k_epilogue_fields_size;
  if (data.size() <= non_payload_size) {
    throw core::Error("CacheEntry data underflow");
  }
  m_payload =
    data.subspan(m_header.serialized_size(), data.size() - non_payload_size);
  m_checksum = data.last(k_epilogue_fields_size);

  switch (m_header.compression_type) {
  case CompressionType::none:
    break;

  case CompressionType::zstd:
    m_uncompressed_payload.reserve(m_header.uncompressed_payload_size());
    util::throw_on_error<core::Error>(
      util::zstd_decompress(
        m_payload, m_uncompressed_payload, m_uncompressed_payload.capacity()),
      "Cache entry payload decompression error: ");

    break;
  }
}

void
CacheEntry::verify_checksum() const
{
  util::Bytes header_data;
  m_header.serialize(header_data);

  util::XXH3_128 checksum;
  checksum.update(header_data);
  checksum.update(m_payload);
  const auto actual = checksum.digest();

  if (actual != m_checksum) {
    throw core::Error(
      FMT("Incorrect checksum (actual {}, expected {})",
          Util::format_base16(actual.data(), actual.size()),
          Util::format_base16(m_checksum.data(), m_checksum.size())));
  }
}

const CacheEntry::Header&
CacheEntry::header() const
{
  return m_header;
}

nonstd::span<const uint8_t>
CacheEntry::payload() const
{
  return m_header.compression_type == CompressionType::none
           ? m_payload
           : nonstd::span<const uint8_t>(m_uncompressed_payload);
}

util::Bytes
CacheEntry::serialize(const CacheEntry::Header& header,
                      Serializer& payload_serializer)
{
  return do_serialize(
    header,
    payload_serializer.serialized_size(),
    [&payload_serializer](util::Bytes& result, const CacheEntry::Header& hdr) {
      switch (hdr.compression_type) {
      case CompressionType::none:
        payload_serializer.serialize(result);
        break;

      case CompressionType::zstd:
        util::Bytes payload;
        payload_serializer.serialize(payload);
        util::throw_on_error<core::Error>(
          util::zstd_compress(payload, result, hdr.compression_level),
          "Cache entry payload compression error: ");
        break;
      }
    });
}

util::Bytes
CacheEntry::serialize(const CacheEntry::Header& header,
                      nonstd::span<const uint8_t> payload)
{
  return do_serialize(
    header,
    payload.size(),
    [&payload](util::Bytes& result, const CacheEntry::Header& hdr) {
      switch (hdr.compression_type) {
      case CompressionType::none:
        result.insert(result.end(), payload.begin(), payload.end());
        break;

      case CompressionType::zstd:
        util::throw_on_error<core::Error>(
          util::zstd_compress(payload, result, hdr.compression_level),
          "Cache entry payload compression error: ");
        break;
      }
    });
}

util::Bytes
CacheEntry::do_serialize(
  const CacheEntry::Header& header,
  size_t serialized_payload_size,
  std::function<void(util::Bytes& result, const Header& hdr)> serialize_payload)
{
  CacheEntry::Header hdr(header);
  const size_t non_payload_size =
    hdr.serialized_size() + k_epilogue_fields_size;
  hdr.entry_size = non_payload_size + serialized_payload_size;

  if (hdr.compression_type == CompressionType::zstd) {
    const auto [level, explanation] =
      util::zstd_supported_compression_level(hdr.compression_level);
    if (!explanation.empty()) {
      LOG("Using ZSTD compression level {} ({}) instead of {}",
          level,
          explanation,
          hdr.compression_level);
    }
    hdr.compression_level = level;
  }

  const size_t max_serialized_size =
    hdr.compression_type == CompressionType::zstd
      ? (non_payload_size + util::zstd_compress_bound(serialized_payload_size))
      : hdr.entry_size;
  util::Bytes result;
  result.reserve(max_serialized_size);

  hdr.serialize(result);
  serialize_payload(result, hdr);

  util::XXH3_128 checksum;
  checksum.update(result);
  const auto digest = checksum.digest();
  result.insert(result.end(), digest.begin(), digest.end());

  return result;
}

} // namespace core