Обновление контроллеров и хранилища
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
#include <controllers/anomaly_logs/get.h>
|
#include <controllers/anomaly_logs/get.h>
|
||||||
#include <data_models/anomaly_logs.h>
|
#include <data_models/anomaly_logs.h>
|
||||||
#include <storage/transaction.h>
|
#include <storage/storage.h>
|
||||||
#include <utils/utils.h>
|
#include <utils/utils.h>
|
||||||
|
|
||||||
#include "details/fields.h"
|
#include "details/fields.h"
|
||||||
@@ -12,13 +12,14 @@ json Get::operator()(const json& parameters) const {
|
|||||||
utils::CheckForRequiredFields(parameters, { fields::last_id });
|
utils::CheckForRequiredFields(parameters, { fields::last_id });
|
||||||
|
|
||||||
// Создаём транзакцию
|
// Создаём транзакцию
|
||||||
auto transaction = storage::Transaction::Create();
|
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||||
|
|
||||||
// Создаём модель
|
// Создаём модель
|
||||||
data_models::AnomalyLogsModel anomaly_logs_model(transaction);
|
data_models::AnomalyLogsModel anomaly_logs_model(transaction);
|
||||||
|
|
||||||
// Запрашиваем логи
|
// Запрашиваем логи
|
||||||
auto anomaly_logs = anomaly_logs_model.GetAll(parameters[fields::last_id]);
|
auto last_id = std::stoull(parameters[fields::last_id].get<std::string>());
|
||||||
|
auto anomaly_logs = anomaly_logs_model.GetAll(last_id);
|
||||||
|
|
||||||
// Формируем ответ
|
// Формируем ответ
|
||||||
json result = json::array();
|
json result = json::array();
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#include <controllers/anomaly_logs/update_cluster_id.h>
|
#include <controllers/anomaly_logs/update_cluster_id.h>
|
||||||
#include <data_models/anomaly_logs.h>
|
#include <data_models/anomaly_logs.h>
|
||||||
#include <storage/transaction.h>
|
#include <storage/storage.h>
|
||||||
#include <utils/utils.h>
|
#include <utils/utils.h>
|
||||||
|
|
||||||
#include "details/fields.h"
|
#include "details/fields.h"
|
||||||
@@ -12,7 +12,7 @@ json UpdateClusterId::operator()(const json& parameters) const {
|
|||||||
utils::CheckForRequiredFields(parameters, { fields::id, fields::cluster_id });
|
utils::CheckForRequiredFields(parameters, { fields::id, fields::cluster_id });
|
||||||
|
|
||||||
// Создаём транзакцию
|
// Создаём транзакцию
|
||||||
auto transaction = storage::Transaction::Create();
|
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||||
|
|
||||||
// Создаём модель
|
// Создаём модель
|
||||||
data_models::AnomalyLogsModel anomaly_logs_model(transaction);
|
data_models::AnomalyLogsModel anomaly_logs_model(transaction);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#include <controllers/logs_clusters/create.h>
|
#include <controllers/logs_clusters/create.h>
|
||||||
#include <data_models/logs_clusters.h>
|
#include <data_models/logs_clusters.h>
|
||||||
#include <storage/transaction.h>
|
#include <storage/storage.h>
|
||||||
#include <utils/utils.h>
|
#include <utils/utils.h>
|
||||||
|
|
||||||
#include "details/fields.h"
|
#include "details/fields.h"
|
||||||
@@ -12,7 +12,7 @@ json Create::operator()(const json& parameters) const {
|
|||||||
utils::CheckForRequiredFields(parameters, { fields::id, fields::name, fields::description, fields::recommendation });
|
utils::CheckForRequiredFields(parameters, { fields::id, fields::name, fields::description, fields::recommendation });
|
||||||
|
|
||||||
// Создаём транзакцию
|
// Создаём транзакцию
|
||||||
auto transaction = storage::Transaction::Create();
|
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||||
|
|
||||||
// Создаём модель
|
// Создаём модель
|
||||||
data_models::LogsClustersModel logs_clusters_model(transaction);
|
data_models::LogsClustersModel logs_clusters_model(transaction);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#include <controllers/logs_clusters/get.h>
|
#include <controllers/logs_clusters/get.h>
|
||||||
#include <data_models/logs_clusters.h>
|
#include <data_models/logs_clusters.h>
|
||||||
#include <storage/transaction.h>
|
#include <storage/storage.h>
|
||||||
|
|
||||||
#include "details/fields.h"
|
#include "details/fields.h"
|
||||||
|
|
||||||
@@ -8,7 +8,7 @@ using namespace controllers::logs_clusters;
|
|||||||
|
|
||||||
json Get::operator()(const json& parameters) const {
|
json Get::operator()(const json& parameters) const {
|
||||||
// Создаём транзакцию
|
// Создаём транзакцию
|
||||||
auto transaction = storage::Transaction::Create();
|
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||||
|
|
||||||
// Создаём модель
|
// Создаём модель
|
||||||
data_models::LogsClustersModel logs_clusters_model(transaction);
|
data_models::LogsClustersModel logs_clusters_model(transaction);
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
#include <controllers/statistics/get.h>
|
#include <controllers/statistics/get.h>
|
||||||
#include <data_models/statistics.h>
|
#include <data_models/statistics.h>
|
||||||
#include <storage/transaction.h>
|
#include <storage/storage.h>
|
||||||
|
|
||||||
using namespace controllers::statistics;
|
using namespace controllers::statistics;
|
||||||
|
|
||||||
json Get::operator()(const json& parameters) const {
|
json Get::operator()(const json& parameters) const {
|
||||||
// Создаём транзакцию
|
// Создаём транзакцию
|
||||||
auto transaction = storage::Transaction::Create();
|
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||||
|
|
||||||
// Создаём модель
|
// Создаём модель
|
||||||
data_models::StatisticsModel statistics_model(transaction);
|
data_models::StatisticsModel statistics_model(transaction);
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
#include <userver/server/handlers/http_handler_base.hpp>
|
#include <userver/server/handlers/http_handler_base.hpp>
|
||||||
|
|
||||||
|
#include <json/json.h>
|
||||||
|
|
||||||
#include "details.h"
|
#include "details.h"
|
||||||
#include "traits.h"
|
#include "traits.h"
|
||||||
|
|
||||||
@@ -23,7 +25,8 @@ namespace server::details {
|
|||||||
/// @param[in] context Контекст
|
/// @param[in] context Контекст
|
||||||
/// @returns Ответ
|
/// @returns Ответ
|
||||||
std::string HandleRequestThrow(const userver::server::http::HttpRequest& request, userver::server::request::RequestContext&) const override {
|
std::string HandleRequestThrow(const userver::server::http::HttpRequest& request, userver::server::request::RequestContext&) const override {
|
||||||
return server::details::HandleRequest(controller_, request.RequestBody());
|
auto request_body = server::details::GetRequestBody(request);
|
||||||
|
return server::details::HandleRequest(controller_, request_body);
|
||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -5,40 +5,42 @@
|
|||||||
|
|
||||||
#include "fields.h"
|
#include "fields.h"
|
||||||
|
|
||||||
namespace {
|
|
||||||
json HandleRequestImpl(const controllers::ControllerBase& controller, const std::string& request) {
|
|
||||||
using namespace server::details;
|
|
||||||
|
|
||||||
// Проверяем корректность формата запроса
|
|
||||||
auto json = ParseJson(request);
|
|
||||||
|
|
||||||
// Проверяем наличие необходимых ключей
|
|
||||||
utils::CheckForRequiredFields(json, { fields::parameters });
|
|
||||||
|
|
||||||
// Формируем и возвращаем ответ
|
|
||||||
auto parameters = json[fields::parameters];
|
|
||||||
return controller(parameters);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace server::details {
|
namespace server::details {
|
||||||
json ParseJson(const std::string& data) {
|
json ParseJson(const std::string& data) {
|
||||||
json json;
|
json json;
|
||||||
try {
|
try {
|
||||||
json = json::parse(data);
|
json = json::parse(data);
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
throw std::runtime_error("failed to parse request");
|
throw std::runtime_error("failed to parse json, details: " + std::string(e.what()));
|
||||||
}
|
}
|
||||||
|
|
||||||
return json;
|
return json;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string HandleRequest(const controllers::ControllerBase& controller, const std::string& request) {
|
json GetRequestBody(const userver::server::http::HttpRequest& request) {
|
||||||
Logger::Get().Write(LogLevel::Info, "accepted request '" + request + "'");
|
json body;
|
||||||
|
|
||||||
|
if (!request.RequestBody().empty() && request.RequestBody() != "null") {
|
||||||
|
body = json::parse(request.RequestBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto& argument_name : request.ArgNames()) {
|
||||||
|
if (body.contains(argument_name)) {
|
||||||
|
throw std::runtime_error("body already has parameter '" + argument_name + "'");
|
||||||
|
}
|
||||||
|
|
||||||
|
body[argument_name] = request.GetArg(argument_name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string HandleRequest(const controllers::ControllerBase& controller, const json& request) {
|
||||||
|
Logger::Get().Write(LogLevel::Info, "accepted request '" + request.dump() + "'");
|
||||||
|
|
||||||
json result;
|
json result;
|
||||||
try {
|
try {
|
||||||
result = HandleRequestImpl(controller, request);
|
result = controller(request);
|
||||||
}
|
}
|
||||||
catch (const std::exception& e) {
|
catch (const std::exception& e) {
|
||||||
json json;
|
json json;
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <userver/server/http/http_request.hpp>
|
||||||
|
|
||||||
#include <controllers/controller_base.h>
|
#include <controllers/controller_base.h>
|
||||||
|
#include <json/json.h>
|
||||||
|
|
||||||
namespace server::details {
|
namespace server::details {
|
||||||
/// @brief Парсинг строки в json
|
/// @brief Парсинг строки в json
|
||||||
@@ -7,9 +12,14 @@ namespace server::details {
|
|||||||
/// @returns json
|
/// @returns json
|
||||||
json ParseJson(const std::string& data);
|
json ParseJson(const std::string& data);
|
||||||
|
|
||||||
|
/// @brief Получение тела запроса
|
||||||
|
/// @param[in] request Запрос
|
||||||
|
/// @returns Тело запроса
|
||||||
|
json GetRequestBody(const userver::server::http::HttpRequest& request);
|
||||||
|
|
||||||
/// @brief Обработка запроса
|
/// @brief Обработка запроса
|
||||||
/// @param[in] controller Контроллер
|
/// @param[in] controller Контроллер
|
||||||
/// @param[in] request Запрос
|
/// @param[in] request Запрос
|
||||||
/// @returns Ответ
|
/// @returns Ответ
|
||||||
std::string HandleRequest(const controllers::ControllerBase& controller, const std::string& request);
|
std::string HandleRequest(const controllers::ControllerBase& controller, const json& request);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ StorageWrapper::StorageWrapper(const userver::components::ComponentConfig& confi
|
|||||||
connection_data.host = config["host"].As<std::string>();
|
connection_data.host = config["host"].As<std::string>();
|
||||||
connection_data.port = config["port"].As<std::string>();
|
connection_data.port = config["port"].As<std::string>();
|
||||||
|
|
||||||
storage::Storage::Connect(connection_data);
|
storage::Storage::Get().Connect(connection_data);
|
||||||
}
|
}
|
||||||
|
|
||||||
userver::yaml_config::Schema StorageWrapper::GetStaticConfigSchema() {
|
userver::yaml_config::Schema StorageWrapper::GetStaticConfigSchema() {
|
||||||
|
|||||||
@@ -3,8 +3,6 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
#include <pqxx/pqxx>
|
|
||||||
|
|
||||||
#include <storage/transaction.h>
|
#include <storage/transaction.h>
|
||||||
|
|
||||||
namespace storage {
|
namespace storage {
|
||||||
@@ -22,11 +20,13 @@ namespace storage {
|
|||||||
|
|
||||||
/// @brief Подключение к хранилищу
|
/// @brief Подключение к хранилищу
|
||||||
/// @param[in] connection_data Данных подключения
|
/// @param[in] connection_data Данных подключения
|
||||||
static void Connect(const ConnectionData& connection_data);
|
void Connect(const ConnectionData& connection_data);
|
||||||
|
|
||||||
friend class Transaction;
|
/// @brief Создание транзацкии
|
||||||
|
/// @returns Транзакция
|
||||||
|
Transaction CreateTransaction();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::unique_ptr<pqxx::connection> connection_; ///< Соединение
|
std::string connection_data_; ///< Данные подключения
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
#include <pqxx/pqxx>
|
#include <pqxx/pqxx>
|
||||||
|
|
||||||
@@ -8,6 +9,9 @@ namespace storage {
|
|||||||
/// @brief Транзакция
|
/// @brief Транзакция
|
||||||
class Transaction {
|
class Transaction {
|
||||||
public:
|
public:
|
||||||
|
/// @brief Конструктор
|
||||||
|
Transaction(const std::string& connection_data);
|
||||||
|
|
||||||
/// @brief Деструктор
|
/// @brief Деструктор
|
||||||
~Transaction();
|
~Transaction();
|
||||||
|
|
||||||
@@ -17,21 +21,13 @@ namespace storage {
|
|||||||
/// @brief Оператор перемещающего присваивания
|
/// @brief Оператор перемещающего присваивания
|
||||||
Transaction& operator=(Transaction&&) = default;
|
Transaction& operator=(Transaction&&) = default;
|
||||||
|
|
||||||
/// @brief Создание транзацкии
|
|
||||||
/// @pre Должно быть установлено соединение с хранилищем
|
|
||||||
/// @returns Транзакция
|
|
||||||
static Transaction Create();
|
|
||||||
|
|
||||||
/// @brief Выполнение запроса
|
/// @brief Выполнение запроса
|
||||||
/// @param[in] query Запрос
|
/// @param[in] query Запрос
|
||||||
/// @returns Результат выполнения
|
/// @returns Результат выполнения
|
||||||
pqxx::result Do(std::string_view query) const;
|
pqxx::result Do(std::string_view query) const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
/// @brief Конструктор
|
std::unique_ptr<pqxx::connection> connection_; ///< Соединение
|
||||||
Transaction() = default;
|
|
||||||
|
|
||||||
private:
|
|
||||||
std::unique_ptr<pqxx::work> transaction_; ///< Транзакция
|
std::unique_ptr<pqxx::work> transaction_; ///< Транзакция
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,12 +10,16 @@ Storage& Storage::Get() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Storage::Connect(const ConnectionData& connection_data) {
|
void Storage::Connect(const ConnectionData& connection_data) {
|
||||||
std::ostringstream options;
|
std::ostringstream connection;
|
||||||
options << "dbname = " << connection_data.database
|
connection << "dbname = " << connection_data.database
|
||||||
<< " user = " << connection_data.username
|
<< " user = " << connection_data.username
|
||||||
<< " password = " << connection_data.password
|
<< " password = " << connection_data.password
|
||||||
<< " host = " << connection_data.host
|
<< " host = " << connection_data.host
|
||||||
<< " port = " << connection_data.port;
|
<< " port = " << connection_data.port;
|
||||||
|
|
||||||
Get().connection_ = std::make_unique<pqxx::connection>(options.str());
|
connection_data_ = connection.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
Transaction Storage::CreateTransaction() {
|
||||||
|
return { connection_data_ };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,20 @@
|
|||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
#include <storage/storage.h>
|
|
||||||
#include <storage/transaction.h>
|
#include <storage/transaction.h>
|
||||||
|
|
||||||
using namespace storage;
|
using namespace storage;
|
||||||
|
|
||||||
|
Transaction::Transaction(const std::string& connection_data)
|
||||||
|
: connection_(std::make_unique<pqxx::connection>(connection_data))
|
||||||
|
, transaction_(std::make_unique<pqxx::work>(*connection_)) {}
|
||||||
|
|
||||||
Transaction::~Transaction() {
|
Transaction::~Transaction() {
|
||||||
transaction_->commit();
|
if (connection_ && transaction_) {
|
||||||
}
|
transaction_->commit();
|
||||||
|
connection_->close();
|
||||||
Transaction Transaction::Create() {
|
}
|
||||||
auto& storage = storage::Storage::Get();
|
|
||||||
|
|
||||||
Transaction transaction;
|
|
||||||
transaction.transaction_ = std::make_unique<pqxx::work>(*storage.connection_);
|
|
||||||
|
|
||||||
return transaction;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pqxx::result Transaction::Do(std::string_view query) const {
|
pqxx::result Transaction::Do(std::string_view query) const {
|
||||||
return transaction_->exec(query);
|
return transaction_->exec(query);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user