blob: 0a3962fb98fabf9d4e80fe8de9fca2f9c948148e [file] [log] [blame]
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/logger/observation_writer.h"
#include <memory>
#include <utility>
#include "src/logging.h"
#include "src/observation_store/observation_store.h"
#include "src/pb/observation.pb.h"
#include "src/tracing.h"
namespace cobalt::logger {
using ::cobalt::observation_store::ObservationStoreWriterInterface;
using observation_store::ObservationStore;
void ObservationWriter::AddRandomId(Observation* observation) const {
static const size_t kNumRandomBytes = 8;
observation->set_allocated_random_id(new std::string(kNumRandomBytes, 0));
random_.RandomString(observation->mutable_random_id());
}
Status ObservationWriter::WriteObservation(const std::unique_ptr<Observation>& observation,
std::unique_ptr<ObservationMetadata> metadata,
bool is_contribution) const {
TRACE_DURATION("cobalt_core", "ObservationWriter::WriteObservation");
AddRandomId(observation.get());
ObservationStore::StoreStatus store_status;
if (observation_encrypter_) {
auto encrypted_observation = std::make_unique<EncryptedMessage>();
if (!observation_encrypter_->Encrypt(*observation, encrypted_observation.get())) {
LOG(ERROR) << "Encryption of an Observation failed.";
return kOther;
}
store_status = observation_store_->StoreObservation(std::move(encrypted_observation),
std::move(metadata), is_contribution);
} else {
// Make a copy of |observation| to add to the store.
store_status = observation_store_->StoreObservation(std::make_unique<Observation>(*observation),
std::move(metadata), is_contribution);
}
if (store_status != ObservationStoreWriterInterface::kOk) {
LOG_FIRST_N(ERROR, 10) << "ObservationStore::StoreObservation() failed with status "
<< store_status;
return kOther;
}
if (update_recipient_) {
update_recipient_->NotifyObservationsAdded();
}
return kOK;
}
} // namespace cobalt::logger