refactor: Return row id in IStore::retrieve_one
This is a prerequisite to synchronizing security ids stored via IDGenerator (the "new" way to store ids, added when we implemented Deribit), and SecurityDB (the original way from spark days). The problem was that these 2 implementations were using separate databases. We need to unify the interfaces between these storage services to avoid breaking existing code.
This commit is contained in:
1 parent
cb187e6997
commit
bd8c97244a
28 files changed
+719
-566
No files matched your search
@@ -1,19 +1,25 @@
|
||||
#ifndef _WIN32
|
||||
#include "SecurityIDRecorder.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/persistence/IStore.h"
|
||||
#include "lib/persistence/SqliteStore.h"
|
||||
#include <boost/pool/object_pool.hpp>
|
||||
|
||||
#include "lib/config/config.h"
|
||||
#include "lib/logging/logging.h"
|
||||
#include "lib/utils/Sqlite_utils.h"
|
||||
#include "lib/utils/checked_arithmetic.h"
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <tbb/concurrent_queue.h>
|
||||
|
||||
#include "lib/config/protos/market_data.pb.h"
|
||||
#include "lib/config/protos/system_config.pb.h"
|
||||
|
||||
#include <memory>
|
||||
#include <sqlite/sqlite3.h>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <tbb/concurrent_queue.h>
|
||||
|
||||
using namespace std;
|
||||
using namespace bts::utils;
|
||||
@@ -26,9 +32,32 @@ using bts::api::Security;
|
||||
using bts::api::SecurityType;
|
||||
using bts::api::Venue;
|
||||
using bts::config::SystemConfig;
|
||||
using bts::persistence::IStore;
|
||||
using bts::persistence::SqliteStore;
|
||||
|
||||
uint64_t exchange_id(const api::Security &security);
|
||||
|
||||
static std::unique_ptr<IStore> get_default_store() {
|
||||
return std::make_unique<SqliteStore>("key_ids");
|
||||
}
|
||||
|
||||
static persistence::StoreRow get_row(
|
||||
Venue venue,
|
||||
SecurityType type,
|
||||
const std::string &name,
|
||||
const std::string &prefix = "") {
|
||||
return persistence::StoreRow{
|
||||
fmt::format(
|
||||
"{}{}.{}", std::string{prefix}, Venue_Name(venue).substr(6),
|
||||
SecurityType_Name(type).substr(13)),
|
||||
name, ""};
|
||||
}
|
||||
|
||||
static persistence::StoreRow get_row(
|
||||
const api::Security &s, const std::string &prefix = "") {
|
||||
return get_row(s.exchange(), bts::securities::security_type(s), prefix);
|
||||
}
|
||||
|
||||
struct SecurityIdRequest {
|
||||
Venue venue;
|
||||
SecurityType type;
|
||||
@@ -38,14 +67,16 @@ struct SecurityIdRequest {
|
||||
};
|
||||
|
||||
struct SecurityIDRecorderState {
|
||||
SecurityIDRecorderState(SecurityIDRecorderParams &p)
|
||||
: pending_handle(), thread_id(), db(nullptr, sqlite3_close), timer(),
|
||||
lookup_key(p.lookup_key), unresolved_legs() {}
|
||||
SecurityIDRecorderState(
|
||||
std::unique_ptr<IStore> store, KeyLookupOption lookup_key)
|
||||
: store(store == nullptr ? get_default_store() : std::move(store)),
|
||||
pending_handle(), thread_id(), timer(), lookup_key(lookup_key),
|
||||
unresolved_legs() {}
|
||||
|
||||
std::unique_ptr<IStore> store{nullptr};
|
||||
tbb::concurrent_queue<std::shared_ptr<SecurityIdRequest>> id_request_queue;
|
||||
tbb::concurrent_queue<MDProducerHandle> pending_handle;
|
||||
std::thread::id thread_id;
|
||||
sqlite3_ptr db;
|
||||
unique_ptr<DispatcherTimer> timer;
|
||||
|
||||
KeyLookupOption lookup_key;
|
||||
@@ -81,46 +112,28 @@ struct SecurityIDRecorderState {
|
||||
|
||||
void check_access() { bts_assert(thread_id == std::this_thread::get_id()); }
|
||||
void add_unresolved_spread(MDProducerHandle &handle);
|
||||
security_key search(const std::string &descriptor);
|
||||
security_key insert(const std::string &descriptor, SecurityType);
|
||||
security_key search(const persistence::StoreRow &row);
|
||||
security_key insert(const persistence::StoreRow &row);
|
||||
};
|
||||
|
||||
SecurityIDRecorder::SecurityIDRecorder(SecurityIDRecorderParams params)
|
||||
: _self(new SecurityIDRecorderState(params)) {
|
||||
if (params.db) {
|
||||
_self->db = std::move(params.db);
|
||||
}
|
||||
SecurityIDRecorder::SecurityIDRecorder(
|
||||
std::unique_ptr<persistence::IStore> store,
|
||||
KeyLookupOption lookup_key,
|
||||
utils::Dispatcher *dispatcher)
|
||||
: _self(std::make_unique<SecurityIDRecorderState>(
|
||||
store == nullptr
|
||||
? std::make_unique<persistence::SqliteStore>("key_ids")
|
||||
: std::move(store),
|
||||
lookup_key)) {
|
||||
init();
|
||||
if (params.dispatcher) {
|
||||
_self->run(*params.dispatcher);
|
||||
if (dispatcher != nullptr) {
|
||||
_self->run(*dispatcher);
|
||||
}
|
||||
}
|
||||
|
||||
SecurityIDRecorder::~SecurityIDRecorder() {}
|
||||
|
||||
void SecurityIDRecorder::init() {
|
||||
LOG(md, Info, "SecurityIDRecorder::init");
|
||||
string db_dir =
|
||||
config::get<config::SystemConfig>().data_path() + "databases/md/";
|
||||
string db_path = db_dir + "/security_keys.sqlite";
|
||||
|
||||
if (!boost::filesystem::exists(db_dir)) {
|
||||
boost::filesystem::create_directories(db_dir);
|
||||
}
|
||||
|
||||
if (!_self->db) {
|
||||
_self->db = sqlite::open_db(db_path.c_str());
|
||||
bts_assert(_self->db);
|
||||
}
|
||||
|
||||
// Set a long busy timeout
|
||||
sqlite3_busy_timeout(_self->db.get(), 9999);
|
||||
sqlite::exec_nofail(_self->db, "PRAGMA journal_mode=WAL");
|
||||
sqlite::exec_nofail(_self->db, "PRAGMA syncronous=0");
|
||||
sqlite::exec_nofail(
|
||||
_self->db, "CREATE TABLE IF NOT EXISTS store (descriptor STRING "
|
||||
"NOT NULL PRIMARY KEY, type int);");
|
||||
}
|
||||
void SecurityIDRecorder::init() {}
|
||||
|
||||
void SecurityIDRecorder::ensure_key(MDProducerHandle handle) {
|
||||
LOG(md, Info, "SecurityIDRecorder::ensure_key desc: {} key: {} num_id: {}",
|
||||
@@ -134,7 +147,7 @@ void SecurityIDRecorder::assign_key(
|
||||
assign_key(
|
||||
security.exchange(), bts::securities::security_type(security),
|
||||
bts::securities::descriptor(security),
|
||||
[&callback, msec = security](
|
||||
[callback, msec = security](
|
||||
api::Venue, api::SecurityType, const std::string &,
|
||||
uint32_t id) mutable {
|
||||
msec.set_id(id);
|
||||
@@ -269,27 +282,25 @@ void SecurityIDRecorderState::work_db() {
|
||||
// SPARK-1446 Need to try to add existing securities to the db in case we
|
||||
// deleted them by hand
|
||||
vector<std::shared_ptr<SecurityIdRequest>> existing_securities;
|
||||
vector<std::shared_ptr<SecurityIdRequest>> defer;
|
||||
vector<string> new_descriptors;
|
||||
vector<persistence::StoreRow> new_rows;
|
||||
size_t count = 0;
|
||||
string descriptor;
|
||||
while (id_request_queue.try_pop(temp)) {
|
||||
descriptor = temp->name;
|
||||
|
||||
// If we're unable to create a descriptor try again later
|
||||
if (descriptor == "") {
|
||||
defer.push_back(std::move(temp));
|
||||
continue;
|
||||
security_key key = invalid_security_key;
|
||||
auto row = get_row(temp->venue, temp->type, temp->name);
|
||||
try {
|
||||
key = search(row);
|
||||
} catch (const std::overflow_error &ex) {
|
||||
LOG(persist, Error,
|
||||
"SecurityIDRecorderState::work_db. Row search threw ex: {}",
|
||||
std::string{ex.what()});
|
||||
}
|
||||
|
||||
security_key key = search(descriptor);
|
||||
if (key != invalid_security_key) {
|
||||
temp->callback(temp->venue, temp->type, temp->name, key);
|
||||
existing_securities.push_back(std::move(temp));
|
||||
} else {
|
||||
// always push in parallel
|
||||
new_entries.push_back(std::make_pair(key, std::move(temp)));
|
||||
new_descriptors.push_back(descriptor);
|
||||
new_rows.push_back(std::move(row));
|
||||
++count;
|
||||
// Limit the amount of time we spend writing to sqlite during startup
|
||||
// to avoid blocking the heartbeat
|
||||
@@ -299,22 +310,14 @@ void SecurityIDRecorderState::work_db() {
|
||||
}
|
||||
}
|
||||
|
||||
for (auto &d : defer) {
|
||||
LOG(md, Info, "SecurityIDRecorderState::work_db work.push d: {}",
|
||||
d->name);
|
||||
id_request_queue.push(std::move(d));
|
||||
}
|
||||
|
||||
if (!new_entries.empty()) {
|
||||
sqlite::exec_nofail(db.get(), "BEGIN TRANSACTION");
|
||||
|
||||
store->insert_many_resolve_ids(new_rows);
|
||||
for (size_t x = 0; x < new_entries.size(); ++x) {
|
||||
auto &entry = new_entries[x];
|
||||
entry.first = insert(new_descriptors[x], entry.second->type);
|
||||
auto &row = new_rows[x];
|
||||
entry.first = row.id;
|
||||
bts_assert_d(entry.first != invalid_security_key);
|
||||
}
|
||||
|
||||
sqlite::exec_nofail(db.get(), "COMMIT TRANSACTION");
|
||||
}
|
||||
|
||||
if (!new_entries.empty()) {
|
||||
@@ -327,65 +330,27 @@ void SecurityIDRecorderState::work_db() {
|
||||
|
||||
void SecurityIDRecorder::bulk_insert(
|
||||
const std::vector<const api::Security *> &data, const char *prefix) {
|
||||
LOG(md, Info, "SecurityIDRecorder::bulk_insert size: {}", data.size());
|
||||
if (data.size() == 0)
|
||||
return;
|
||||
sqlite::exec_nofail(_self->db.get(), "BEGIN TRANSACTION");
|
||||
std::string descriptor;
|
||||
{
|
||||
auto insert_stmt = sqlite::prepare_query(
|
||||
_self->db, "INSERT INTO security_keys (rowid, descriptor, type) "
|
||||
"values (?, ?, ?)");
|
||||
for (const api::Security *sec : data) {
|
||||
descriptor = prefix + bts::securities::unique_descriptor(*sec);
|
||||
auto type = securitytype_of(*sec);
|
||||
|
||||
sqlite3_bind_int(insert_stmt.get(), 1, sec->id());
|
||||
sqlite3_bind_text(
|
||||
insert_stmt.get(), 2, descriptor.c_str(), descriptor.size(),
|
||||
SQLITE_STATIC);
|
||||
sqlite3_bind_int(insert_stmt.get(), 3, (int)type);
|
||||
sqlite3_step(insert_stmt.get());
|
||||
sqlite3_reset(insert_stmt.get());
|
||||
}
|
||||
std::vector<persistence::StoreRow> rows;
|
||||
rows.reserve(data.size());
|
||||
for (const auto *s : data) {
|
||||
rows.push_back(get_row(*s, prefix));
|
||||
}
|
||||
sqlite::exec_nofail(_self->db.get(), "COMMIT TRANSACTION");
|
||||
_self->store->insert_many_resolve_ids(rows);
|
||||
}
|
||||
|
||||
security_key SecurityIDRecorderState::search(const std::string &descriptor) {
|
||||
LOG(md, Info, "SecurityIDRecorderState::search descriptor: {}", descriptor);
|
||||
auto select_stmt = sqlite::prepare_query(
|
||||
db, "SELECT rowid from security_keys where descriptor=? LIMIT 1;");
|
||||
sqlite3_bind_text(
|
||||
select_stmt.get(), 1, descriptor.c_str(), descriptor.size(),
|
||||
SQLITE_STATIC);
|
||||
int result = sqlite3_step(select_stmt.get());
|
||||
if (result == SQLITE_DONE || result == SQLITE_ROW) {
|
||||
return sqlite3_column_int(select_stmt.get(), 0);
|
||||
security_key SecurityIDRecorderState::search(const persistence::StoreRow &row) {
|
||||
auto [exists, rowid, val] = store->retrieve_one(row.ns, row.key);
|
||||
if (exists) {
|
||||
if (!val.empty()) {
|
||||
bts_assert(stol(val) == rowid);
|
||||
}
|
||||
return system::math::checked_ltou(rowid);
|
||||
}
|
||||
return invalid_security_key;
|
||||
}
|
||||
|
||||
security_key SecurityIDRecorderState::insert(
|
||||
const std::string &descriptor, SecurityType type) {
|
||||
LOG(md, Info, "SecurityIDRecorderState::insert descriptor: {}", descriptor);
|
||||
auto insert_stmt = sqlite::prepare_query(
|
||||
db, "INSERT INTO security_keys (descriptor, type) values (?, ?)");
|
||||
sqlite3_bind_text(
|
||||
insert_stmt.get(), 1, descriptor.c_str(), descriptor.size(),
|
||||
SQLITE_STATIC);
|
||||
sqlite3_bind_int(insert_stmt.get(), 2, (int)type);
|
||||
int result = sqlite3_step(insert_stmt.get());
|
||||
if (result == SQLITE_DONE || result == SQLITE_ROW) {
|
||||
return sqlite3_last_insert_rowid(db.get());
|
||||
}
|
||||
// Just in case our insert failed due to duplicate row
|
||||
auto key = search(descriptor);
|
||||
if (key == invalid_security_key) {
|
||||
LOG(md, Error, "Failed to assign security key. SQLite return code: {}",
|
||||
result);
|
||||
}
|
||||
return key;
|
||||
security_key SecurityIDRecorderState::insert(const persistence::StoreRow &row) {
|
||||
return store->insert(row.ns, row.key, row.value);
|
||||
}
|
||||
|
||||
} // namespace md
|
||||
|
||||
Reference in new issue
Block a user