sui_indexer/
system_package_task.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::indexer_reader::IndexerReader;
5use std::time::Duration;
6use sui_types::SYSTEM_PACKAGE_ADDRESSES;
7use tokio_util::sync::CancellationToken;
8
9/// Background task responsible for evicting system packages from the package resolver's cache after
10/// detecting an epoch boundary.
11pub(crate) struct SystemPackageTask {
12    /// Holds the DB connection and also the package resolver to evict packages from.
13    reader: IndexerReader,
14    /// Signal to cancel the task.
15    cancel: CancellationToken,
16    /// Interval to sleep for between checks.
17    interval: Duration,
18}
19
20impl SystemPackageTask {
21    pub(crate) fn new(
22        reader: IndexerReader,
23        cancel: CancellationToken,
24        interval: Duration,
25    ) -> Self {
26        Self {
27            reader,
28            cancel,
29            interval,
30        }
31    }
32
33    pub(crate) async fn run(&self) {
34        let mut last_epoch: i64 = 0;
35        loop {
36            tokio::select! {
37                _ = self.cancel.cancelled() => {
38                    tracing::info!(
39                        "Shutdown signal received, terminating system package eviction task"
40                    );
41                    return;
42                }
43                _ = tokio::time::sleep(self.interval) => {
44                    let next_epoch = match self.reader.get_latest_epoch_info_from_db().await {
45                        Ok(epoch) => epoch.epoch,
46                        Err(e) => {
47                            tracing::error!("Failed to fetch latest epoch: {:?}", e);
48                            continue;
49                        }
50                    };
51
52                    if next_epoch > last_epoch {
53                        last_epoch = next_epoch;
54                        tracing::info!(
55                            "Detected epoch boundary, evicting system packages from cache"
56                        );
57                        self.reader
58                            .package_resolver()
59                            .package_store()
60                            .evict(SYSTEM_PACKAGE_ADDRESSES.iter().copied());
61                    }
62                }
63            }
64        }
65    }
66}