This allows natural synopsis policies like cache all or cache N to be overlayed on top of the event without affecting the event members.
97 lines
2.7 KiB
C++
97 lines
2.7 KiB
C++
#include "SecuritySrc.h"
|
|
#include "server/sparkd/orderman2/events/NewSecuritiesEvent.h"
|
|
#include "server/sparkd/mercury/events/PollEvent.h"
|
|
#include "server/sparkd/persistence/SqliteStore.h"
|
|
#include "server/sparkd/mercury/events/TimerEvent.h"
|
|
#include "lib/md/MDRecoverableConsumer.h"
|
|
#include "lib/utils/bts_chrono.h"
|
|
|
|
#include <unordered_map>
|
|
|
|
namespace bts {
|
|
namespace orderman2 {
|
|
|
|
auto const sec_ns = "securities";
|
|
|
|
struct SecuritySrc::PImpl
|
|
{
|
|
PImpl() :
|
|
store(new persistence::SqliteStore("securities")),
|
|
md_consumer(),
|
|
known_securities(),
|
|
last_scan(),
|
|
new_securities_stream ()
|
|
{}
|
|
|
|
std::unique_ptr<persistence::IStore> store;
|
|
md::MDRecoverableConsumer md_consumer;
|
|
std::unordered_map<SecurityKey::Value,std::unique_ptr<api::Security>> known_securities;
|
|
TimeStamp last_scan;
|
|
mercury::Stream<NewSecuritiesEvent> new_securities_stream;
|
|
std::vector<const api::Security*> to_publish;
|
|
};
|
|
|
|
SecuritySrc::SecuritySrc () : me (new PImpl()) {}
|
|
SecuritySrc::~SecuritySrc(){}
|
|
|
|
void SecuritySrc::init()
|
|
{
|
|
auto all = me->store->retrieve_all()[sec_ns];
|
|
for (auto const &kvp : all) {
|
|
auto r = securities::from_str(kvp.second);
|
|
if (r.first) {
|
|
auto k = r.second.id();
|
|
auto ptr = std::make_unique<api::Security>(r.second);
|
|
auto ptr_cpy = ptr.get();
|
|
me->known_securities[k] = std::move(ptr);
|
|
me->to_publish.push_back(ptr_cpy);
|
|
}
|
|
else
|
|
LOG(Persistence,Error,
|
|
"Could not retrieve security with key {} from storage. "
|
|
"This security will be ignored "
|
|
"Security string is: {} ", kvp.first, kvp.second);
|
|
}
|
|
|
|
me->md_consumer.on_security ([this] (api::Security const &sec,
|
|
md2::MDConsumerHandle )
|
|
{cache_if_new(sec);});
|
|
|
|
me->new_securities_stream = make_stream<NewSecuritiesEvent>();
|
|
subscribe<mercury::TimerEvent> ([this] (auto) {this->on_scan_securities();});
|
|
}
|
|
|
|
void SecuritySrc::cache_if_new(api::Security const&sec)
|
|
{
|
|
auto &ptr = me->known_securities[sec.id()];
|
|
|
|
if (!ptr) {
|
|
|
|
// first time we see this security, copy and index it
|
|
ptr = std::make_unique<api::Security>(sec);
|
|
|
|
// remember that we need to publish it
|
|
me->to_publish.push_back (ptr.get());
|
|
|
|
// persist it
|
|
auto ks = std::to_string(sec.id());
|
|
auto vs = securities::to_str(sec);
|
|
me->store->insert(sec_ns,ks,vs);
|
|
}
|
|
}
|
|
|
|
void SecuritySrc::on_scan_securities()
|
|
{
|
|
auto now = Timer::now();
|
|
if (sec_diff(now,me->last_scan) > 5) {
|
|
me->last_scan = now;
|
|
me->md_consumer.scan_securities ();
|
|
if (me->to_publish.size())
|
|
mercury::Actor::publish_batch(me->new_securities_stream, me->to_publish);
|
|
}
|
|
}
|
|
|
|
}}
|
|
|
|
|