bool FilePersistenceLayer::persist()

in wangle/client/persistence/FilePersistenceLayer.cpp [27:63]


bool FilePersistenceLayer::persist(const folly::dynamic& dynObj) noexcept {
  std::string serializedCache;
  try {
    folly::json::serialization_opts opts;
    opts.allow_non_string_keys = true;
    serializedCache = folly::json::serialize(dynObj, opts);
  } catch (...) {
    LOG(ERROR) << "Serializing to JSON failed with error: "
               << folly::exceptionStr(std::current_exception());
    return false;
  }
  bool persisted = false;
  const auto fd =
      folly::openNoInt(file_.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
  if (fd == -1) {
    return false;
  }
  const auto nWritten =
      folly::writeFull(fd, serializedCache.data(), serializedCache.size());
  persisted = nWritten >= 0 &&
      (static_cast<size_t>(nWritten) == serializedCache.size());
  if (!persisted) {
    LOG(ERROR) << "Failed to write to " << file_ << ":";
    if (nWritten == -1) {
      LOG(ERROR) << "write failed with errno " << errno;
    }
  }
  if (folly::fdatasyncNoInt(fd) != 0) {
    LOG(ERROR) << "Failed to sync " << file_ << ": errno " << errno;
    persisted = false;
  }
  if (folly::closeNoInt(fd) != 0) {
    LOG(ERROR) << "Failed to close " << file_ << ": errno " << errno;
    persisted = false;
  }
  return persisted;
}