jetstreamer-plugin 0.6.0

Support crate for Jetstreamer containing plugin framework abstractions and utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use std::sync::Arc;

use clickhouse::{Client, Row};
use dashmap::DashMap;
use futures_util::FutureExt;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use solana_address::Address;
use solana_message::VersionedMessage;

use crate::{Plugin, PluginFuture};
use jetstreamer_firehose::firehose::{BlockData, TransactionData};

/// Per-slot accumulator: maps each pubkey to its mention count within that slot.
static PENDING_BY_SLOT: Lazy<
    DashMap<u64, DashMap<Address, u32, ahash::RandomState>, ahash::RandomState>,
> = Lazy::new(|| DashMap::with_hasher(ahash::RandomState::new()));

#[derive(Row, Deserialize, Serialize, Copy, Clone, Debug)]
struct PubkeyMention {
    slot: u32,
    timestamp: u32,
    pubkey: Address,
    num_mentions: u32,
}

#[derive(Debug, Clone)]
/// Tracks per-slot pubkey mention counts and writes them to ClickHouse.
///
/// For every transaction, all account keys referenced in the message (both static and loaded)
/// are counted. A ClickHouse `pubkey_mentions` table stores the aggregated count per
/// `(slot, pubkey)` pair using `ReplacingMergeTree` for safe parallel ingestion.
///
/// A companion `pubkeys` table assigns a unique auto-incremented id to each pubkey, maintained
/// via a materialised view so lookups by id are efficient.
pub struct PubkeyStatsPlugin;

impl PubkeyStatsPlugin {
    /// Creates a new instance.
    pub const fn new() -> Self {
        Self
    }

    fn take_slot_events(slot: u64, block_time: Option<i64>) -> Vec<PubkeyMention> {
        let timestamp = clamp_block_time(block_time);
        if let Some((_, pubkey_counts)) = PENDING_BY_SLOT.remove(&slot) {
            return pubkey_counts
                .into_iter()
                .map(|(pubkey, num_mentions)| PubkeyMention {
                    slot: slot.min(u32::MAX as u64) as u32,
                    timestamp,
                    pubkey,
                    num_mentions,
                })
                .collect();
        }
        Vec::new()
    }

    fn drain_all_pending(block_time: Option<i64>) -> Vec<PubkeyMention> {
        let timestamp = clamp_block_time(block_time);
        let slots: Vec<u64> = PENDING_BY_SLOT.iter().map(|entry| *entry.key()).collect();
        let mut rows = Vec::new();
        for slot in slots {
            if let Some((_, pubkey_counts)) = PENDING_BY_SLOT.remove(&slot) {
                rows.extend(pubkey_counts.into_iter().map(|(pubkey, num_mentions)| {
                    PubkeyMention {
                        slot: slot.min(u32::MAX as u64) as u32,
                        timestamp,
                        pubkey,
                        num_mentions,
                    }
                }));
            }
        }
        rows
    }
}

impl Default for PubkeyStatsPlugin {
    fn default() -> Self {
        Self::new()
    }
}

impl Plugin for PubkeyStatsPlugin {
    #[inline(always)]
    fn name(&self) -> &'static str {
        "Pubkey Stats"
    }

    #[inline(always)]
    fn on_transaction<'a>(
        &'a self,
        _thread_id: usize,
        _db: Option<Arc<Client>>,
        transaction: &'a TransactionData,
    ) -> PluginFuture<'a> {
        async move {
            let account_keys = match &transaction.transaction.message {
                VersionedMessage::Legacy(msg) => &msg.account_keys,
                VersionedMessage::V0(msg) => &msg.account_keys,
            };
            if account_keys.is_empty() {
                return Ok(());
            }

            let slot = transaction.slot;
            let slot_entry = PENDING_BY_SLOT
                .entry(slot)
                .or_insert_with(|| DashMap::with_hasher(ahash::RandomState::new()));
            for pubkey in account_keys {
                *slot_entry.entry(*pubkey).or_insert(0) += 1;
            }

            Ok(())
        }
        .boxed()
    }

    #[inline(always)]
    fn on_block(
        &self,
        _thread_id: usize,
        db: Option<Arc<Client>>,
        block: &BlockData,
    ) -> PluginFuture<'_> {
        let slot = block.slot();
        let block_time = block.block_time();
        let was_skipped = block.was_skipped();
        async move {
            if was_skipped {
                return Ok(());
            }

            let rows = Self::take_slot_events(slot, block_time);

            if let Some(db_client) = db
                && !rows.is_empty()
            {
                tokio::spawn(async move {
                    if let Err(err) = write_pubkey_mentions(db_client, rows).await {
                        log::error!("failed to write pubkey mentions: {}", err);
                    }
                });
            }

            Ok(())
        }
        .boxed()
    }

    #[inline(always)]
    fn on_load(&self, db: Option<Arc<Client>>) -> PluginFuture<'_> {
        async move {
            log::info!("Pubkey Stats Plugin loaded.");
            if let Some(db) = db {
                log::info!("Creating pubkey_mentions table if it does not exist...");
                db.query(
                    r#"
                    CREATE TABLE IF NOT EXISTS pubkey_mentions (
                        slot          UInt32,
                        timestamp     DateTime('UTC'),
                        pubkey        FixedString(32),
                        num_mentions  UInt32
                    )
                    ENGINE = ReplacingMergeTree(timestamp)
                    ORDER BY (slot, pubkey)
                    "#,
                )
                .execute()
                .await?;

                log::info!("Creating pubkeys table if it does not exist...");
                db.query(
                    r#"
                    CREATE TABLE IF NOT EXISTS pubkeys (
                        pubkey  FixedString(32),
                        id      UInt64
                    )
                    ENGINE = ReplacingMergeTree()
                    ORDER BY pubkey
                    "#,
                )
                .execute()
                .await?;

                log::info!("Creating pubkeys materialised view if it does not exist...");
                db.query(
                    r#"
                    CREATE MATERIALIZED VIEW IF NOT EXISTS pubkeys_mv TO pubkeys AS
                    SELECT
                        pubkey,
                        sipHash64(pubkey) AS id
                    FROM pubkey_mentions
                    GROUP BY pubkey
                    "#,
                )
                .execute()
                .await?;

                log::info!("done.");
            } else {
                log::warn!(
                    "Pubkey Stats Plugin running without ClickHouse; data will not be persisted."
                );
            }
            Ok(())
        }
        .boxed()
    }

    #[inline(always)]
    fn on_exit(&self, db: Option<Arc<Client>>) -> PluginFuture<'_> {
        async move {
            if let Some(db_client) = db {
                let rows = Self::drain_all_pending(None);
                if !rows.is_empty() {
                    write_pubkey_mentions(Arc::clone(&db_client), rows)
                        .await
                        .map_err(|err| -> Box<dyn std::error::Error + Send + Sync> {
                            Box::new(err)
                        })?;
                }
                backfill_pubkey_timestamps(db_client)
                    .await
                    .map_err(|err| -> Box<dyn std::error::Error + Send + Sync> { Box::new(err) })?;
            }
            Ok(())
        }
        .boxed()
    }
}

async fn write_pubkey_mentions(
    db: Arc<Client>,
    rows: Vec<PubkeyMention>,
) -> Result<(), clickhouse::error::Error> {
    if rows.is_empty() {
        return Ok(());
    }
    let mut insert = db.insert::<PubkeyMention>("pubkey_mentions").await?;
    for row in rows {
        insert.write(&row).await?;
    }
    insert.end().await?;
    Ok(())
}

fn clamp_block_time(block_time: Option<i64>) -> u32 {
    let Some(raw_ts) = block_time else {
        return 0;
    };
    if raw_ts < 0 {
        0
    } else if raw_ts > u32::MAX as i64 {
        u32::MAX
    } else {
        raw_ts as u32
    }
}

async fn backfill_pubkey_timestamps(db: Arc<Client>) -> Result<(), clickhouse::error::Error> {
    db.query(
        r#"
        INSERT INTO pubkey_mentions
        SELECT pm.slot,
               ss.block_time,
               pm.pubkey,
               pm.num_mentions
        FROM pubkey_mentions AS pm
        ANY INNER JOIN jetstreamer_slot_status AS ss USING (slot)
        WHERE pm.timestamp = toDateTime(0)
          AND ss.block_time > toDateTime(0)
        "#,
    )
    .execute()
    .await?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Plugin;
    use jetstreamer_firehose::firehose::{BlockData, TransactionData};
    use serial_test::serial;
    use solana_hash::Hash;
    use solana_message::VersionedMessage;
    use solana_message::legacy::Message as LegacyMessage;
    use solana_runtime::bank::KeyedRewardsAndNumPartitions;
    use solana_transaction::versioned::VersionedTransaction;
    use solana_transaction_status::TransactionStatusMeta;

    fn make_tx(slot: u64, account_keys: Vec<Address>) -> TransactionData {
        let message = LegacyMessage {
            account_keys,
            ..LegacyMessage::default()
        };
        TransactionData {
            slot,
            transaction_slot_index: 0,
            signature: Default::default(),
            message_hash: Hash::default(),
            is_vote: false,
            transaction_status_meta: TransactionStatusMeta {
                status: Ok(()),
                fee: 0,
                pre_balances: vec![],
                post_balances: vec![],
                inner_instructions: None,
                log_messages: None,
                pre_token_balances: None,
                post_token_balances: None,
                rewards: None,
                loaded_addresses: Default::default(),
                return_data: None,
                compute_units_consumed: Some(0),
                cost_units: None,
            },
            transaction: VersionedTransaction {
                signatures: vec![],
                message: VersionedMessage::Legacy(message),
            },
        }
    }

    fn make_block(slot: u64, block_time: Option<i64>) -> BlockData {
        BlockData::Block {
            slot,
            parent_slot: slot.saturating_sub(1),
            blockhash: Hash::default(),
            parent_blockhash: Hash::default(),
            rewards: KeyedRewardsAndNumPartitions {
                keyed_rewards: vec![],
                num_partitions: None,
            },
            block_time,
            block_height: Some(slot),
            executed_transaction_count: 0,
            entry_count: 0,
        }
    }

    fn clear_pending() {
        PENDING_BY_SLOT.clear();
    }

    #[test]
    fn clamp_block_time_none_returns_zero() {
        assert_eq!(clamp_block_time(None), 0);
    }

    #[test]
    fn clamp_block_time_negative_returns_zero() {
        assert_eq!(clamp_block_time(Some(-100)), 0);
    }

    #[test]
    fn clamp_block_time_overflow_returns_max() {
        assert_eq!(clamp_block_time(Some(u32::MAX as i64 + 1)), u32::MAX);
    }

    #[test]
    fn clamp_block_time_normal() {
        assert_eq!(clamp_block_time(Some(1_700_000_000)), 1_700_000_000);
    }

    #[serial]
    #[tokio::test]
    async fn single_transaction_counts_all_account_keys() {
        clear_pending();
        let plugin = PubkeyStatsPlugin::new();
        let key_a = Address::from([1u8; 32]);
        let key_b = Address::from([2u8; 32]);
        let key_c = Address::from([3u8; 32]);
        let tx = make_tx(100, vec![key_a, key_b, key_c]);

        plugin.on_transaction(0, None, &tx).await.unwrap();

        let events = PubkeyStatsPlugin::take_slot_events(100, Some(1_700_000_000));
        assert_eq!(events.len(), 3);
        for event in &events {
            assert_eq!(event.num_mentions, 1);
            assert_eq!(event.slot, 100);
            assert_eq!(event.timestamp, 1_700_000_000);
        }
    }

    #[serial]
    #[tokio::test]
    async fn duplicate_keys_in_single_transaction_accumulate() {
        clear_pending();
        let plugin = PubkeyStatsPlugin::new();
        let key_a = Address::from([1u8; 32]);
        let tx = make_tx(200, vec![key_a, key_a, key_a]);

        plugin.on_transaction(0, None, &tx).await.unwrap();

        let events = PubkeyStatsPlugin::take_slot_events(200, None);
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].num_mentions, 3);
        assert_eq!(events[0].pubkey, key_a);
    }

    #[serial]
    #[tokio::test]
    async fn multiple_transactions_same_slot_accumulate() {
        clear_pending();
        let plugin = PubkeyStatsPlugin::new();
        let key_a = Address::from([10u8; 32]);
        let key_b = Address::from([20u8; 32]);

        let tx1 = make_tx(300, vec![key_a, key_b]);
        let tx2 = make_tx(300, vec![key_a]);

        plugin.on_transaction(0, None, &tx1).await.unwrap();
        plugin.on_transaction(0, None, &tx2).await.unwrap();

        let events = PubkeyStatsPlugin::take_slot_events(300, None);
        assert_eq!(events.len(), 2);
        let a_event = events.iter().find(|e| e.pubkey == key_a).unwrap();
        let b_event = events.iter().find(|e| e.pubkey == key_b).unwrap();
        assert_eq!(a_event.num_mentions, 2);
        assert_eq!(b_event.num_mentions, 1);
    }

    #[serial]
    #[tokio::test]
    async fn different_slots_are_independent() {
        clear_pending();
        let plugin = PubkeyStatsPlugin::new();
        let key = Address::from([42u8; 32]);

        let tx1 = make_tx(400, vec![key]);
        let tx2 = make_tx(401, vec![key]);

        plugin.on_transaction(0, None, &tx1).await.unwrap();
        plugin.on_transaction(0, None, &tx2).await.unwrap();

        let events_400 = PubkeyStatsPlugin::take_slot_events(400, None);
        let events_401 = PubkeyStatsPlugin::take_slot_events(401, None);
        assert_eq!(events_400.len(), 1);
        assert_eq!(events_401.len(), 1);
        assert_eq!(events_400[0].num_mentions, 1);
        assert_eq!(events_401[0].num_mentions, 1);
    }

    #[serial]
    #[tokio::test]
    async fn take_slot_events_drains_slot() {
        clear_pending();
        let plugin = PubkeyStatsPlugin::new();
        let tx = make_tx(500, vec![Address::from([1u8; 32])]);
        plugin.on_transaction(0, None, &tx).await.unwrap();

        let first = PubkeyStatsPlugin::take_slot_events(500, None);
        let second = PubkeyStatsPlugin::take_slot_events(500, None);
        assert_eq!(first.len(), 1);
        assert!(second.is_empty());
    }

    #[serial]
    #[tokio::test]
    async fn drain_all_pending_collects_all_slots() {
        clear_pending();
        let plugin = PubkeyStatsPlugin::new();

        let tx1 = make_tx(600, vec![Address::from([1u8; 32])]);
        let tx2 = make_tx(601, vec![Address::from([2u8; 32])]);
        let tx3 = make_tx(602, vec![Address::from([3u8; 32])]);

        plugin.on_transaction(0, None, &tx1).await.unwrap();
        plugin.on_transaction(0, None, &tx2).await.unwrap();
        plugin.on_transaction(0, None, &tx3).await.unwrap();

        let events = PubkeyStatsPlugin::drain_all_pending(Some(1_000));
        assert_eq!(events.len(), 3);
        assert!(PENDING_BY_SLOT.is_empty());
    }

    #[serial]
    #[tokio::test]
    async fn empty_account_keys_produces_no_events() {
        clear_pending();
        let plugin = PubkeyStatsPlugin::new();
        let tx = make_tx(700, vec![]);
        plugin.on_transaction(0, None, &tx).await.unwrap();
        assert!(PENDING_BY_SLOT.is_empty());
    }

    #[serial]
    #[tokio::test]
    async fn on_block_drains_pending_slot() {
        clear_pending();
        let plugin = PubkeyStatsPlugin::new();
        let tx = make_tx(800, vec![Address::from([1u8; 32])]);
        plugin.on_transaction(0, None, &tx).await.unwrap();
        assert!(!PENDING_BY_SLOT.is_empty());

        let block = make_block(800, Some(1_700_000_000));
        plugin.on_block(0, None, &block).await.unwrap();

        // on_block without db just drains, doesn't write
        assert!(!PENDING_BY_SLOT.contains_key(&800));
    }

    #[serial]
    #[tokio::test]
    async fn skipped_block_does_not_drain() {
        clear_pending();
        let plugin = PubkeyStatsPlugin::new();
        let tx = make_tx(900, vec![Address::from([1u8; 32])]);
        plugin.on_transaction(0, None, &tx).await.unwrap();

        let skipped = BlockData::PossibleLeaderSkipped { slot: 900 };
        plugin.on_block(0, None, &skipped).await.unwrap();

        assert!(PENDING_BY_SLOT.contains_key(&900));
        clear_pending();
    }

    #[test]
    fn plugin_name() {
        assert_eq!(PubkeyStatsPlugin::new().name(), "Pubkey Stats");
    }

    #[serial]
    #[test]
    fn slot_clamped_to_u32_max() {
        let slot = u64::from(u32::MAX) + 100;
        PENDING_BY_SLOT.clear();
        let inner = DashMap::with_hasher(ahash::RandomState::new());
        inner.insert(Address::from([1u8; 32]), 5);
        PENDING_BY_SLOT.insert(slot, inner);

        let events = PubkeyStatsPlugin::take_slot_events(slot, None);
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].slot, u32::MAX);
    }
}