nautilus_infrastructure/sql/
cache.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::{
17    collections::{HashMap, VecDeque},
18    time::{Duration, Instant},
19};
20
21use bytes::Bytes;
22use nautilus_common::{
23    cache::database::{CacheDatabaseAdapter, CacheMap},
24    custom::CustomData,
25    logging::{log_task_awaiting, log_task_started, log_task_stopped},
26    runtime::get_runtime,
27    signal::Signal,
28};
29use nautilus_core::UnixNanos;
30use nautilus_model::{
31    accounts::AccountAny,
32    data::{Bar, DataType, QuoteTick, TradeTick},
33    events::{OrderEventAny, OrderSnapshot, position::snapshot::PositionSnapshot},
34    identifiers::{
35        AccountId, ClientId, ClientOrderId, ComponentId, InstrumentId, PositionId, StrategyId,
36        VenueOrderId,
37    },
38    instruments::{Instrument, InstrumentAny, SyntheticInstrument},
39    orderbook::OrderBook,
40    orders::{Order, OrderAny},
41    position::Position,
42    types::Currency,
43};
44use sqlx::{PgPool, postgres::PgConnectOptions};
45use tokio::try_join;
46use ustr::Ustr;
47
48use crate::sql::{
49    pg::{connect_pg, get_postgres_connect_options},
50    queries::DatabaseQueries,
51};
52
53// Task and connection names
54const CACHE_PROCESS: &str = "cache-process";
55
56#[derive(Debug)]
57#[cfg_attr(
58    feature = "python",
59    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.infrastructure")
60)]
61pub struct PostgresCacheDatabase {
62    pub pool: PgPool,
63    tx: tokio::sync::mpsc::UnboundedSender<DatabaseQuery>,
64    handle: tokio::task::JoinHandle<()>,
65}
66
67#[allow(clippy::large_enum_variant)]
68#[derive(Debug, Clone)]
69pub enum DatabaseQuery {
70    Close,
71    Add(String, Vec<u8>),
72    AddCurrency(Currency),
73    AddInstrument(InstrumentAny),
74    AddOrder(OrderAny, Option<ClientId>, bool),
75    AddOrderSnapshot(OrderSnapshot),
76    AddPositionSnapshot(PositionSnapshot),
77    AddAccount(AccountAny, bool),
78    AddSignal(Signal),
79    AddCustom(CustomData),
80    AddQuote(QuoteTick),
81    AddTrade(TradeTick),
82    AddBar(Bar),
83    UpdateOrder(OrderEventAny),
84}
85
86impl PostgresCacheDatabase {
87    /// Connects to the Postgres cache database using the provided connection parameters.
88    ///
89    /// # Errors
90    ///
91    /// Returns an error if establishing the database connection fails.
92    ///
93    /// # Panics
94    ///
95    /// Panics if the internal Postgres pool connection attempt (`connect_pg`) unwraps on error.
96    pub async fn connect(
97        host: Option<String>,
98        port: Option<u16>,
99        username: Option<String>,
100        password: Option<String>,
101        database: Option<String>,
102    ) -> Result<Self, sqlx::Error> {
103        let pg_connect_options =
104            get_postgres_connect_options(host, port, username, password, database);
105        let pool = connect_pg(pg_connect_options.clone().into()).await.unwrap();
106        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<DatabaseQuery>();
107
108        // Spawn a task to handle messages
109        let handle = tokio::spawn(async move {
110            Self::process_commands(rx, pg_connect_options.clone().into()).await;
111        });
112        Ok(Self { pool, tx, handle })
113    }
114
115    async fn process_commands(
116        mut rx: tokio::sync::mpsc::UnboundedReceiver<DatabaseQuery>,
117        pg_connect_options: PgConnectOptions,
118    ) {
119        log_task_started(CACHE_PROCESS);
120
121        let pool = connect_pg(pg_connect_options).await.unwrap();
122
123        // Buffering
124        let mut buffer: VecDeque<DatabaseQuery> = VecDeque::new();
125        let mut last_drain = Instant::now();
126
127        // TODO: Add `buffer_interval_ms` to config, setting this above 0 currently fails tests
128        let buffer_interval = Duration::from_millis(0);
129
130        // Continue to receive and handle messages until channel is hung up
131        loop {
132            if last_drain.elapsed() >= buffer_interval && !buffer.is_empty() {
133                drain_buffer(&pool, &mut buffer).await;
134                last_drain = Instant::now();
135            } else if let Some(msg) = rx.recv().await {
136                tracing::debug!("Received {msg:?}");
137                match msg {
138                    DatabaseQuery::Close => break,
139                    _ => buffer.push_back(msg),
140                }
141            } else {
142                tracing::debug!("Command channel closed");
143                break;
144            }
145        }
146
147        // Drain any remaining message
148        if !buffer.is_empty() {
149            drain_buffer(&pool, &mut buffer).await;
150        }
151
152        log_task_stopped(CACHE_PROCESS);
153    }
154}
155
156/// Retrieves a `PostgresCacheDatabase` using default connection options.
157///
158/// # Errors
159///
160/// Returns an error if connecting to the database or initializing the cache adapter fails.
161pub async fn get_pg_cache_database() -> anyhow::Result<PostgresCacheDatabase> {
162    let connect_options = get_postgres_connect_options(None, None, None, None, None);
163    Ok(PostgresCacheDatabase::connect(
164        Some(connect_options.host),
165        Some(connect_options.port),
166        Some(connect_options.username),
167        Some(connect_options.password),
168        Some(connect_options.database),
169    )
170    .await?)
171}
172
173#[allow(dead_code)]
174#[allow(unused)]
175#[async_trait::async_trait]
176impl CacheDatabaseAdapter for PostgresCacheDatabase {
177    fn close(&mut self) -> anyhow::Result<()> {
178        let pool = self.pool.clone();
179        let (tx, rx) = std::sync::mpsc::channel();
180
181        log::debug!("Closing connection pool");
182
183        tokio::task::block_in_place(|| {
184            get_runtime().block_on(async {
185                pool.close().await;
186                if let Err(e) = tx.send(()) {
187                    log::error!("Error closing pool: {e:?}");
188                }
189            });
190        });
191
192        // Cancel message handling task
193        if let Err(e) = self.tx.send(DatabaseQuery::Close) {
194            log::error!("Error sending close: {e:?}");
195        }
196
197        log_task_awaiting("cache-write");
198
199        tokio::task::block_in_place(|| {
200            if let Err(e) = get_runtime().block_on(&mut self.handle) {
201                log::error!("Error awaiting task 'cache-write': {e:?}");
202            }
203        });
204
205        log::debug!("Closed");
206
207        Ok(rx.recv()?)
208    }
209
210    fn flush(&mut self) -> anyhow::Result<()> {
211        let pool = self.pool.clone();
212        let (tx, rx) = std::sync::mpsc::channel();
213
214        tokio::task::block_in_place(|| {
215            get_runtime().block_on(async {
216                if let Err(e) = DatabaseQueries::truncate(&pool).await {
217                    log::error!("Error flushing pool: {e:?}");
218                }
219                if let Err(e) = tx.send(()) {
220                    log::error!("Error sending flush result: {e:?}");
221                }
222            });
223        });
224
225        Ok(rx.recv()?)
226    }
227
228    async fn load_all(&self) -> anyhow::Result<CacheMap> {
229        let (currencies, instruments, synthetics, accounts, orders, positions) = try_join!(
230            self.load_currencies(),
231            self.load_instruments(),
232            self.load_synthetics(),
233            self.load_accounts(),
234            self.load_orders(),
235            self.load_positions()
236        )
237        .map_err(|e| anyhow::anyhow!("Error loading cache data: {}", e))?;
238
239        // For now, we don't load greeks and yield curves from the database
240        // This will be implemented in the future
241        let greeks = HashMap::new();
242        let yield_curves = HashMap::new();
243
244        Ok(CacheMap {
245            currencies,
246            instruments,
247            synthetics,
248            accounts,
249            orders,
250            positions,
251            greeks,
252            yield_curves,
253        })
254    }
255
256    fn load(&self) -> anyhow::Result<HashMap<String, Bytes>> {
257        let pool = self.pool.clone();
258        let (tx, rx) = std::sync::mpsc::channel();
259        tokio::spawn(async move {
260            let result = DatabaseQueries::load(&pool).await;
261            match result {
262                Ok(items) => {
263                    let mapping = items
264                        .into_iter()
265                        .map(|(k, v)| (k, Bytes::from(v)))
266                        .collect();
267                    if let Err(e) = tx.send(mapping) {
268                        log::error!("Failed to send general items: {e:?}");
269                    }
270                }
271                Err(e) => {
272                    log::error!("Failed to load general items: {e:?}");
273                    if let Err(e) = tx.send(HashMap::new()) {
274                        log::error!("Failed to send empty general items: {e:?}");
275                    }
276                }
277            }
278        });
279        Ok(rx.recv()?)
280    }
281
282    async fn load_currencies(&self) -> anyhow::Result<HashMap<Ustr, Currency>> {
283        let pool = self.pool.clone();
284        let (tx, rx) = std::sync::mpsc::channel();
285        tokio::spawn(async move {
286            let result = DatabaseQueries::load_currencies(&pool).await;
287            match result {
288                Ok(currencies) => {
289                    let mapping = currencies
290                        .into_iter()
291                        .map(|currency| (currency.code, currency))
292                        .collect();
293                    if let Err(e) = tx.send(mapping) {
294                        log::error!("Failed to send currencies: {e:?}");
295                    }
296                }
297                Err(e) => {
298                    log::error!("Failed to load currencies: {e:?}");
299                    if let Err(e) = tx.send(HashMap::new()) {
300                        log::error!("Failed to send empty currencies: {e:?}");
301                    }
302                }
303            }
304        });
305        Ok(rx.recv()?)
306    }
307
308    async fn load_instruments(&self) -> anyhow::Result<HashMap<InstrumentId, InstrumentAny>> {
309        let pool = self.pool.clone();
310        let (tx, rx) = std::sync::mpsc::channel();
311        tokio::spawn(async move {
312            let result = DatabaseQueries::load_instruments(&pool).await;
313            match result {
314                Ok(instruments) => {
315                    let mapping = instruments
316                        .into_iter()
317                        .map(|instrument| (instrument.id(), instrument))
318                        .collect();
319                    if let Err(e) = tx.send(mapping) {
320                        log::error!("Failed to send instruments: {e:?}");
321                    }
322                }
323                Err(e) => {
324                    log::error!("Failed to load instruments: {e:?}");
325                    if let Err(e) = tx.send(HashMap::new()) {
326                        log::error!("Failed to send empty instruments: {e:?}");
327                    }
328                }
329            }
330        });
331        Ok(rx.recv()?)
332    }
333
334    async fn load_synthetics(&self) -> anyhow::Result<HashMap<InstrumentId, SyntheticInstrument>> {
335        todo!()
336    }
337
338    async fn load_accounts(&self) -> anyhow::Result<HashMap<AccountId, AccountAny>> {
339        let pool = self.pool.clone();
340        let (tx, rx) = std::sync::mpsc::channel();
341        tokio::spawn(async move {
342            let result = DatabaseQueries::load_accounts(&pool).await;
343            match result {
344                Ok(accounts) => {
345                    let mapping = accounts
346                        .into_iter()
347                        .map(|account| (account.id(), account))
348                        .collect();
349                    if let Err(e) = tx.send(mapping) {
350                        log::error!("Failed to send accounts: {e:?}");
351                    }
352                }
353                Err(e) => {
354                    log::error!("Failed to load accounts: {e:?}");
355                    if let Err(e) = tx.send(HashMap::new()) {
356                        log::error!("Failed to send empty accounts: {e:?}");
357                    }
358                }
359            }
360        });
361        Ok(rx.recv()?)
362    }
363
364    async fn load_orders(&self) -> anyhow::Result<HashMap<ClientOrderId, OrderAny>> {
365        let pool = self.pool.clone();
366        let (tx, rx) = std::sync::mpsc::channel();
367        tokio::spawn(async move {
368            let result = DatabaseQueries::load_orders(&pool).await;
369            match result {
370                Ok(orders) => {
371                    let mapping = orders
372                        .into_iter()
373                        .map(|order| (order.client_order_id(), order))
374                        .collect();
375                    if let Err(e) = tx.send(mapping) {
376                        log::error!("Failed to send orders: {e:?}");
377                    }
378                }
379                Err(e) => {
380                    log::error!("Failed to load orders: {e:?}");
381                    if let Err(e) = tx.send(HashMap::new()) {
382                        log::error!("Failed to send empty orders: {e:?}");
383                    }
384                }
385            }
386        });
387        Ok(rx.recv()?)
388    }
389
390    async fn load_positions(&self) -> anyhow::Result<HashMap<PositionId, Position>> {
391        todo!()
392    }
393
394    fn load_index_order_position(&self) -> anyhow::Result<HashMap<ClientOrderId, Position>> {
395        todo!()
396    }
397
398    fn load_index_order_client(&self) -> anyhow::Result<HashMap<ClientOrderId, ClientId>> {
399        let pool = self.pool.clone();
400        let (tx, rx) = std::sync::mpsc::channel();
401        tokio::spawn(async move {
402            let result = DatabaseQueries::load_distinct_order_event_client_ids(&pool).await;
403            match result {
404                Ok(currency) => {
405                    if let Err(e) = tx.send(currency) {
406                        log::error!("Failed to send load_index_order_client result: {e:?}");
407                    }
408                }
409                Err(e) => {
410                    log::error!("Failed to run query load_distinct_order_event_client_ids: {e:?}");
411                    if let Err(e) = tx.send(HashMap::new()) {
412                        log::error!("Failed to send empty load_index_order_client result: {e:?}");
413                    }
414                }
415            }
416        });
417        Ok(rx.recv()?)
418    }
419
420    async fn load_currency(&self, code: &Ustr) -> anyhow::Result<Option<Currency>> {
421        let pool = self.pool.clone();
422        let code = code.to_owned(); // Clone the code
423        let (tx, rx) = std::sync::mpsc::channel();
424        tokio::spawn(async move {
425            let result = DatabaseQueries::load_currency(&pool, &code).await;
426            match result {
427                Ok(currency) => {
428                    if let Err(e) = tx.send(currency) {
429                        log::error!("Failed to send currency {code}: {e:?}");
430                    }
431                }
432                Err(e) => {
433                    log::error!("Failed to load currency {code}: {e:?}");
434                    if let Err(e) = tx.send(None) {
435                        log::error!("Failed to send None for currency {code}: {e:?}");
436                    }
437                }
438            }
439        });
440        Ok(rx.recv()?)
441    }
442
443    async fn load_instrument(
444        &self,
445        instrument_id: &InstrumentId,
446    ) -> anyhow::Result<Option<InstrumentAny>> {
447        let pool = self.pool.clone();
448        let instrument_id = instrument_id.to_owned(); // Clone the instrument_id
449        let (tx, rx) = std::sync::mpsc::channel();
450        tokio::spawn(async move {
451            let result = DatabaseQueries::load_instrument(&pool, &instrument_id).await;
452            match result {
453                Ok(instrument) => {
454                    if let Err(e) = tx.send(instrument) {
455                        log::error!("Failed to send instrument {instrument_id}: {e:?}");
456                    }
457                }
458                Err(e) => {
459                    log::error!("Failed to load instrument {instrument_id}: {e:?}");
460                    if let Err(e) = tx.send(None) {
461                        log::error!("Failed to send None for instrument {instrument_id}: {e:?}");
462                    }
463                }
464            }
465        });
466        Ok(rx.recv()?)
467    }
468
469    async fn load_synthetic(
470        &self,
471        instrument_id: &InstrumentId,
472    ) -> anyhow::Result<Option<SyntheticInstrument>> {
473        todo!()
474    }
475
476    async fn load_account(&self, account_id: &AccountId) -> anyhow::Result<Option<AccountAny>> {
477        let pool = self.pool.clone();
478        let account_id = account_id.to_owned();
479        let (tx, rx) = std::sync::mpsc::channel();
480        tokio::spawn(async move {
481            let result = DatabaseQueries::load_account(&pool, &account_id).await;
482            match result {
483                Ok(account) => {
484                    if let Err(e) = tx.send(account) {
485                        log::error!("Failed to send account {account_id}: {e:?}");
486                    }
487                }
488                Err(e) => {
489                    log::error!("Failed to load account {account_id}: {e:?}");
490                    if let Err(e) = tx.send(None) {
491                        log::error!("Failed to send None for account {account_id}: {e:?}");
492                    }
493                }
494            }
495        });
496        Ok(rx.recv()?)
497    }
498
499    async fn load_order(
500        &self,
501        client_order_id: &ClientOrderId,
502    ) -> anyhow::Result<Option<OrderAny>> {
503        let pool = self.pool.clone();
504        let client_order_id = client_order_id.to_owned();
505        let (tx, rx) = std::sync::mpsc::channel();
506        tokio::spawn(async move {
507            let result = DatabaseQueries::load_order(&pool, &client_order_id).await;
508            match result {
509                Ok(order) => {
510                    if let Err(e) = tx.send(order) {
511                        log::error!("Failed to send order {client_order_id}: {e:?}");
512                    }
513                }
514                Err(e) => {
515                    log::error!("Failed to load order {client_order_id}: {e:?}");
516                    let _ = tx.send(None);
517                }
518            }
519        });
520        Ok(rx.recv()?)
521    }
522
523    async fn load_position(&self, position_id: &PositionId) -> anyhow::Result<Option<Position>> {
524        todo!()
525    }
526
527    fn load_actor(&self, component_id: &ComponentId) -> anyhow::Result<HashMap<String, Bytes>> {
528        todo!()
529    }
530
531    fn delete_actor(&self, component_id: &ComponentId) -> anyhow::Result<()> {
532        todo!()
533    }
534
535    fn load_strategy(&self, strategy_id: &StrategyId) -> anyhow::Result<HashMap<String, Bytes>> {
536        todo!()
537    }
538
539    fn delete_strategy(&self, component_id: &StrategyId) -> anyhow::Result<()> {
540        todo!()
541    }
542
543    fn add(&self, key: String, value: Bytes) -> anyhow::Result<()> {
544        let query = DatabaseQuery::Add(key, value.into());
545        self.tx
546            .send(query)
547            .map_err(|e| anyhow::anyhow!("Failed to send query to database message handler: {e}"))
548    }
549
550    fn add_currency(&self, currency: &Currency) -> anyhow::Result<()> {
551        let query = DatabaseQuery::AddCurrency(*currency);
552        self.tx.send(query).map_err(|e| {
553            anyhow::anyhow!("Failed to query add_currency to database message handler: {e}")
554        })
555    }
556
557    fn add_instrument(&self, instrument: &InstrumentAny) -> anyhow::Result<()> {
558        let query = DatabaseQuery::AddInstrument(instrument.clone());
559        self.tx.send(query).map_err(|e| {
560            anyhow::anyhow!("Failed to send query add_instrument to database message handler: {e}")
561        })
562    }
563
564    fn add_synthetic(&self, synthetic: &SyntheticInstrument) -> anyhow::Result<()> {
565        todo!()
566    }
567
568    fn add_account(&self, account: &AccountAny) -> anyhow::Result<()> {
569        let query = DatabaseQuery::AddAccount(account.clone(), false);
570        self.tx.send(query).map_err(|e| {
571            anyhow::anyhow!("Failed to send query add_account to database message handler: {e}")
572        })
573    }
574
575    fn add_order(&self, order: &OrderAny, client_id: Option<ClientId>) -> anyhow::Result<()> {
576        let query = DatabaseQuery::AddOrder(order.clone(), client_id, false);
577        self.tx.send(query).map_err(|e| {
578            anyhow::anyhow!("Failed to send query add_order to database message handler: {e}")
579        })
580    }
581
582    fn add_order_snapshot(&self, snapshot: &OrderSnapshot) -> anyhow::Result<()> {
583        let query = DatabaseQuery::AddOrderSnapshot(snapshot.to_owned());
584        self.tx.send(query).map_err(|e| {
585            anyhow::anyhow!(
586                "Failed to send query add_order_snapshot to database message handler: {e}"
587            )
588        })
589    }
590
591    fn add_position(&self, position: &Position) -> anyhow::Result<()> {
592        todo!()
593    }
594
595    fn add_position_snapshot(&self, snapshot: &PositionSnapshot) -> anyhow::Result<()> {
596        let query = DatabaseQuery::AddPositionSnapshot(snapshot.to_owned());
597        self.tx.send(query).map_err(|e| {
598            anyhow::anyhow!(
599                "Failed to send query add_position_snapshot to database message handler: {e}"
600            )
601        })
602    }
603
604    fn add_order_book(&self, order_book: &OrderBook) -> anyhow::Result<()> {
605        todo!()
606    }
607
608    fn add_quote(&self, quote: &QuoteTick) -> anyhow::Result<()> {
609        let query = DatabaseQuery::AddQuote(quote.to_owned());
610        self.tx.send(query).map_err(|e| {
611            anyhow::anyhow!("Failed to send query add_quote to database message handler: {e}")
612        })
613    }
614
615    fn load_quotes(&self, instrument_id: &InstrumentId) -> anyhow::Result<Vec<QuoteTick>> {
616        let pool = self.pool.clone();
617        let instrument_id = instrument_id.to_owned();
618        let (tx, rx) = std::sync::mpsc::channel();
619        tokio::spawn(async move {
620            let result = DatabaseQueries::load_quotes(&pool, &instrument_id).await;
621            match result {
622                Ok(quotes) => {
623                    if let Err(e) = tx.send(quotes) {
624                        log::error!("Failed to send quotes for instrument {instrument_id}: {e:?}");
625                    }
626                }
627                Err(e) => {
628                    log::error!("Failed to load quotes for instrument {instrument_id}: {e:?}");
629                    if let Err(e) = tx.send(Vec::new()) {
630                        log::error!(
631                            "Failed to send empty quotes for instrument {instrument_id}: {e:?}"
632                        );
633                    }
634                }
635            }
636        });
637        Ok(rx.recv()?)
638    }
639
640    fn add_trade(&self, trade: &TradeTick) -> anyhow::Result<()> {
641        let query = DatabaseQuery::AddTrade(trade.to_owned());
642        self.tx.send(query).map_err(|e| {
643            anyhow::anyhow!("Failed to send query add_trade to database message handler: {e}")
644        })
645    }
646
647    fn load_trades(&self, instrument_id: &InstrumentId) -> anyhow::Result<Vec<TradeTick>> {
648        let pool = self.pool.clone();
649        let instrument_id = instrument_id.to_owned();
650        let (tx, rx) = std::sync::mpsc::channel();
651        tokio::spawn(async move {
652            let result = DatabaseQueries::load_trades(&pool, &instrument_id).await;
653            match result {
654                Ok(trades) => {
655                    if let Err(e) = tx.send(trades) {
656                        log::error!("Failed to send trades for instrument {instrument_id}: {e:?}");
657                    }
658                }
659                Err(e) => {
660                    log::error!("Failed to load trades for instrument {instrument_id}: {e:?}");
661                    if let Err(e) = tx.send(Vec::new()) {
662                        log::error!(
663                            "Failed to send empty trades for instrument {instrument_id}: {e:?}"
664                        );
665                    }
666                }
667            }
668        });
669        Ok(rx.recv()?)
670    }
671
672    fn add_bar(&self, bar: &Bar) -> anyhow::Result<()> {
673        let query = DatabaseQuery::AddBar(bar.to_owned());
674        self.tx.send(query).map_err(|e| {
675            anyhow::anyhow!("Failed to send query add_bar to database message handler: {e}")
676        })
677    }
678
679    fn load_bars(&self, instrument_id: &InstrumentId) -> anyhow::Result<Vec<Bar>> {
680        let pool = self.pool.clone();
681        let instrument_id = instrument_id.to_owned();
682        let (tx, rx) = std::sync::mpsc::channel();
683        tokio::spawn(async move {
684            let result = DatabaseQueries::load_bars(&pool, &instrument_id).await;
685            match result {
686                Ok(bars) => {
687                    if let Err(e) = tx.send(bars) {
688                        log::error!("Failed to send bars for instrument {instrument_id}: {e:?}");
689                    }
690                }
691                Err(e) => {
692                    log::error!("Failed to load bars for instrument {instrument_id}: {e:?}");
693                    if let Err(e) = tx.send(Vec::new()) {
694                        log::error!(
695                            "Failed to send empty bars for instrument {instrument_id}: {e:?}"
696                        );
697                    }
698                }
699            }
700        });
701        Ok(rx.recv()?)
702    }
703
704    fn add_signal(&self, signal: &Signal) -> anyhow::Result<()> {
705        let query = DatabaseQuery::AddSignal(signal.to_owned());
706        self.tx.send(query).map_err(|e| {
707            anyhow::anyhow!("Failed to send query add_signal to database message handler: {e}")
708        })
709    }
710
711    fn load_signals(&self, name: &str) -> anyhow::Result<Vec<Signal>> {
712        let pool = self.pool.clone();
713        let name = name.to_owned();
714        let (tx, rx) = std::sync::mpsc::channel();
715        tokio::spawn(async move {
716            let result = DatabaseQueries::load_signals(&pool, &name).await;
717            match result {
718                Ok(signals) => {
719                    if let Err(e) = tx.send(signals) {
720                        log::error!("Failed to send signals for '{name}': {e:?}");
721                    }
722                }
723                Err(e) => {
724                    log::error!("Failed to load signals for '{name}': {e:?}");
725                    if let Err(e) = tx.send(Vec::new()) {
726                        log::error!("Failed to send empty signals for '{name}': {e:?}");
727                    }
728                }
729            }
730        });
731        Ok(rx.recv()?)
732    }
733
734    fn add_custom_data(&self, data: &CustomData) -> anyhow::Result<()> {
735        let query = DatabaseQuery::AddCustom(data.to_owned());
736        self.tx.send(query).map_err(|e| {
737            anyhow::anyhow!("Failed to send query add_signal to database message handler: {e}")
738        })
739    }
740
741    fn load_custom_data(&self, data_type: &DataType) -> anyhow::Result<Vec<CustomData>> {
742        let pool = self.pool.clone();
743        let data_type = data_type.to_owned();
744        let (tx, rx) = std::sync::mpsc::channel();
745        tokio::spawn(async move {
746            let result = DatabaseQueries::load_custom_data(&pool, &data_type).await;
747            match result {
748                Ok(signals) => {
749                    if let Err(e) = tx.send(signals) {
750                        log::error!("Failed to send custom data for '{data_type}': {e:?}");
751                    }
752                }
753                Err(e) => {
754                    log::error!("Failed to load custom data for '{data_type}': {e:?}");
755                    if let Err(e) = tx.send(Vec::new()) {
756                        log::error!("Failed to send empty custom data for '{data_type}': {e:?}");
757                    }
758                }
759            }
760        });
761        Ok(rx.recv()?)
762    }
763
764    fn load_order_snapshot(
765        &self,
766        client_order_id: &ClientOrderId,
767    ) -> anyhow::Result<Option<OrderSnapshot>> {
768        let pool = self.pool.clone();
769        let client_order_id = client_order_id.to_owned();
770        let (tx, rx) = std::sync::mpsc::channel();
771        tokio::spawn(async move {
772            let result = DatabaseQueries::load_order_snapshot(&pool, &client_order_id).await;
773            match result {
774                Ok(snapshot) => {
775                    if let Err(e) = tx.send(snapshot) {
776                        log::error!("Failed to send order snapshot {client_order_id}: {e:?}");
777                    }
778                }
779                Err(e) => {
780                    log::error!("Failed to load order snapshot {client_order_id}: {e:?}");
781                    if let Err(e) = tx.send(None) {
782                        log::error!(
783                            "Failed to send None for order snapshot {client_order_id}: {e:?}"
784                        );
785                    }
786                }
787            }
788        });
789        Ok(rx.recv()?)
790    }
791
792    fn load_position_snapshot(
793        &self,
794        position_id: &PositionId,
795    ) -> anyhow::Result<Option<PositionSnapshot>> {
796        let pool = self.pool.clone();
797        let position_id = position_id.to_owned();
798        let (tx, rx) = std::sync::mpsc::channel();
799        tokio::spawn(async move {
800            let result = DatabaseQueries::load_position_snapshot(&pool, &position_id).await;
801            match result {
802                Ok(snapshot) => {
803                    if let Err(e) = tx.send(snapshot) {
804                        log::error!("Failed to send position snapshot {position_id}: {e:?}");
805                    }
806                }
807                Err(e) => {
808                    log::error!("Failed to load position snapshot {position_id}: {e:?}");
809                    if let Err(e) = tx.send(None) {
810                        log::error!(
811                            "Failed to send None for position snapshot {position_id}: {e:?}"
812                        );
813                    }
814                }
815            }
816        });
817        Ok(rx.recv()?)
818    }
819
820    fn index_venue_order_id(
821        &self,
822        client_order_id: ClientOrderId,
823        venue_order_id: VenueOrderId,
824    ) -> anyhow::Result<()> {
825        todo!()
826    }
827
828    fn index_order_position(
829        &self,
830        client_order_id: ClientOrderId,
831        position_id: PositionId,
832    ) -> anyhow::Result<()> {
833        todo!()
834    }
835
836    fn update_actor(&self) -> anyhow::Result<()> {
837        todo!()
838    }
839
840    fn update_strategy(&self) -> anyhow::Result<()> {
841        todo!()
842    }
843
844    fn update_account(&self, account: &AccountAny) -> anyhow::Result<()> {
845        let query = DatabaseQuery::AddAccount(account.clone(), true);
846        self.tx.send(query).map_err(|e| {
847            anyhow::anyhow!("Failed to send query add_account to database message handler: {e}")
848        })
849    }
850
851    fn update_order(&self, event: &OrderEventAny) -> anyhow::Result<()> {
852        let query = DatabaseQuery::UpdateOrder(event.clone());
853        self.tx.send(query).map_err(|e| {
854            anyhow::anyhow!("Failed to send query update_order to database message handler: {e}")
855        })
856    }
857
858    fn update_position(&self, position: &Position) -> anyhow::Result<()> {
859        todo!()
860    }
861
862    fn snapshot_order_state(&self, order: &OrderAny) -> anyhow::Result<()> {
863        todo!()
864    }
865
866    fn snapshot_position_state(&self, position: &Position) -> anyhow::Result<()> {
867        todo!()
868    }
869
870    fn heartbeat(&self, timestamp: UnixNanos) -> anyhow::Result<()> {
871        todo!()
872    }
873}
874
875async fn drain_buffer(pool: &PgPool, buffer: &mut VecDeque<DatabaseQuery>) {
876    for cmd in buffer.drain(..) {
877        let result: anyhow::Result<()> = match cmd {
878            DatabaseQuery::Close => Ok(()),
879            DatabaseQuery::Add(key, value) => DatabaseQueries::add(pool, key, value).await,
880            DatabaseQuery::AddCurrency(currency) => {
881                DatabaseQueries::add_currency(pool, currency).await
882            }
883            DatabaseQuery::AddInstrument(instrument_any) => match instrument_any {
884                InstrumentAny::Betting(instrument) => {
885                    DatabaseQueries::add_instrument(pool, "BETTING", Box::new(instrument)).await
886                }
887                InstrumentAny::BinaryOption(instrument) => {
888                    DatabaseQueries::add_instrument(pool, "BINARY_OPTION", Box::new(instrument))
889                        .await
890                }
891                InstrumentAny::CryptoFuture(instrument) => {
892                    DatabaseQueries::add_instrument(pool, "CRYPTO_FUTURE", Box::new(instrument))
893                        .await
894                }
895                InstrumentAny::CryptoOption(instrument) => {
896                    DatabaseQueries::add_instrument(pool, "CRYPTO_OPTION", Box::new(instrument))
897                        .await
898                }
899                InstrumentAny::CryptoPerpetual(instrument) => {
900                    DatabaseQueries::add_instrument(pool, "CRYPTO_PERPETUAL", Box::new(instrument))
901                        .await
902                }
903                InstrumentAny::CurrencyPair(instrument) => {
904                    DatabaseQueries::add_instrument(pool, "CURRENCY_PAIR", Box::new(instrument))
905                        .await
906                }
907                InstrumentAny::Equity(equity) => {
908                    DatabaseQueries::add_instrument(pool, "EQUITY", Box::new(equity)).await
909                }
910                InstrumentAny::FuturesContract(instrument) => {
911                    DatabaseQueries::add_instrument(pool, "FUTURES_CONTRACT", Box::new(instrument))
912                        .await
913                }
914                InstrumentAny::FuturesSpread(instrument) => {
915                    DatabaseQueries::add_instrument(pool, "FUTURES_SPREAD", Box::new(instrument))
916                        .await
917                }
918                InstrumentAny::OptionContract(instrument) => {
919                    DatabaseQueries::add_instrument(pool, "OPTION_CONTRACT", Box::new(instrument))
920                        .await
921                }
922                InstrumentAny::OptionSpread(instrument) => {
923                    DatabaseQueries::add_instrument(pool, "OPTION_SPREAD", Box::new(instrument))
924                        .await
925                }
926            },
927            DatabaseQuery::AddOrder(order_any, client_id, updated) => match order_any {
928                OrderAny::Limit(order) => {
929                    DatabaseQueries::add_order(pool, "LIMIT", updated, Box::new(order), client_id)
930                        .await
931                }
932                OrderAny::LimitIfTouched(order) => {
933                    DatabaseQueries::add_order(
934                        pool,
935                        "LIMIT_IF_TOUCHED",
936                        updated,
937                        Box::new(order),
938                        client_id,
939                    )
940                    .await
941                }
942                OrderAny::Market(order) => {
943                    DatabaseQueries::add_order(pool, "MARKET", updated, Box::new(order), client_id)
944                        .await
945                }
946                OrderAny::MarketIfTouched(order) => {
947                    DatabaseQueries::add_order(
948                        pool,
949                        "MARKET_IF_TOUCHED",
950                        updated,
951                        Box::new(order),
952                        client_id,
953                    )
954                    .await
955                }
956                OrderAny::MarketToLimit(order) => {
957                    DatabaseQueries::add_order(
958                        pool,
959                        "MARKET_TO_LIMIT",
960                        updated,
961                        Box::new(order),
962                        client_id,
963                    )
964                    .await
965                }
966                OrderAny::StopLimit(order) => {
967                    DatabaseQueries::add_order(
968                        pool,
969                        "STOP_LIMIT",
970                        updated,
971                        Box::new(order),
972                        client_id,
973                    )
974                    .await
975                }
976                OrderAny::StopMarket(order) => {
977                    DatabaseQueries::add_order(
978                        pool,
979                        "STOP_MARKET",
980                        updated,
981                        Box::new(order),
982                        client_id,
983                    )
984                    .await
985                }
986                OrderAny::TrailingStopLimit(order) => {
987                    DatabaseQueries::add_order(
988                        pool,
989                        "TRAILING_STOP_LIMIT",
990                        updated,
991                        Box::new(order),
992                        client_id,
993                    )
994                    .await
995                }
996                OrderAny::TrailingStopMarket(order) => {
997                    DatabaseQueries::add_order(
998                        pool,
999                        "TRAILING_STOP_MARKET",
1000                        updated,
1001                        Box::new(order),
1002                        client_id,
1003                    )
1004                    .await
1005                }
1006            },
1007            DatabaseQuery::AddOrderSnapshot(snapshot) => {
1008                DatabaseQueries::add_order_snapshot(pool, snapshot).await
1009            }
1010            DatabaseQuery::AddPositionSnapshot(snapshot) => {
1011                DatabaseQueries::add_position_snapshot(pool, snapshot).await
1012            }
1013            DatabaseQuery::AddAccount(account_any, updated) => match account_any {
1014                AccountAny::Cash(account) => {
1015                    DatabaseQueries::add_account(pool, "CASH", updated, Box::new(account)).await
1016                }
1017                AccountAny::Margin(account) => {
1018                    DatabaseQueries::add_account(pool, "MARGIN", updated, Box::new(account)).await
1019                }
1020            },
1021            DatabaseQuery::AddSignal(signal) => DatabaseQueries::add_signal(pool, &signal).await,
1022            DatabaseQuery::AddCustom(data) => DatabaseQueries::add_custom_data(pool, &data).await,
1023            DatabaseQuery::AddQuote(quote) => DatabaseQueries::add_quote(pool, &quote).await,
1024            DatabaseQuery::AddTrade(trade) => DatabaseQueries::add_trade(pool, &trade).await,
1025            DatabaseQuery::AddBar(bar) => DatabaseQueries::add_bar(pool, &bar).await,
1026            DatabaseQuery::UpdateOrder(event) => {
1027                DatabaseQueries::add_order_event(pool, event.into_boxed(), None).await
1028            }
1029        };
1030
1031        if let Err(e) = result {
1032            tracing::error!("Error on query: {e:?}");
1033        }
1034    }
1035}