|
1 |
| -use std::{path::Path, sync::Arc}; |
| 1 | +use std::{path::Path, result, time::Duration}; |
2 | 2 |
|
3 | 3 | use anyhow::{Context, Result};
|
4 | 4 | use iroh_metrics::inc;
|
5 | 5 | use pkarr::SignedPacket;
|
6 | 6 | use redb::{backends::InMemoryBackend, Database, ReadableTable, TableDefinition};
|
| 7 | +use tokio::sync::{mpsc, oneshot}; |
| 8 | +use tokio_util::sync::CancellationToken; |
7 | 9 | use tracing::info;
|
8 | 10 |
|
9 | 11 | use crate::{metrics::Metrics, util::PublicKeyBytes};
|
10 | 12 |
|
11 | 13 | pub type SignedPacketsKey = [u8; 32];
|
12 | 14 | const SIGNED_PACKETS_TABLE: TableDefinition<&SignedPacketsKey, &[u8]> =
|
13 | 15 | TableDefinition::new("signed-packets-1");
|
| 16 | +const MAX_BATCH_SIZE: usize = 1024 * 64; |
| 17 | +const MAX_BATCH_TIME: Duration = Duration::from_secs(1); |
14 | 18 |
|
15 | 19 | #[derive(Debug)]
|
16 | 20 | pub struct SignedPacketStore {
|
17 |
| - db: Arc<Database>, |
| 21 | + send: mpsc::Sender<Message>, |
| 22 | + cancel: CancellationToken, |
| 23 | + thread: Option<std::thread::JoinHandle<()>>, |
| 24 | +} |
| 25 | + |
| 26 | +impl Drop for SignedPacketStore { |
| 27 | + fn drop(&mut self) { |
| 28 | + // cancel the actor |
| 29 | + self.cancel.cancel(); |
| 30 | + // join the thread. This is important so that Drop implementations that |
| 31 | + // are called from the actor thread can complete before we return. |
| 32 | + if let Some(thread) = self.thread.take() { |
| 33 | + let _ = thread.join(); |
| 34 | + } |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +enum Message { |
| 39 | + Upsert { |
| 40 | + packet: SignedPacket, |
| 41 | + res: oneshot::Sender<bool>, |
| 42 | + }, |
| 43 | + Get { |
| 44 | + key: PublicKeyBytes, |
| 45 | + res: oneshot::Sender<Option<SignedPacket>>, |
| 46 | + }, |
| 47 | + Remove { |
| 48 | + key: PublicKeyBytes, |
| 49 | + res: oneshot::Sender<bool>, |
| 50 | + }, |
| 51 | +} |
| 52 | + |
| 53 | +struct Actor { |
| 54 | + db: Database, |
| 55 | + recv: mpsc::Receiver<Message>, |
| 56 | + cancel: CancellationToken, |
| 57 | + max_batch_size: usize, |
| 58 | + max_batch_time: Duration, |
| 59 | +} |
| 60 | + |
| 61 | +impl Actor { |
| 62 | + async fn run(mut self) { |
| 63 | + match self.run0().await { |
| 64 | + Ok(()) => {} |
| 65 | + Err(e) => { |
| 66 | + self.cancel.cancel(); |
| 67 | + tracing::error!("packet store actor failed: {:?}", e); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + async fn run0(&mut self) -> anyhow::Result<()> { |
| 73 | + loop { |
| 74 | + let transaction = self.db.begin_write()?; |
| 75 | + let mut tables = Tables::new(&transaction)?; |
| 76 | + let timeout = tokio::time::sleep(self.max_batch_time); |
| 77 | + tokio::pin!(timeout); |
| 78 | + for _ in 0..self.max_batch_size { |
| 79 | + tokio::select! { |
| 80 | + _ = self.cancel.cancelled() => { |
| 81 | + drop(tables); |
| 82 | + transaction.commit()?; |
| 83 | + return Ok(()); |
| 84 | + } |
| 85 | + _ = &mut timeout => break, |
| 86 | + Some(msg) = self.recv.recv() => { |
| 87 | + match msg { |
| 88 | + Message::Get { key, res } => { |
| 89 | + let packet = get_packet(&tables.signed_packets, &key)?; |
| 90 | + res.send(packet).ok(); |
| 91 | + } |
| 92 | + Message::Upsert { packet, res } => { |
| 93 | + let key = PublicKeyBytes::from_signed_packet(&packet); |
| 94 | + let mut replaced = false; |
| 95 | + if let Some(existing) = get_packet(&tables.signed_packets, &key)? { |
| 96 | + if existing.more_recent_than(&packet) { |
| 97 | + res.send(false).ok(); |
| 98 | + continue; |
| 99 | + } else { |
| 100 | + replaced = true; |
| 101 | + } |
| 102 | + } |
| 103 | + let value = packet.as_bytes(); |
| 104 | + tables.signed_packets.insert(key.as_bytes(), &value[..])?; |
| 105 | + if replaced { |
| 106 | + inc!(Metrics, store_packets_updated); |
| 107 | + } else { |
| 108 | + inc!(Metrics, store_packets_inserted); |
| 109 | + } |
| 110 | + res.send(true).ok(); |
| 111 | + } |
| 112 | + Message::Remove { key, res } => { |
| 113 | + let updated = |
| 114 | + tables.signed_packets.remove(key.as_bytes())?.is_some() |
| 115 | + ; |
| 116 | + if updated { |
| 117 | + inc!(Metrics, store_packets_removed); |
| 118 | + } |
| 119 | + res.send(updated).ok(); |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + drop(tables); |
| 126 | + transaction.commit()?; |
| 127 | + } |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +/// A struct similar to [`redb::Table`] but for all tables that make up the |
| 132 | +/// signed packet store. |
| 133 | +pub(super) struct Tables<'a> { |
| 134 | + pub signed_packets: redb::Table<'a, &'static SignedPacketsKey, &'static [u8]>, |
| 135 | +} |
| 136 | + |
| 137 | +impl<'txn> Tables<'txn> { |
| 138 | + pub fn new(tx: &'txn redb::WriteTransaction) -> result::Result<Self, redb::TableError> { |
| 139 | + Ok(Self { |
| 140 | + signed_packets: tx.open_table(SIGNED_PACKETS_TABLE)?, |
| 141 | + }) |
| 142 | + } |
18 | 143 | }
|
19 | 144 |
|
20 | 145 | impl SignedPacketStore {
|
@@ -42,73 +167,53 @@ impl SignedPacketStore {
|
42 | 167 | }
|
43 | 168 |
|
44 | 169 | pub fn open(db: Database) -> Result<Self> {
|
| 170 | + // create tables |
45 | 171 | let write_tx = db.begin_write()?;
|
46 |
| - { |
47 |
| - let _table = write_tx.open_table(SIGNED_PACKETS_TABLE)?; |
48 |
| - } |
| 172 | + let _ = Tables::new(&write_tx)?; |
49 | 173 | write_tx.commit()?;
|
50 |
| - Ok(Self { db: Arc::new(db) }) |
| 174 | + let (send, recv) = mpsc::channel(1024); |
| 175 | + let cancel = CancellationToken::new(); |
| 176 | + let cancel2 = cancel.clone(); |
| 177 | + let actor = Actor { |
| 178 | + db, |
| 179 | + recv, |
| 180 | + cancel: cancel2, |
| 181 | + max_batch_size: MAX_BATCH_SIZE, |
| 182 | + max_batch_time: MAX_BATCH_TIME, |
| 183 | + }; |
| 184 | + // start an io thread and donate it to the tokio runtime so we can do blocking IO |
| 185 | + // inside the thread despite being in a tokio runtime |
| 186 | + let handle = tokio::runtime::Handle::try_current()?; |
| 187 | + let thread = std::thread::Builder::new() |
| 188 | + .name("packet-store-actor".into()) |
| 189 | + .spawn(move || { |
| 190 | + handle.block_on(actor.run()); |
| 191 | + })?; |
| 192 | + Ok(Self { |
| 193 | + send, |
| 194 | + cancel, |
| 195 | + thread: Some(thread), |
| 196 | + }) |
51 | 197 | }
|
52 | 198 |
|
53 | 199 | pub async fn upsert(&self, packet: SignedPacket) -> Result<bool> {
|
54 |
| - let key = PublicKeyBytes::from_signed_packet(&packet); |
55 |
| - let db = self.db.clone(); |
56 |
| - tokio::task::spawn_blocking(move || { |
57 |
| - let tx = db.begin_write()?; |
58 |
| - let mut replaced = false; |
59 |
| - { |
60 |
| - let mut table = tx.open_table(SIGNED_PACKETS_TABLE)?; |
61 |
| - if let Some(existing) = get_packet(&table, &key)? { |
62 |
| - if existing.more_recent_than(&packet) { |
63 |
| - return Ok(false); |
64 |
| - } else { |
65 |
| - replaced = true; |
66 |
| - } |
67 |
| - } |
68 |
| - let value = packet.as_bytes(); |
69 |
| - table.insert(key.as_bytes(), &value[..])?; |
70 |
| - } |
71 |
| - tx.commit()?; |
72 |
| - if replaced { |
73 |
| - inc!(Metrics, store_packets_updated); |
74 |
| - } else { |
75 |
| - inc!(Metrics, store_packets_inserted); |
76 |
| - } |
77 |
| - Ok(true) |
78 |
| - }) |
79 |
| - .await? |
| 200 | + let (tx, rx) = oneshot::channel(); |
| 201 | + self.send.send(Message::Upsert { packet, res: tx }).await?; |
| 202 | + Ok(rx.await?) |
80 | 203 | }
|
81 | 204 |
|
82 | 205 | pub async fn get(&self, key: &PublicKeyBytes) -> Result<Option<SignedPacket>> {
|
83 |
| - let db = self.db.clone(); |
84 |
| - let key = *key; |
85 |
| - let res = tokio::task::spawn_blocking(move || { |
86 |
| - let tx = db.begin_read()?; |
87 |
| - let table = tx.open_table(SIGNED_PACKETS_TABLE)?; |
88 |
| - get_packet(&table, &key) |
89 |
| - }) |
90 |
| - .await??; |
91 |
| - Ok(res) |
| 206 | + let (tx, rx) = oneshot::channel(); |
| 207 | + self.send.send(Message::Get { key: *key, res: tx }).await?; |
| 208 | + Ok(rx.await?) |
92 | 209 | }
|
93 | 210 |
|
94 | 211 | pub async fn remove(&self, key: &PublicKeyBytes) -> Result<bool> {
|
95 |
| - let db = self.db.clone(); |
96 |
| - let key = *key; |
97 |
| - tokio::task::spawn_blocking(move || { |
98 |
| - let tx = db.begin_write()?; |
99 |
| - let updated = { |
100 |
| - let mut table = tx.open_table(SIGNED_PACKETS_TABLE)?; |
101 |
| - let did_remove = table.remove(key.as_bytes())?.is_some(); |
102 |
| - #[allow(clippy::let_and_return)] |
103 |
| - did_remove |
104 |
| - }; |
105 |
| - tx.commit()?; |
106 |
| - if updated { |
107 |
| - inc!(Metrics, store_packets_removed) |
108 |
| - } |
109 |
| - Ok(updated) |
110 |
| - }) |
111 |
| - .await? |
| 212 | + let (tx, rx) = oneshot::channel(); |
| 213 | + self.send |
| 214 | + .send(Message::Remove { key: *key, res: tx }) |
| 215 | + .await?; |
| 216 | + Ok(rx.await?) |
112 | 217 | }
|
113 | 218 | }
|
114 | 219 |
|
|
0 commit comments