Skip to content

Commit

Permalink
chore: don't use Utc::now() (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucacasonato authored Oct 31, 2023
1 parent be0dc25 commit 4ba28b8
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 68 deletions.
56 changes: 2 additions & 54 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ denokv_proto = { version = "0.2.0", path = "./proto" }
anyhow = "1"
async-trait = "0.1"
bytes = "1"
chrono = { version = "0.4", features = ["serde"] }
chrono = { version = "0.4", default-features = false, features = ["std", "serde"] }
futures = "0.3.28"
log = "0.4.20"
num-bigint = "0.4"
Expand Down
2 changes: 2 additions & 0 deletions proto/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2023 the Deno authors. All rights reserved. MIT license.

mod codec;
mod interface;
mod protobuf;
Expand Down
2 changes: 1 addition & 1 deletion remote/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "denokv_remote"
description = "Remote (KV Connect) backend for Deno KV"
version = "0.2.2"
version = "0.2.3"
edition.workspace = true
license.workspace = true
repository.workspace = true
Expand Down
11 changes: 8 additions & 3 deletions remote/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
// Copyright 2023 the Deno authors. All rights reserved. MIT license.

mod time;

use std::ops::Sub;
use std::sync::Arc;
use std::time::Duration;
Expand Down Expand Up @@ -25,6 +29,7 @@ use log::warn;
use rand::Rng;
use reqwest::StatusCode;
use serde::Deserialize;
use time::utc_now;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use url::Url;
Expand Down Expand Up @@ -231,15 +236,15 @@ async fn metadata_refresh_task(
match res {
RetryableResult::Ok(metadata) => {
attempts = 0;
let expires_in = metadata.expires_at.signed_duration_since(Utc::now());
let expires_in = metadata.expires_at.signed_duration_since(utc_now());

if tx.send(MetadataState::Ok(Arc::new(metadata))).is_err() {
// The receiver has been dropped, so we can stop now.
return;
}

// Sleep until the token expires, minus a 10 minute buffer, but at minimum
// one minute.
// Sleep until the token expires, minus a 10 minute buffer, but at
// minimum one minute.
let sleep_time = expires_in
.sub(chrono::Duration::seconds(10))
.to_std()
Expand Down
19 changes: 19 additions & 0 deletions remote/time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright 2023 the Deno authors. All rights reserved. MIT license.

/// Identical to chrono::Utc::now() but without the system "clock"
/// feature flag.
///
/// The "clock" feature flag pulls in the "iana-time-zone" crate
/// which links to macOS's "CoreFoundation" framework which increases
/// startup time for the CLI.
pub fn utc_now() -> chrono::DateTime<chrono::Utc> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("system time before Unix epoch");
let naive = chrono::NaiveDateTime::from_timestamp_opt(
now.as_secs() as i64,
now.subsec_nanos(),
)
.unwrap();
chrono::DateTime::from_naive_utc_and_offset(naive, chrono::Utc)
}
2 changes: 1 addition & 1 deletion sqlite/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "denokv_sqlite"
description = "SQLite storage backend for Deno KV"
version = "0.2.0"
version = "0.2.1"
edition.workspace = true
license.workspace = true
repository.workspace = true
Expand Down
14 changes: 9 additions & 5 deletions sqlite/backend.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2023 the Deno authors. All rights reserved. MIT license.

use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
Expand All @@ -24,6 +26,8 @@ use rusqlite::OptionalExtension;
use rusqlite::Transaction;
use uuid::Uuid;

use crate::time::utc_now;

const STATEMENT_INC_AND_GET_DATA_VERSION: &str =
"update data_version set version = version + ? where k = 0 returning version";
const STATEMENT_KV_RANGE_SCAN: &str =
Expand Down Expand Up @@ -343,7 +347,7 @@ impl SqliteBackend {

pub fn queue_running_keepalive(&mut self) -> Result<(), anyhow::Error> {
let running_messages = self.messages_running.clone();
let now = Utc::now();
let now = utc_now();
self.run_tx(|tx, _| {
let mut update_deadline_stmt =
tx.prepare_cached(STATEMENT_QUEUE_UPDATE_RUNNING_DEADLINE)?;
Expand All @@ -360,7 +364,7 @@ impl SqliteBackend {
}

pub fn queue_cleanup(&mut self) -> Result<(), anyhow::Error> {
let now = Utc::now();
let now = utc_now();
let queue_dequeue_waker = self.dequeue_notify.clone();
loop {
let done = self.run_tx(|tx, rng| {
Expand Down Expand Up @@ -389,7 +393,7 @@ impl SqliteBackend {
&mut self,
) -> Result<(Option<DequeuedMessage>, Option<DateTime<Utc>>), anyhow::Error>
{
let now = Utc::now();
let now = utc_now();

let can_dispatch = self.messages_running.len() < DISPATCH_CONCURRENCY_LIMIT;

Expand Down Expand Up @@ -476,7 +480,7 @@ impl SqliteBackend {
id: &QueueMessageId,
success: bool,
) -> Result<(), anyhow::Error> {
let now = Utc::now();
let now = utc_now();
let requeued = self.run_tx(|tx, rng| {
let requeued = if success {
let changed = tx
Expand All @@ -498,7 +502,7 @@ impl SqliteBackend {
pub fn collect_expired(
&mut self,
) -> Result<Option<DateTime<Utc>>, anyhow::Error> {
let now = Utc::now();
let now = utc_now();
self.run_tx(|tx, _| {
tx.prepare_cached(STATEMENT_DELETE_ALL_EXPIRED)?
.execute(params![now.timestamp_millis()])?;
Expand Down
10 changes: 7 additions & 3 deletions sqlite/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// Copyright 2023 the Deno authors. All rights reserved. MIT license.

mod backend;
mod time;

use std::collections::VecDeque;
use std::ops::Add;
Expand All @@ -24,6 +27,7 @@ use denokv_proto::SnapshotReadOptions;
use futures::future::Either;
use rand::RngCore;
pub use rusqlite::Connection;
use time::utc_now;
use tokio::select;
use tokio::sync::oneshot;
use tokio::sync::Notify;
Expand Down Expand Up @@ -109,7 +113,7 @@ async fn sqlite_thread(
dequeue_notify: Arc<Notify>,
mut request_rx: tokio::sync::mpsc::Receiver<SqliteRequest>,
) {
let start = Utc::now();
let start = utc_now();
if let Err(err) = backend.queue_cleanup() {
panic!("KV queue cleanup failed: {err}");
}
Expand Down Expand Up @@ -138,7 +142,7 @@ async fn sqlite_thread(
EXPIRY_JITTER,
);
loop {
let now = Utc::now();
let now = utc_now();
let mut closest_deadline = queue_cleanup_deadline
.min(queue_keepalive_deadline)
.min(expiry_deadline);
Expand Down Expand Up @@ -245,7 +249,7 @@ fn compute_deadline_with_max_and_jitter(
max: Duration,
jitter_duration: Duration,
) -> DateTime<Utc> {
let fallback = Utc::now() + max;
let fallback = utc_now() + max;
next_ready.unwrap_or(fallback).min(fallback)
+ duration_with_total_jitter(jitter_duration)
}
Expand Down
19 changes: 19 additions & 0 deletions sqlite/time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright 2023 the Deno authors. All rights reserved. MIT license.

/// Identical to chrono::Utc::now() but without the system "clock"
/// feature flag.
///
/// The "clock" feature flag pulls in the "iana-time-zone" crate
/// which links to macOS's "CoreFoundation" framework which increases
/// startup time for the CLI.
pub fn utc_now() -> chrono::DateTime<chrono::Utc> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("system time before Unix epoch");
let naive = chrono::NaiveDateTime::from_timestamp_opt(
now.as_secs() as i64,
now.subsec_nanos(),
)
.unwrap();
chrono::DateTime::from_naive_utc_and_offset(naive, chrono::Utc)
}

0 comments on commit 4ba28b8

Please sign in to comment.