tycho-collator 0.3.6

A collator node.
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
use std::collections::BTreeMap;
use std::sync::Arc;

use anyhow::Result;
use tycho_block_util::queue::{QueueKey, QueuePartitionIdx, RouterAddr, RouterPartitions};
use tycho_storage::StorageContext;
use tycho_types::cell::HashBytes;
use tycho_types::models::{BlockId, BlockIdShort, ShardIdent};
use tycho_util::metrics::HistogramGuard;
use tycho_util::{FastHashMap, FastHashSet};

use crate::internal_queue::state::state_iterator::{StateIterator, StateIteratorImpl};
use crate::internal_queue::types::diff::{DiffZone, QueueDiffWithMessages};
use crate::internal_queue::types::message::InternalMessageValue;
use crate::internal_queue::types::ranges::QueueShardRange;
use crate::internal_queue::types::router::PartitionRouter;
use crate::internal_queue::types::stats::{
    AccountStatistics, DiffStatistics, SeparatedStatisticsByPartitions,
};
use crate::storage::InternalQueueStorage;
use crate::storage::models::{
    CommitPointerValue, DiffInfo, DiffInfoKey, DiffTailKey, ShardsInternalMessagesKey, StatKey,
};
use crate::storage::snapshot::InternalQueueSnapshot;
use crate::storage::transaction::InternalQueueTransaction;
use crate::types::ProcessedTo;

// FACTORY

pub trait QueueStateFactory<V: InternalMessageValue> {
    type QueueState: QueueState<V>;

    fn create(&self) -> Result<Self::QueueState>;
}

impl<F, R, V> QueueStateFactory<V> for F
where
    F: Fn() -> Result<R>,
    R: QueueState<V>,
    V: InternalMessageValue,
{
    type QueueState = R;

    fn create(&self) -> Result<Self::QueueState> {
        self()
    }
}

pub struct QueueStateImplFactory {
    pub storage: InternalQueueStorage,
}

impl QueueStateImplFactory {
    pub fn new(ctx: StorageContext) -> Result<Self> {
        let storage = InternalQueueStorage::open(ctx)?;
        Ok(Self { storage })
    }
}

impl<V: InternalMessageValue> QueueStateFactory<V> for QueueStateImplFactory {
    type QueueState = QueueStateStdImpl;

    fn create(&self) -> Result<Self::QueueState> {
        Ok(QueueStateStdImpl {
            storage: self.storage.clone(),
        })
    }
}

// TRAIT

pub trait QueueState<V: InternalMessageValue>: Send + Sync {
    /// Create snapshot
    fn snapshot(&self) -> InternalQueueSnapshot;

    /// Create iterator for given partition and ranges
    fn iterator(
        &self,
        snapshot: &InternalQueueSnapshot,
        receiver: ShardIdent,
        partition: QueuePartitionIdx,
        ranges: &[QueueShardRange],
    ) -> Result<Box<dyn StateIterator<V>>>;

    /// Delete messages in given partition and ranges
    fn delete(&self, partition: QueuePartitionIdx, ranges: &[QueueShardRange]) -> Result<()>;

    /// Set commit pointers and last committed mc block id.
    /// ATTENTION! Overrides old value without checks. Should validate the new value in the calling code.
    fn commit(
        &self,
        commit_pointers: FastHashMap<ShardIdent, (QueueKey, u32)>,
        mc_block_id: &BlockId,
    ) -> Result<()>;

    /// Load statistics for given partition and ranges
    fn load_diff_statistics(
        &self,
        partition: QueuePartitionIdx,
        range: &QueueShardRange,
        result: &mut AccountStatistics,
    ) -> Result<()>;

    /// Load separated diff statistics for the specified partitions and range
    fn load_separated_diff_statistics(
        &self,
        partitions: &FastHashSet<QueuePartitionIdx>,
        range: &QueueShardRange,
    ) -> Result<SeparatedStatisticsByPartitions>;

    /// Get mc block id on which the queue was committed.
    /// Returns None if queue was not committed
    fn get_last_committed_mc_block_id(&self) -> Result<Option<BlockId>>;

    /// Get diffs tail len from uncommitted state and committed state
    fn get_diffs_tail_len(&self, shard_ident: &ShardIdent, from: &QueueKey) -> u32;

    /// Get diff info by diff seqno
    fn get_diff_info(
        &self,
        shard_ident: &ShardIdent,
        seqno: u32,
        zone: DiffZone,
    ) -> Result<Option<DiffInfo>>;

    /// Get last applied block seqno by shard ident from committed and uncommited zone
    fn get_last_applied_seqno(&self, shard_ident: &ShardIdent) -> Result<Option<u32>>;

    /// Get commit pointers
    fn get_commit_pointers(&self) -> Result<FastHashMap<ShardIdent, CommitPointerValue>>;

    fn write_diff(
        &self,
        block_id_short: &BlockIdShort,
        statistics: &DiffStatistics,
        hash: HashBytes,
        diff: QueueDiffWithMessages<V>,
    ) -> Result<()>;

    fn clear_uncommitted(
        &self,
        partitions: &FastHashSet<QueuePartitionIdx>,
        top_shards: &[ShardIdent],
    ) -> Result<()>;
}

// IMPLEMENTATION

pub struct QueueStateStdImpl {
    storage: InternalQueueStorage,
}

impl<V: InternalMessageValue> QueueState<V> for QueueStateStdImpl {
    fn snapshot(&self) -> InternalQueueSnapshot {
        let _histogram = HistogramGuard::begin("tycho_internal_queue_snapshot_time");
        self.storage.make_snapshot()
    }

    fn iterator(
        &self,
        snapshot: &InternalQueueSnapshot,
        receiver: ShardIdent,
        partition: QueuePartitionIdx,
        ranges: &[QueueShardRange],
    ) -> Result<Box<dyn StateIterator<V>>> {
        let mut shards_iters = Vec::new();

        for range in ranges {
            let from = ShardsInternalMessagesKey::new(partition, range.shard_ident, range.from);
            let to = ShardsInternalMessagesKey::new(partition, range.shard_ident, range.to);
            shards_iters.push((snapshot.iter_messages(from, to), range.shard_ident));
        }

        let iterator = StateIteratorImpl::new(shards_iters, receiver)?;
        Ok(Box::new(iterator))
    }

    fn delete(&self, partition: QueuePartitionIdx, ranges: &[QueueShardRange]) -> Result<()> {
        let mut queue_ranges = vec![];
        for range in ranges {
            queue_ranges.push(crate::storage::models::QueueRange {
                partition,
                shard_ident: range.shard_ident,
                from: range.from,
                to: range.to,
            });
        }

        let tx = self.storage.begin_transaction();
        tx.delete(&queue_ranges)?;
        tx.write()
    }

    fn commit(
        &self,
        commit_pointers: FastHashMap<ShardIdent, (QueueKey, u32)>,
        mc_block_id: &BlockId,
    ) -> Result<()> {
        let mut tx = self.storage.begin_transaction();
        tx.commit_messages(commit_pointers)?;
        tx.set_last_committed_mc_block_id(mc_block_id)?;
        tx.write()?;
        let db = self.storage.db();
        db.rocksdb()
            .flush_cf(&db.internal_message_commit_pointer.cf())?;
        db.rocksdb().flush_cf(&db.internal_message_var.cf())?;
        Ok(())
    }

    fn load_diff_statistics(
        &self,
        partition: QueuePartitionIdx,
        range: &QueueShardRange,
        result: &mut AccountStatistics,
    ) -> Result<()> {
        let _histogram = HistogramGuard::begin("tycho_internal_queue_statistics_load_time");
        let snapshot = self.storage.make_snapshot();
        snapshot.collect_stats_in_range(
            &range.shard_ident,
            partition,
            &range.from,
            &range.to,
            result,
        )
    }

    fn load_separated_diff_statistics(
        &self,
        partitions: &FastHashSet<QueuePartitionIdx>,
        range: &QueueShardRange,
    ) -> Result<SeparatedStatisticsByPartitions> {
        let _histogram =
            HistogramGuard::begin("tycho_internal_queue_separated_statistics_load_time");
        let snapshot = self.storage.make_snapshot();

        let result = snapshot.collect_separated_stats_in_range_for_partitions(
            &range.shard_ident,
            partitions,
            &range.from,
            &range.to,
        )?;

        Ok(result)
    }

    fn get_last_committed_mc_block_id(&self) -> Result<Option<BlockId>> {
        let snapshot = self.storage.make_snapshot();
        snapshot.get_last_committed_mc_block_id()
    }

    fn get_diffs_tail_len(&self, shard_ident: &ShardIdent, from: &QueueKey) -> u32 {
        let snapshot = self.storage.make_snapshot();
        snapshot.calc_diffs_tail(&DiffTailKey {
            shard_ident: *shard_ident,
            max_message: *from,
        })
    }

    fn get_diff_info(
        &self,
        shard_ident: &ShardIdent,
        seqno: u32,
        zone: DiffZone,
    ) -> Result<Option<DiffInfo>> {
        let snapshot = self.storage.make_snapshot();

        let diff_info_bytes = snapshot.get_diff_info(&DiffInfoKey {
            shard_ident: *shard_ident,
            seqno,
        })?;

        let diff_info_bytes = match diff_info_bytes {
            Some(bytes) => bytes,
            None => return Ok(None),
        };

        let diff_info: DiffInfo = tl_proto::deserialize(&diff_info_bytes)?;

        match zone {
            DiffZone::Both => {}
            DiffZone::Committed => {
                let commit_pointers = snapshot.read_commit_pointers()?;
                if let Some(commit_pointer) = commit_pointers.get(shard_ident) {
                    // if true then diff is in uncommitted zone
                    if commit_pointer.queue_key < diff_info.max_message {
                        return Ok(None);
                    }
                } else {
                    return Ok(None);
                }
            }
            DiffZone::Uncommitted => {
                let commit_pointers = snapshot.read_commit_pointers()?;
                if let Some(commit_pointer) = commit_pointers.get(shard_ident) {
                    // if true then diff is in committed zone
                    if commit_pointer.queue_key >= diff_info.max_message {
                        return Ok(None);
                    }
                }
            }
        }

        Ok(Some(diff_info))
    }

    fn get_last_applied_seqno(&self, shard_ident: &ShardIdent) -> Result<Option<u32>> {
        let snapshot = self.storage.make_snapshot();
        snapshot.get_last_applied_diff_seqno(shard_ident)
    }

    fn get_commit_pointers(&self) -> Result<FastHashMap<ShardIdent, CommitPointerValue>> {
        self.storage.make_snapshot().read_commit_pointers()
    }

    fn write_diff(
        &self,
        block_id_short: &BlockIdShort,
        statistics: &DiffStatistics,
        hash: HashBytes,
        diff: QueueDiffWithMessages<V>,
    ) -> Result<()> {
        let mut tx = self.storage.begin_transaction();

        Self::add_messages(
            &mut tx,
            block_id_short.shard,
            &diff.partition_router,
            &diff.messages,
        )?;
        Self::add_statistics(&mut tx, statistics)?;
        Self::add_diff_tail(&mut tx, block_id_short, statistics.max_message());

        let src_router_partition = diff.partition_router.to_router_partitions_src();
        let dst_router_partition = diff.partition_router.to_router_partitions_dst();

        Self::add_diff_info(
            &mut tx,
            block_id_short,
            statistics,
            hash,
            diff.processed_to,
            src_router_partition,
            dst_router_partition,
        );

        let _histogram = HistogramGuard::begin("tycho_internal_queue_write_diff_time");

        let labels = [("workchain", block_id_short.shard.workchain().to_string())];

        let (batch_len, batch_size) = tx.size();

        metrics::gauge!("tycho_internal_queue_write_diff_batch_len", &labels).set(batch_len as f64);
        metrics::gauge!("tycho_internal_queue_write_diff_batch_size", &labels)
            .set(batch_size as f64);
        metrics::gauge!("tycho_internal_queue_write_diff_messages_count", &labels)
            .set(diff.messages.len() as f64);

        tx.write()?;

        Ok(())
    }

    fn clear_uncommitted(
        &self,
        partitions: &FastHashSet<QueuePartitionIdx>,
        top_shards: &[ShardIdent],
    ) -> Result<()> {
        let snapshot = self.storage.make_snapshot();
        let pointers = snapshot.read_commit_pointers()?;
        let tx = self.storage.begin_transaction();
        tx.clear_uncommitted(partitions, &pointers, top_shards)?;
        tx.write()
    }
}

impl QueueStateStdImpl {
    /// write new messages to storage
    fn add_messages<V: InternalMessageValue>(
        internal_queue_tx: &mut InternalQueueTransaction,
        source: ShardIdent,
        partition_router: &PartitionRouter,
        messages: &BTreeMap<QueueKey, Arc<V>>,
    ) -> Result<()> {
        let _histogram = HistogramGuard::begin("tycho_internal_queue_apply_diff_add_messages_time");
        let mut buffer = Vec::new();
        for (internal_message_key, message) in messages {
            let destination = message.destination();
            let partition = partition_router.get_partition(Some(message.source()), destination);

            buffer.clear();
            message.serialize(&mut buffer);

            internal_queue_tx.insert_message(
                &ShardsInternalMessagesKey::new(partition, source, *internal_message_key),
                destination,
                &buffer,
            );
        }

        Ok(())
    }

    /// write new statistics to storage
    fn add_statistics(
        internal_queue_tx: &mut InternalQueueTransaction,
        diff_statistics: &DiffStatistics,
    ) -> Result<()> {
        let _histogram =
            HistogramGuard::begin("tycho_internal_queue_apply_diff_add_statistics_time");
        let shard_ident = diff_statistics.shard_ident();
        let max_message = diff_statistics.max_message();

        for (partition, values) in diff_statistics.iter() {
            for (addr, count) in values {
                let Some(dest) = RouterAddr::from_int_addr(addr) else {
                    anyhow::bail!("cannot add VarAddr to router statistics");
                };

                let key = StatKey {
                    shard_ident: *shard_ident,
                    partition: *partition,
                    max_message: *max_message,
                    dest,
                };

                internal_queue_tx.insert_statistics(&key, *count);
            }
            metrics::counter!(
                "tycho_internal_queue_apply_diff_add_statistics_accounts_count",
                "partition" => partition.to_string(),
            )
            .increment(values.len() as u64);
        }

        Ok(())
    }

    fn add_diff_tail(
        internal_queue_tx: &mut InternalQueueTransaction,
        block_id_short: &BlockIdShort,
        max_message: &QueueKey,
    ) {
        internal_queue_tx.insert_diff_tail(
            &DiffTailKey {
                shard_ident: block_id_short.shard,
                max_message: *max_message,
            },
            block_id_short.seqno.to_le_bytes().as_slice(),
        );
    }

    fn add_diff_info(
        internal_queue_tx: &mut InternalQueueTransaction,
        block_id_short: &BlockIdShort,
        diff_statistics: &DiffStatistics,
        hash: HashBytes,
        processed_to: ProcessedTo,
        router_partitions_src: RouterPartitions,
        router_partitions_dst: RouterPartitions,
    ) {
        let shard_messages_count = diff_statistics.shards_messages_count();

        let key = DiffInfoKey {
            shard_ident: block_id_short.shard,
            seqno: block_id_short.seqno,
        };

        let diff_info = DiffInfo {
            min_message: *diff_statistics.min_message(),
            max_message: *diff_statistics.max_message(),
            shards_messages_count: shard_messages_count.clone(),
            hash,
            processed_to,
            router_partitions_src,
            router_partitions_dst,
            seqno: block_id_short.seqno,
        };

        let serialized_diff_info = tl_proto::serialize(diff_info);

        internal_queue_tx.insert_diff_info(&key, &serialized_diff_info);
    }
}