diff --git a/.github/workflows/extensions-test.yml b/.github/workflows/extensions-test.yml index a02c6ab316..5a58349f4f 100644 --- a/.github/workflows/extensions-test.yml +++ b/.github/workflows/extensions-test.yml @@ -17,7 +17,7 @@ concurrency: jobs: c-tests: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 defaults: run: working-directory: libsql-sqlite3 @@ -41,7 +41,7 @@ jobs: make test rs-tests: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 defaults: run: working-directory: libsql-sqlite3 @@ -61,7 +61,7 @@ jobs: cargo test --features=loadable_extension extensions-tests: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 name: Extensions Tests steps: diff --git a/.github/workflows/golang-bindings.yml b/.github/workflows/golang-bindings.yml index d4924906c6..329b55e3fd 100644 --- a/.github/workflows/golang-bindings.yml +++ b/.github/workflows/golang-bindings.yml @@ -14,7 +14,7 @@ concurrency: jobs: golang-bindings: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 services: sqld: @@ -37,7 +37,9 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: '>=1.21' + # 1.27.4 rejects the LTO section in the static lib built above (".llvmbc" in + # #cgo LDFLAGS); 1.27.3 is the last version that builds go-libsql. + go-version: '1.27.3' - name: get TCL run: sudo apt-get install -y tcl8.6-dev diff --git a/Cargo.lock b/Cargo.lock index c091acdc86..8e6c987c69 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -915,8 +915,8 @@ dependencies = [ "aws-config", "aws-sdk-s3", "bytes", - "chrono", "futures-core", + "jiff", "libsql-sys", "libsql_replication", "metrics", @@ -940,8 +940,8 @@ dependencies = [ "aws-smithy-types", "bottomless", "bytes", - "chrono", "clap 4.5.9", + "jiff", "libsql-rusqlite", "libsql-sys", "tokio", @@ -1159,7 +1159,6 @@ dependencies = [ "iana-time-zone", "js-sys", "num-traits", - "serde", "wasm-bindgen", "windows-link", ] @@ -2810,6 +2809,58 @@ dependencies = [ "cc", ] +[[package]] +name = "jiff" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + +[[package]] +name = "jiff-tzdb-platform" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jobserver" version = "0.1.31" @@ -3033,7 +3084,6 @@ dependencies = [ "bytes", "bytesize", "cbc", - "chrono", "clap 4.5.9", "console-subscriber", "crc", @@ -3054,6 +3104,7 @@ dependencies = [ "indicatif", "insta", "itertools 0.10.5", + "jiff", "jsonwebtoken", "libsql", "libsql-client", @@ -3859,9 +3910,18 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.6.0" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] [[package]] name = "powerfmt" @@ -3920,9 +3980,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.86" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] @@ -4078,9 +4138,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.36" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -5049,6 +5109,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "0.1.2" diff --git a/bottomless-cli/Cargo.toml b/bottomless-cli/Cargo.toml index 264611b748..f4335c793c 100644 --- a/bottomless-cli/Cargo.toml +++ b/bottomless-cli/Cargo.toml @@ -17,7 +17,7 @@ aws-sdk-s3 = "1" aws-smithy-types = "1" bottomless = { version = "0", path = "../bottomless" } bytes = "1" -chrono = "0.4.23" +jiff = "1" clap = { version = "4.0.29", features = ["derive"] } libsql-sys = { path = "../libsql-sys" } tokio = { version = "1.23.0", features = ["macros", "rt", "rt-multi-thread"] } diff --git a/bottomless-cli/src/main.rs b/bottomless-cli/src/main.rs index d81b3ac39c..79856aea18 100644 --- a/bottomless-cli/src/main.rs +++ b/bottomless-cli/src/main.rs @@ -1,8 +1,8 @@ use anyhow::{anyhow, Result}; use aws_sdk_s3::Client; use bytes::Bytes; -use chrono::NaiveDateTime; use clap::{Parser, Subcommand}; +use jiff::civil::{Date, DateTime}; use libsql_sys::{connection::NO_AUTOCHECKPOINT, wal::Sqlite3WalManager}; use rusqlite::params; use std::path::PathBuf; @@ -59,15 +59,17 @@ enum Commands { #[clap( long, conflicts_with = "generation", - long_help = "List only generations older than given date" + long_help = "List only generations older than given date", + value_parser = bottomless::replicator::parse_date )] - older_than: Option, + older_than: Option, #[clap( long, conflicts_with = "generation", - long_help = "List only generations newer than given date" + long_help = "List only generations newer than given date", + value_parser = bottomless::replicator::parse_date )] - newer_than: Option, + newer_than: Option, #[clap( long, short, @@ -89,7 +91,8 @@ enum Commands { conflicts_with = "generation", long_help = "UTC timestamp which is an upper bound for the transactions to be restored." )] - utc_time: Option, + #[clap(value_parser = bottomless::replicator::parse_utc_datetime)] + utc_time: Option, #[clap(long, short, conflicts_with_all = ["generation", "utc_time"], long_help = "Restore from a local directory")] from_dir: Option, }, @@ -107,7 +110,8 @@ enum Commands { conflicts_with = "generation", long_help = "UTC timestamp which is an upper bound for the transactions to be verified." )] - utc_time: Option, + #[clap(value_parser = bottomless::replicator::parse_utc_datetime)] + utc_time: Option, }, #[clap(about = "Remove given generation from remote storage")] Rm { @@ -116,9 +120,10 @@ enum Commands { #[clap( long, conflicts_with = "generation", - long_help = "Remove generations older than given date" + long_help = "Remove generations older than given date", + value_parser = bottomless::replicator::parse_date )] - older_than: Option, + older_than: Option, #[clap(long, short)] verbose: bool, }, diff --git a/bottomless-cli/src/replicator_extras.rs b/bottomless-cli/src/replicator_extras.rs index 94670bd07f..a3dca15e7c 100644 --- a/bottomless-cli/src/replicator_extras.rs +++ b/bottomless-cli/src/replicator_extras.rs @@ -3,7 +3,9 @@ use aws_sdk_s3::error::SdkError; use aws_sdk_s3::types::ObjectAttributes; use aws_sdk_s3::Client; use aws_smithy_types::date_time::Format; -use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; +use jiff::civil::{Date, DateTime}; +use jiff::tz::TimeZone; +use jiff::Timestamp; use tokio::io::BufReader; pub(crate) struct Replicator { @@ -24,15 +26,18 @@ impl std::ops::DerefMut for Replicator { } } -fn uuid_to_datetime(uuid: &uuid::Uuid) -> chrono::NaiveDateTime { +fn uuid_to_datetime(uuid: &uuid::Uuid) -> DateTime { let timestamp = bottomless::replicator::Replicator::generation_to_timestamp(uuid); let (seconds, _) = timestamp .as_ref() .map(uuid::Timestamp::to_unix) .unwrap_or_default(); - chrono::DateTime::from_timestamp_millis((seconds * 1000) as i64) - .unwrap() - .naive_utc() + TimeZone::UTC.to_datetime(Timestamp::from_second(seconds as i64).unwrap_or(Timestamp::MAX)) +} + +/// `2026-11-30 12:00:00`, as the listings have always printed a UTC datetime. +fn fmt_datetime(datetime: &DateTime) -> String { + datetime.strftime("%Y-%m-%d %H:%M:%S").to_string() } pub(crate) async fn detect_db(client: &Client, bucket: &str, namespace: &str) -> Option { @@ -95,8 +100,8 @@ impl Replicator { pub(crate) async fn list_generations( &self, limit: Option, - older_than: Option, - newer_than: Option, + older_than: Option, + newer_than: Option, verbose: bool, ) -> Result<()> { let mut next_marker = None; @@ -130,19 +135,23 @@ impl Replicator { let prefix = &prefix[self.db_name.len() + 1..prefix.len() - 1]; let uuid = uuid::Uuid::try_parse(prefix)?; let datetime = uuid_to_datetime(&uuid); - if datetime.date() < newer_than.unwrap_or(chrono::NaiveDate::MIN) { + if datetime.date() < newer_than.unwrap_or(Date::MIN) { continue; } - if datetime.date() > older_than.unwrap_or(chrono::NaiveDate::MAX) { + if datetime.date() > older_than.unwrap_or(Date::MAX) { continue; } - println!("{} (created: {})", uuid, datetime.and_utc().to_rfc3339()); + println!( + "{} (created: {})", + uuid, + datetime.strftime("%Y-%m-%dT%H:%M:%S+00:00") + ); if verbose { let counter = self.get_remote_change_counter(&uuid).await?; let consistent_frame = self.get_last_consistent_frame(&uuid).await?; let m = self.get_metadata(&uuid).await?; let parent = self.get_dependency(&uuid).await?; - println!("\tcreated at (UTC): {datetime}"); + println!("\tcreated at (UTC): {}", fmt_datetime(&datetime)); println!("\tchange counter: {counter:?}"); println!("\tconsistent WAL frame: {consistent_frame}"); if let Some((page_size, crc)) = m { @@ -169,17 +178,23 @@ impl Replicator { } } - pub(crate) async fn remove_many(&self, older_than: NaiveDate, verbose: bool) -> Result<()> { - let older_than = NaiveDateTime::new(older_than, NaiveTime::MIN); + pub(crate) async fn remove_many(&self, older_than: Date, verbose: bool) -> Result<()> { + let older_than = older_than.to_datetime(jiff::civil::Time::midnight()); let delete_all = self.inner.delete_all(Some(older_than)).await?; if verbose { - println!("Tombstoned {} at {}", self.inner.db_path, older_than); + println!( + "Tombstoned {} at {}", + self.inner.db_path, + fmt_datetime(&older_than) + ); } let removed_generations = delete_all.commit().await?; if verbose { println!( "Removed {} generations of {} up to {}", - removed_generations, self.inner.db_path, older_than + removed_generations, + self.inner.db_path, + fmt_datetime(&older_than) ); } Ok(()) @@ -253,7 +268,10 @@ impl Replicator { let meta = self.get_metadata(&generation).await?; let dep = self.get_dependency(&generation).await?; println!("Generation {} for {}", generation, self.db_name); - println!("\tcreated at: {}", uuid_to_datetime(&generation)); + println!( + "\tcreated at: {}", + fmt_datetime(&uuid_to_datetime(&generation)) + ); println!("\tchange counter: {counter:?}"); println!("\tconsistent WAL frame: {consistent_frame}"); if let Some((page_size, crc)) = meta { diff --git a/bottomless/Cargo.toml b/bottomless/Cargo.toml index 59e5cb5dfa..5f0554265e 100644 --- a/bottomless/Cargo.toml +++ b/bottomless/Cargo.toml @@ -21,7 +21,7 @@ tokio-util = "0.7" tracing = "0.1.37" tracing-subscriber = "0.3.16" arc-swap = "1.6" -chrono = "0.4.23" +jiff = "1" uuid = "1.4.1" rand = "0.8.5" futures-core = "0.3.29" diff --git a/bottomless/src/backup.rs b/bottomless/src/backup.rs index 96d531d1b1..97451dbb97 100644 --- a/bottomless/src/backup.rs +++ b/bottomless/src/backup.rs @@ -85,7 +85,7 @@ impl WalCopier { let mut ready_ranges = 0; for start in frames.clone().step_by(self.max_frames_per_batch) { let period_start = Instant::now(); - let timestamp = chrono::Utc::now().timestamp() as u64; + let timestamp = jiff::Timestamp::now().as_second() as u64; let end = (start + self.max_frames_per_batch as u32).min(frames.end); let len = (end - start) as usize; let fdesc = format!( diff --git a/bottomless/src/replicator.rs b/bottomless/src/replicator.rs index 6f318fd125..a9d9199455 100644 --- a/bottomless/src/replicator.rs +++ b/bottomless/src/replicator.rs @@ -16,7 +16,9 @@ use aws_sdk_s3::operation::list_objects::ListObjectsOutput; use aws_sdk_s3::primitives::ByteStream; use aws_sdk_s3::{Client, Config}; use bytes::{Buf, Bytes}; -use chrono::{DateTime, NaiveDateTime, TimeZone, Utc}; +use jiff::civil::DateTime; +use jiff::tz::TimeZone; +use jiff::Timestamp; use libsql_replication::injector::Injector as _; use libsql_replication::rpc::replication::Frame as RpcFrame; use libsql_sys::{Cipher, EncryptionConfig}; @@ -41,6 +43,41 @@ use uuid::{NoContext, Uuid}; /// consecutive generations has to have a snapshot included. const MAX_RESTORE_STACK_DEPTH: usize = 100; +/// Tombstone value (Unix seconds) meaning "every generation": the timestamp of the +/// largest `chrono::NaiveDateTime` (+262143-12-31T23:59:59 UTC). Tombstones written for deleted +/// namespaces already hold this value in S3, and an older sqld reading a different one would +/// treat the database as not deleted, so it stays byte-for-byte what it was. +const TOMBSTONE_ALL: i64 = 8_210_266_876_799; + +/// Parses a UTC datetime given as `YYYY-MM-DDTHH:MM:SS` with optional fractional seconds. Anything +/// else is an error, notably a trailing `Z` or offset: a civil datetime has none, and silently +/// dropping `+05:00` would restore to the wrong point in time. +pub fn parse_utc_datetime(s: &str) -> std::result::Result { + DateTime::strptime("%Y-%m-%dT%H:%M:%S%.f", s) +} + +/// Parses a `YYYY-MM-DD` date. +pub fn parse_date(s: &str) -> std::result::Result { + jiff::civil::Date::strptime("%Y-%m-%d", s) +} + +/// Unix seconds of a civil datetime read as UTC. Beyond what [Timestamp] can hold, it saturates +/// instead of failing: callers only compare it with generation timestamps. +fn civil_to_unix_secs(datetime: &DateTime) -> i64 { + match TimeZone::UTC.to_timestamp(*datetime) { + Ok(timestamp) => timestamp.as_second(), + Err(_) if *datetime < DateTime::ZERO => Timestamp::MIN.as_second(), + Err(_) => Timestamp::MAX.as_second(), + } +} + +/// A stored tombstone as a [Timestamp]. Values past its range (see [TOMBSTONE_ALL]) clamp to the +/// ends: the result is only ever compared with generation timestamps, which are far inside it. +fn unix_secs_to_timestamp(secs: i64) -> Timestamp { + Timestamp::from_second(secs.clamp(Timestamp::MIN.as_second(), Timestamp::MAX.as_second())) + .expect("clamped to the Timestamp range") +} + pub type Result = anyhow::Result; #[derive(Debug)] @@ -1172,14 +1209,11 @@ impl Replicator { // it should be more robust and continue looking if the first item does not // match the -/ pattern. #[tracing::instrument(skip(self))] - pub async fn latest_generation_before( - &self, - timestamp: Option<&NaiveDateTime>, - ) -> Option { + pub async fn latest_generation_before(&self, timestamp: Option<&DateTime>) -> Option { tracing::debug!("last generation before"); let mut next_marker: Option = None; let prefix = format!("{}-", self.db_name); - let threshold = timestamp.map(|ts| ts.and_utc().timestamp() as u64); + let threshold = timestamp.map(|ts| civil_to_unix_secs(ts) as u64); loop { let mut request = self.list_objects().prefix(prefix.clone()); if threshold.is_none() { @@ -1221,14 +1255,10 @@ impl Replicator { Some(ts) => { let (unix_seconds, _) = ts.to_unix(); if tracing::enabled!(tracing::Level::DEBUG) { - let ts = Utc - .timestamp_millis_opt((unix_seconds * 1000) as i64) - .unwrap() - .to_rfc3339(); tracing::debug!( "Generation candidate: {} - timestamp: {}", generation, - ts + unix_secs_to_timestamp(unix_seconds as i64) ); } if &unix_seconds <= threshold { @@ -1304,7 +1334,7 @@ impl Replicator { async fn restore_from( &mut self, generation: Uuid, - timestamp: Option, + timestamp: Option, ) -> Result<(RestoreAction, bool)> { tracing::debug!("restoring from"); if let Some(tombstoned_at) = self.is_tombstoned(generation).await? { @@ -1359,7 +1389,7 @@ impl Replicator { &mut self, restore_path: &Path, generation: Uuid, - timestamp: Option, + timestamp: Option, last_frame: u32, ) -> Result<(RestoreAction, bool)> { tracing::debug!("Restoring database to `{}`", restore_path.display()); @@ -1569,7 +1599,7 @@ impl Replicator { page_size: usize, last_consistent_frame: Option, mut checksum: (u32, u32), - utc_time: Option, + utc_time: Option, db_path: &Path, ) -> Result { let encryption_config = self.encryption_config.clone(); @@ -1639,9 +1669,9 @@ impl Replicator { } } if let Some(threshold) = utc_time.as_ref() { - match DateTime::from_timestamp(timestamp as i64, 0).map(|t| t.naive_utc()) { - Some(timestamp) => { - if ×tamp > threshold { + match Timestamp::from_second(timestamp as i64) { + Ok(timestamp) => { + if timestamp.as_second() > civil_to_unix_secs(threshold) { tracing::info!("Frame batch {} has timestamp more recent than expected {}. Stopping recovery.", key, timestamp); break 'restore_wal; // reached end of restoration timestamp } @@ -1787,7 +1817,7 @@ impl Replicator { async fn choose_generation( &mut self, generation: Option, - timestamp: Option, + timestamp: Option, ) -> Option { match generation { Some(gen) => Some(gen), @@ -1803,7 +1833,7 @@ impl Replicator { pub async fn restore( &mut self, generation: Option, - timestamp: Option, + timestamp: Option, ) -> Result<(RestoreAction, bool)> { tracing::debug!("restoring with {generation:?} at {timestamp:?}"); let generation = match self.choose_generation(generation, timestamp).await { @@ -1959,20 +1989,20 @@ impl Replicator { } /// Marks current replicator database as deleted, invalidating all generations. - pub async fn delete_all(&self, older_than: Option) -> Result { + pub async fn delete_all(&self, older_than: Option) -> Result { tracing::info!( "Called for tombstoning of all contents of the '{}' database", self.db_name ); let key = format!("{}.tombstone", self.db_name); - let threshold = older_than.unwrap_or(NaiveDateTime::MAX); + let threshold = older_than + .map(|older_than| civil_to_unix_secs(&older_than)) + .unwrap_or(TOMBSTONE_ALL); self.client .put_object() .bucket(&self.bucket) .key(key) - .body(ByteStream::from( - threshold.and_utc().timestamp().to_be_bytes().to_vec(), - )) + .body(ByteStream::from(threshold.to_be_bytes().to_vec())) .send() .await?; let delete_task = DeleteAll::new( @@ -1984,10 +2014,10 @@ impl Replicator { Ok(delete_task) } - pub async fn is_tombstoned(&self, generation: Uuid) -> Result> { + pub async fn is_tombstoned(&self, generation: Uuid) -> Result> { if let Some(tombstone) = self.get_tombstone().await? { if let Some(timestamp) = Self::generation_to_timestamp(&generation) { - if (tombstone.and_utc().timestamp() as u64) >= timestamp.to_unix().0 { + if (tombstone.as_second() as u64) >= timestamp.to_unix().0 { return Ok(Some(tombstone)); }; } @@ -1996,7 +2026,7 @@ impl Replicator { } /// Checks if current replicator database has been marked as deleted. - pub async fn get_tombstone(&self) -> Result> { + pub async fn get_tombstone(&self) -> Result> { let key = format!("{}.tombstone", self.db_name); let resp = self .client @@ -2009,9 +2039,7 @@ impl Replicator { Ok(out) => { let mut buf = [0u8; 8]; out.body.collect().await?.copy_to_slice(&mut buf); - let timestamp = i64::from_be_bytes(buf); - let tombstone = DateTime::from_timestamp(timestamp, 0).map(|t| t.naive_utc()); - Ok(tombstone) + Ok(Some(unix_secs_to_timestamp(i64::from_be_bytes(buf)))) } Err(SdkError::ServiceError(se)) => match se.into_err() { GetObjectError::NoSuchKey(_) => Ok(None), @@ -2030,11 +2058,12 @@ pub struct DeleteAll { client: Client, bucket: String, db_name: String, - threshold: NaiveDateTime, + /// Unix seconds: generations created before this are removed. + threshold: i64, } impl DeleteAll { - fn new(client: Client, bucket: String, db_name: String, threshold: NaiveDateTime) -> Self { + fn new(client: Client, bucket: String, db_name: String, threshold: i64) -> Self { DeleteAll { client, bucket, @@ -2043,8 +2072,8 @@ impl DeleteAll { } } - pub fn threshold(&self) -> &NaiveDateTime { - &self.threshold + pub fn threshold(&self) -> Timestamp { + unix_secs_to_timestamp(self.threshold) } /// Performs hard deletion of all bottomless generations older than timestamp provided in @@ -2077,7 +2106,7 @@ impl DeleteAll { let prefix = &prefix[self.db_name.len() + 1..prefix.len() - 1]; let uuid = Uuid::try_parse(prefix)?; if let Some(datetime) = Replicator::generation_to_timestamp(&uuid) { - if datetime.to_unix().0 >= self.threshold.and_utc().timestamp() as u64 { + if datetime.to_unix().0 >= self.threshold as u64 { continue; } tracing::debug!("Removing generation {}", uuid); @@ -2184,3 +2213,79 @@ impl std::fmt::Display for CompressionKind { } } } + +#[cfg(test)] +mod time_tests { + use super::*; + + #[test] + fn tombstone_all_is_what_chrono_wrote() { + // `chrono::NaiveDateTime::MAX.and_utc().timestamp()`: already stored in S3 for every + // namespace deleted so far, so it must not change. + assert_eq!(TOMBSTONE_ALL, 8_210_266_876_799); + } + + #[test] + fn stored_tombstone_all_still_covers_every_generation() { + // Out of `Timestamp` range, so it clamps, and still sorts after any generation (UUID v7 + // timestamps are 48-bit milliseconds, year 10889 at the very most; real ones are far + // below 9999). + let tombstone = unix_secs_to_timestamp(TOMBSTONE_ALL); + assert_eq!(tombstone.as_second(), Timestamp::MAX.as_second()); + let generation = Uuid::parse_str("019a0000-0000-7000-8000-000000000000").unwrap(); + let secs = Replicator::generation_to_timestamp(&generation) + .unwrap() + .to_unix() + .0; + assert!(tombstone.as_second() as u64 >= secs); + } + + #[test] + fn tombstone_round_trips_inside_the_range() { + let ts = unix_secs_to_timestamp(1_700_000_000); + assert_eq!(ts.as_second(), 1_700_000_000); + assert_eq!( + unix_secs_to_timestamp(i64::MIN).as_second(), + Timestamp::MIN.as_second() + ); + assert_eq!( + unix_secs_to_timestamp(i64::MAX).as_second(), + Timestamp::MAX.as_second() + ); + } + + #[test] + fn civil_datetime_is_read_as_utc() { + let dt = parse_utc_datetime("2026-11-30T12:34:56").unwrap(); + assert_eq!(civil_to_unix_secs(&dt), 1_796_042_096); + assert_eq!( + civil_to_unix_secs(&DateTime::MAX), + Timestamp::MAX.as_second() + ); + assert_eq!( + civil_to_unix_secs(&DateTime::MIN), + Timestamp::MIN.as_second() + ); + } + + #[test] + fn parses_only_plain_utc_datetimes() { + assert!(parse_utc_datetime("2026-11-30T12:34:56").is_ok()); + assert!(parse_utc_datetime("2026-11-30T12:34:56.5").is_ok()); + for bad in [ + "2026-11-30T12:34:56Z", + "2026-11-30T12:34:56+05:00", + "2026-11-30T12:34:56[UTC]", + "2026-11-30 12:34:56", + "2026-11-30T12:34", + "2026-11-30", + "", + ] { + assert!(parse_utc_datetime(bad).is_err(), "{bad:?}"); + } + assert_eq!(parse_date("2026-11-30").unwrap().to_string(), "2026-11-30"); + for bad in ["2026-11-30T00:00:00", "20261130", "2026-13-01", ""] { + assert!(parse_date(bad).is_err(), "{bad:?}"); + } + } +} diff --git a/libsql-server/Cargo.toml b/libsql-server/Cargo.toml index 06107d0557..ebc7032fb5 100644 --- a/libsql-server/Cargo.toml +++ b/libsql-server/Cargo.toml @@ -22,7 +22,6 @@ bincode = "1.3.3" bottomless = { version = "0", path = "../bottomless", features = ["libsql_linked_statically"] } bytes = { version = "1.2.1", features = ["serde"] } bytesize = { version = "1.2.0", features = ["serde"] } -chrono = { version = "0.4.26", features = ["serde"] } clap = { version = "4.0.23", features = [ "derive", "env", "string" ] } console-subscriber = { git = "https://github.com/tokio-rs/console.git", rev = "5a80b98", optional = true } crc = "3.0.0" @@ -35,6 +34,7 @@ hyper = { workspace = true, features = ["http2"] } hyper-rustls = { git = "https://github.com/rustls/hyper-rustls.git", rev = "163b3f5", features = ["http2"] } hyper-tungstenite = "0.11" itertools = "0.10.5" +jiff = "1" jsonwebtoken = "9" libsql = { path = "../libsql/", optional = true } libsql_replication = { path = "../libsql-replication" } diff --git a/libsql-server/src/auth/user_auth_strategies/jwt.rs b/libsql-server/src/auth/user_auth_strategies/jwt.rs index 9c6893d1d7..2fafbd1718 100644 --- a/libsql-server/src/auth/user_auth_strategies/jwt.rs +++ b/libsql-server/src/auth/user_auth_strategies/jwt.rs @@ -1,7 +1,5 @@ use std::fmt::{self, Debug, Formatter}; -use chrono::{DateTime, Utc}; - use crate::{ auth::{ authenticated::LegacyAuth, @@ -61,34 +59,10 @@ pub struct Token { a: Option, #[serde(default)] pub(crate) p: Option, - #[serde(with = "jwt_time", default)] - exp: Option>, -} - -mod jwt_time { - use chrono::{DateTime, Utc}; - use serde::{de::Error, Deserialize, Deserializer, Serializer}; - - pub fn serialize(date: &Option>, serializer: S) -> Result - where - S: Serializer, - { - match date { - Some(date) => serializer.serialize_i64(date.timestamp()), - None => serializer.serialize_none(), - } - } - - pub fn deserialize<'de, D>(deserializer: D) -> Result>, D::Error> - where - D: Deserializer<'de>, - { - Option::::deserialize(deserializer)? - .map(|x| { - DateTime::from_timestamp(x, 0).ok_or_else(|| D::Error::custom("invalid exp claim")) - }) - .transpose() - } + // Seconds since the Unix epoch, as in the token. Not a date type: tokens that never expire + // carry values far past year 9999, which date types reject and jsonwebtoken accepts. + #[serde(default)] + exp: Option, } fn validate_any_jwt( @@ -141,7 +115,7 @@ fn validate_jwt( #[cfg(test)] mod tests { - use std::time::Duration; + use jiff::Timestamp; use jsonwebtoken::{DecodingKey, EncodingKey}; use ring::signature::{Ed25519KeyPair, KeyPair}; @@ -251,7 +225,7 @@ mod tests { id: None, a: None, p: None, - exp: Some(Utc::now() - Duration::from_secs(5 * 60)), + exp: Some(Timestamp::now().as_second() - 5 * 60), }; let token = encode(&token, &enc); @@ -359,7 +333,7 @@ mod tests { id: None, a: None, p: None, - exp: Some(Utc::now() - Duration::from_secs(5 * 60)), + exp: Some(Timestamp::now().as_second() - 5 * 60), }; let token = encode(&token, &multi_enc[0]); @@ -380,7 +354,7 @@ mod tests { id: None, a: None, p: None, - exp: Some(Utc::now() - Duration::from_secs(5 * 60)), + exp: Some(Timestamp::now().as_second() - 5 * 60), }; let token = encode(&token, &multi_enc[2]); diff --git a/libsql-server/src/http/admin/mod.rs b/libsql-server/src/http/admin/mod.rs index 6953696312..1442a5d0cb 100644 --- a/libsql-server/src/http/admin/mod.rs +++ b/libsql-server/src/http/admin/mod.rs @@ -4,9 +4,9 @@ use axum::extract::{FromRef, Path, State}; use axum::middleware::Next; use axum::routing::delete; use axum::Json; -use chrono::NaiveDateTime; use futures::{SinkExt, StreamExt, TryStreamExt}; use hyper::{Body, Request, StatusCode}; +use jiff::civil::DateTime; use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle}; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; @@ -443,7 +443,16 @@ async fn handle_create_namespace( #[derive(Debug, Deserialize)] struct ForkNamespaceReq { - timestamp: NaiveDateTime, + #[serde(deserialize_with = "deserialize_utc_datetime")] + timestamp: DateTime, +} + +fn deserialize_utc_datetime<'de, D>(deserializer: D) -> Result +where + D: serde::Deserializer<'de>, +{ + let s = String::deserialize(deserializer)?; + bottomless::replicator::parse_utc_datetime(&s).map_err(serde::de::Error::custom) } async fn handle_fork_namespace( @@ -609,3 +618,35 @@ async fn delete_profile_heap(Path(profile): Path) -> crate::Result<()> { tokio::fs::remove_dir_all(&profile_dir).await?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(timestamp: &str) -> Result { + serde_json::from_value(serde_json::json!({ "timestamp": timestamp })) + } + + #[test] + fn fork_timestamp_is_a_utc_datetime() { + let req = parse("2026-11-30T12:34:56").unwrap(); + assert_eq!(req.timestamp.to_string(), "2026-11-30T12:34:56"); + let req = parse("2026-11-30T12:34:56.789").unwrap(); + assert_eq!(req.timestamp.to_string(), "2026-11-30T12:34:56.789"); + } + + #[test] + fn fork_timestamp_rejects_an_offset() { + // A civil datetime has none: dropping `+05:00` would restore to the wrong moment. + for bad in [ + "2026-11-30T12:34:56Z", + "2026-11-30T12:34:56+05:00", + "2026-11-30 12:34:56", + "2026-11-30", + "yesterday", + "", + ] { + assert!(parse(bad).is_err(), "{bad:?} must be rejected"); + } + } +} diff --git a/libsql-server/src/http/admin/stats.rs b/libsql-server/src/http/admin/stats.rs index f2948d4d7b..41967ee272 100644 --- a/libsql-server/src/http/admin/stats.rs +++ b/libsql-server/src/http/admin/stats.rs @@ -111,7 +111,7 @@ impl From<&Stats> for Option { let queries = queries.as_ref().unwrap(); Some(QueriesStatsResponse { id: queries.id(), - created_at: queries.created_at().timestamp() as u64, + created_at: queries.created_at().as_second() as u64, count: queries.count(), elapsed: QueriesLatencyStats::from(queries.hist(), &queries.elapsed()), stats: queries diff --git a/libsql-server/src/namespace/configurator/fork.rs b/libsql-server/src/namespace/configurator/fork.rs index 80de9ab19c..7a69012465 100644 --- a/libsql-server/src/namespace/configurator/fork.rs +++ b/libsql-server/src/namespace/configurator/fork.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use anyhow::anyhow; use bottomless::replicator::Replicator; -use chrono::NaiveDateTime; use futures::TryStreamExt; +use jiff::civil::DateTime; use libsql_replication::frame::FrameBorrowed; use tokio::fs::File; use tokio::io::{AsyncSeekExt, AsyncWriteExt}; @@ -29,7 +29,7 @@ pub(super) async fn fork( from_config: MetaStoreHandle, to_ns: NamespaceName, to_config: MetaStoreHandle, - timestamp: Option, + timestamp: Option, store: NamespaceStore, primary_config: &PrimaryConfig, base_path: Arc, @@ -120,7 +120,7 @@ pub struct ForkTask { } pub struct PointInTimeRestore { - pub timestamp: NaiveDateTime, + pub timestamp: DateTime, pub replicator_options: bottomless::replicator::Options, } diff --git a/libsql-server/src/namespace/configurator/mod.rs b/libsql-server/src/namespace/configurator/mod.rs index 517b21ca5a..c486e28349 100644 --- a/libsql-server/src/namespace/configurator/mod.rs +++ b/libsql-server/src/namespace/configurator/mod.rs @@ -3,8 +3,8 @@ use std::pin::Pin; use std::sync::Arc; use std::time::Duration; -use chrono::NaiveDateTime; use futures::Future; +use jiff::civil::DateTime; use libsql_sys::EncryptionConfig; use tokio::sync::Semaphore; @@ -135,7 +135,7 @@ pub trait ConfigureNamespace { from_config: MetaStoreHandle, to_ns: NamespaceName, to_config: MetaStoreHandle, - timestamp: Option, + timestamp: Option, store: NamespaceStore, ) -> Pin> + Send + 'a>>; } diff --git a/libsql-server/src/namespace/configurator/primary.rs b/libsql-server/src/namespace/configurator/primary.rs index f68405fad6..7a4b74627b 100644 --- a/libsql-server/src/namespace/configurator/primary.rs +++ b/libsql-server/src/namespace/configurator/primary.rs @@ -184,7 +184,7 @@ impl ConfigureNamespace for PrimaryConfigurator { from_config: MetaStoreHandle, to_ns: NamespaceName, to_config: MetaStoreHandle, - timestamp: Option, + timestamp: Option, store: NamespaceStore, ) -> Pin> + Send + 'a>> { Box::pin(super::fork::fork( diff --git a/libsql-server/src/namespace/configurator/replica.rs b/libsql-server/src/namespace/configurator/replica.rs index b1a108af73..9ad040cb37 100644 --- a/libsql-server/src/namespace/configurator/replica.rs +++ b/libsql-server/src/namespace/configurator/replica.rs @@ -301,7 +301,7 @@ impl ConfigureNamespace for ReplicaConfigurator { _from_config: MetaStoreHandle, _to_ns: NamespaceName, _to_config: MetaStoreHandle, - _timestamp: Option, + _timestamp: Option, _store: NamespaceStore, ) -> Pin> + Send + 'a>> { Box::pin(std::future::ready(Err(crate::Error::Fork( diff --git a/libsql-server/src/namespace/configurator/schema.rs b/libsql-server/src/namespace/configurator/schema.rs index 275fd71e93..52b829c294 100644 --- a/libsql-server/src/namespace/configurator/schema.rs +++ b/libsql-server/src/namespace/configurator/schema.rs @@ -120,7 +120,7 @@ impl ConfigureNamespace for SchemaConfigurator { from_config: MetaStoreHandle, to_ns: NamespaceName, to_config: MetaStoreHandle, - timestamp: Option, + timestamp: Option, store: NamespaceStore, ) -> std::pin::Pin> + Send + 'a>> { Box::pin(super::fork::fork( diff --git a/libsql-server/src/namespace/mod.rs b/libsql-server/src/namespace/mod.rs index ec45b50445..e673a495b5 100644 --- a/libsql-server/src/namespace/mod.rs +++ b/libsql-server/src/namespace/mod.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use anyhow::Context as _; use bytes::Bytes; -use chrono::NaiveDateTime; use futures_core::{Future, Stream}; +use jiff::civil::DateTime; use tokio::task::JoinSet; use uuid::Uuid; @@ -139,5 +139,5 @@ pub enum RestoreOption { Generation(Uuid), /// Restore database state to a backup version present at a specific point in time. /// Granularity depends of how frequently WAL log pages are being snapshotted. - PointInTime(NaiveDateTime), + PointInTime(DateTime), } diff --git a/libsql-server/src/namespace/store.rs b/libsql-server/src/namespace/store.rs index 86e9438ccd..89fafd007b 100644 --- a/libsql-server/src/namespace/store.rs +++ b/libsql-server/src/namespace/store.rs @@ -2,8 +2,8 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use async_lock::RwLock; -use chrono::NaiveDateTime; use futures::TryFutureExt; +use jiff::civil::DateTime; use moka::future::Cache; use once_cell::sync::OnceCell; use tokio::task::JoinSet; @@ -214,7 +214,7 @@ impl NamespaceStore { from: NamespaceName, to: NamespaceName, to_config: DatabaseConfig, - timestamp: Option, + timestamp: Option, ) -> crate::Result<()> { if self.inner.has_shutdown.load(Ordering::Relaxed) { return Err(Error::NamespaceStoreShutdown); diff --git a/libsql-server/src/replication/primary/frame_stream.rs b/libsql-server/src/replication/primary/frame_stream.rs index 614a4585ca..ec487eea8e 100644 --- a/libsql-server/src/replication/primary/frame_stream.rs +++ b/libsql-server/src/replication/primary/frame_stream.rs @@ -2,9 +2,9 @@ use std::sync::Arc; use std::task::{ready, Poll}; use std::{pin::Pin, task::Context}; -use chrono::{DateTime, Utc}; use futures::future::BoxFuture; use futures::{FutureExt, Stream}; +use jiff::Timestamp; use libsql_replication::frame::{Frame, FrameNo}; use crate::replication::{LogReadError, ReplicationLogger}; @@ -102,7 +102,7 @@ enum FrameStreamState { } impl Stream for FrameStream { - type Item = Result<(Frame, Option>), LogReadError>; + type Item = Result<(Frame, Option), LogReadError>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.logger_closed_fut.poll_unpin(cx).is_ready() { diff --git a/libsql-server/src/replication/primary/logger.rs b/libsql-server/src/replication/primary/logger.rs index 8eb268e4ed..977f072fa7 100644 --- a/libsql-server/src/replication/primary/logger.rs +++ b/libsql-server/src/replication/primary/logger.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use anyhow::{bail, ensure}; use bytes::{Bytes, BytesMut}; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use libsql_replication::frame::{Frame, FrameBorrowed, FrameHeader, FrameMut}; use libsql_replication::snapshot::SnapshotFile; use libsql_sys::EncryptionConfig; @@ -547,7 +547,7 @@ impl Generation { pub struct ReplicationLogger { pub generation: Generation, pub log_file: RwLock, - pub commit_timestamp_cache: moka::sync::Cache>, + pub commit_timestamp_cache: moka::sync::Cache, compactor: LogCompactor, db_path: PathBuf, /// a notifier channel other tasks can subscribe to, and get notified when new frames become @@ -776,7 +776,8 @@ impl ReplicationLogger { let mut log_file = self.log_file.write(); log_file.commit()?; if let Some(frame_no) = log_file.header().last_frame_no() { - self.commit_timestamp_cache.insert(frame_no, Utc::now()); + self.commit_timestamp_cache + .insert(frame_no, Timestamp::now()); } Ok(log_file.header().last_frame_no()) } diff --git a/libsql-server/src/replication/replicator_client.rs b/libsql-server/src/replication/replicator_client.rs index fb8154824d..df6b6b95f6 100644 --- a/libsql-server/src/replication/replicator_client.rs +++ b/libsql-server/src/replication/replicator_client.rs @@ -2,8 +2,8 @@ use std::path::Path; use std::pin::Pin; use bytes::Bytes; -use chrono::{DateTime, Utc}; use futures::TryStreamExt; +use jiff::Timestamp; use libsql_replication::meta::WalIndexMeta; use libsql_replication::replicator::{Error, ReplicatorClient}; use libsql_replication::rpc::replication::log_offset::WalFlavor; @@ -215,9 +215,9 @@ impl ReplicatorClient for Client { .inspect_ok(|f| { match f.timestamp { Some(ts_millis) => { - if let Some(commited_at) = DateTime::from_timestamp_millis(ts_millis) { - let lat = Utc::now() - commited_at; - match lat.to_std() { + if let Ok(commited_at) = Timestamp::from_millisecond(ts_millis) { + let lat = Timestamp::now().duration_since(commited_at); + match std::time::Duration::try_from(lat) { Ok(lat) => { // we can record negative values if the clocks are out-of-sync. There is not // point in recording those values. diff --git a/libsql-server/src/rpc/replication/replication_log.rs b/libsql-server/src/rpc/replication/replication_log.rs index 1f7585f34f..7ddef345c0 100644 --- a/libsql-server/src/rpc/replication/replication_log.rs +++ b/libsql-server/src/rpc/replication/replication_log.rs @@ -4,9 +4,9 @@ use std::pin::Pin; use std::sync::{Arc, RwLock}; use bytes::Bytes; -use chrono::{DateTime, Utc}; use futures::stream::BoxStream; use futures_core::Future; +use jiff::Timestamp; pub use libsql_replication::rpc::replication as rpc; use libsql_replication::rpc::replication::log_offset::WalFlavor; use libsql_replication::rpc::replication::replication_log_server::ReplicationLog; @@ -181,12 +181,12 @@ impl ReplicationLogService { } fn map_frame_stream_output( - r: Result<(libsql_replication::frame::Frame, Option>), LogReadError>, + r: Result<(libsql_replication::frame::Frame, Option), LogReadError>, ) -> Result { match r { Ok((frame, ts)) => Ok(Frame { data: frame.bytes(), - timestamp: ts.map(|ts| ts.timestamp_millis()), + timestamp: ts.map(|ts| ts.as_millisecond()), durable_frame_no: None, }), Err(LogReadError::SnapshotRequired) => Err(Status::new( diff --git a/libsql-server/src/stats.rs b/libsql-server/src/stats.rs index e91c2505c9..67567c26dc 100644 --- a/libsql-server/src/stats.rs +++ b/libsql-server/src/stats.rs @@ -2,8 +2,8 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, RwLock, Weak}; -use chrono::{DateTime, DurationRound, Utc}; use hdrhistogram::Histogram; +use jiff::{RoundMode, SignedDuration, Timestamp, TimestampRound, Unit}; use metrics::{counter, gauge, histogram, increment_counter}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeSet, HashMap}; @@ -92,7 +92,7 @@ pub struct QueriesStats { stats_threshold: u64, hist: Histogram, expires_at: Option, - created_at: DateTime, + created_at: Timestamp, } impl QueriesStats { @@ -104,7 +104,7 @@ impl QueriesStats { stats_threshold: 0, hist: Histogram::::new(3).unwrap(), expires_at: None, - created_at: Utc::now(), + created_at: Timestamp::now(), } } @@ -183,7 +183,7 @@ impl QueriesStats { self.hist.len() as u64 } - pub(crate) fn created_at(&self) -> &DateTime { + pub(crate) fn created_at(&self) -> &Timestamp { &self.created_at } } @@ -534,9 +534,13 @@ async fn try_persist_stats(stats: Weak, path: &Path) -> anyhow::Result<() } fn next_hour() -> Instant { - let utc_now = Utc::now(); - let next_hour = (utc_now + chrono::Duration::hours(1)) - .duration_trunc(chrono::Duration::hours(1)) + let utc_now = Timestamp::now(); + let next_hour = (utc_now + SignedDuration::from_hours(1)) + .round( + TimestampRound::new() + .smallest(Unit::Hour) + .mode(RoundMode::Trunc), + ) .unwrap(); - Instant::now() + (next_hour - utc_now).to_std().unwrap() + Instant::now() + Duration::try_from(next_hour.duration_since(utc_now)).unwrap() }