Skip to main content

torrust_clock/
lib.rs

1//! Time related functions and types.
2//!
3//! It's usually a good idea to control where the time comes from
4//! in an application so that it can be mocked for testing and it can be
5//! controlled in production so we get the intended behavior without
6//! relying on the specific time zone for the underlying system.
7//!
8//! Clocks use the type `DurationSinceUnixEpoch` which is a
9//! `std::time::Duration` since the Unix Epoch (timestamp).
10//!
11//! ```text
12//! Local time:     lun 2023-03-27 16:12:00 WEST
13//! Universal time: lun 2023-03-27 15:12:00 UTC
14//! Time zone:      Atlantic/Canary (WEST, +0100)
15//! Timestamp:      1679929914
16//! Duration:       1679929914.10167426
17//! ```
18//!
19//! > **NOTICE**: internally the `Duration` is stores it's main unit as seconds in a `u64` and it will
20//! > overflow in 584.9 billion years.
21//!
22//! > **NOTICE**: the timestamp does not depend on the time zone. That gives you
23//! > the ability to use the clock regardless of the underlying system time zone
24//! > configuration. See [Unix time Wikipedia entry](https://en.wikipedia.org/wiki/Unix_time).
25pub mod clock;
26pub mod conv;
27pub mod static_time;
28
29use tracing::instrument;
30
31/// A duration measured from the Unix Epoch (1970-01-01 00:00:00 UTC).
32///
33/// This is a type alias for [`std::time::Duration`]. It carries no
34/// tracker-specific logic and lives here so that `torrust-clock`
35/// has no dependency on `torrust-tracker-primitives`.
36pub type DurationSinceUnixEpoch = std::time::Duration;
37
38/// This code needs to be copied into each crate.
39/// Working version, for production.
40#[cfg(not(test))]
41#[allow(dead_code)]
42pub(crate) type CurrentClock = clock::Working;
43
44/// Stopped version, for testing.
45#[cfg(test)]
46#[allow(dead_code)]
47pub(crate) type CurrentClock = clock::Stopped;
48
49/// It initializes the application static values.
50///
51/// These values are accessible throughout the entire application:
52///
53/// - The time when the application started.
54/// - An ephemeral instance random seed. This seed is used for encryption and
55///   it's changed when the main application process is restarted.
56#[instrument(skip())]
57pub fn initialize_static() {
58    // Set the time of Torrust app starting
59    std::sync::LazyLock::force(&static_time::TIME_AT_APP_START);
60}