Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/daemon/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,9 @@ libc.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true

[features]
# Time runs fast and the ledger lives apart; see src/clock.rs. Never ship it.
speedrun = []

[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
64 changes: 64 additions & 0 deletions crates/daemon/src/clock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
//! The daemon's wall clock and focus time. In a normal build both are real.
//!
//! The `speedrun` feature runs them `SPEED` times faster, to play through the
//! progression in an afternoon: a focused hour passes in seconds, a day in
//! minutes. Wall time runs from an anchor kept in the state directory, so it
//! never goes backwards across restarts. Never ship this build.

use std::path::Path;
use std::sync::OnceLock;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use jiff::Timestamp;

/// How many times faster than real time the daemon's clock runs.
pub const SPEED: u32 = if cfg!(feature = "speedrun") { 360 } else { 1 };

static ANCHOR: OnceLock<i64> = OnceLock::new();

fn real_now() -> Duration {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
}

/// Fixes where sped-up time starts: read from `state_dir`, or now on first run.
pub fn init(state_dir: &Path) {
if SPEED == 1 {
return;
}
let path = state_dir.join("speedrun-anchor");
let anchor = std::fs::read_to_string(&path)
.ok()
.and_then(|s| s.trim().parse().ok())
.unwrap_or_else(|| {
let now = real_now().as_secs() as i64;
if let Err(e) = std::fs::write(&path, now.to_string()) {
tracing::error!("could not save {}: {e}", path.display());
}
now
});
let _ = ANCHOR.set(anchor);
tracing::warn!("SPEEDRUN build: time runs {SPEED}x from {anchor}");
}

/// Now, as the daemon sees it.
pub fn timestamp() -> Timestamp {
let real = real_now();
let Some(&anchor) = ANCHOR.get().filter(|_| SPEED > 1) else {
return Timestamp::try_from(SystemTime::now()).unwrap_or(Timestamp::UNIX_EPOCH);
};
let since = real.saturating_sub(Duration::from_secs(anchor.max(0) as u64));
let virt = Duration::from_secs(anchor as u64) + since * SPEED;
Timestamp::from_second(virt.as_secs() as i64).unwrap_or(Timestamp::UNIX_EPOCH)
}

/// Unix seconds, as the daemon sees them.
pub fn unix_now() -> i64 {
timestamp().as_second()
}

/// A real interval in the daemon's time.
pub fn scale(real: Duration) -> Duration {
real * SPEED
}
26 changes: 13 additions & 13 deletions crates/daemon/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use std::time::{Duration, Instant};

use anyhow::Result;
use deepwork_proto::{
Expand All @@ -17,6 +17,7 @@ use tracing::{error, info, warn};

use crate::backup::{self, Backup, BackupSession};
use crate::cfgstate::{self, Outcome, Pending};
use crate::clock;
use crate::config::{Config, Profile};
use crate::dns::Resolver;
use crate::enforcer::{EnforcerHandle, Mode};
Expand Down Expand Up @@ -94,9 +95,7 @@ fn boottime() -> Duration {
}

fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64)
clock::unix_now()
}

impl Core {
Expand All @@ -113,7 +112,7 @@ impl Core {
warn!("could not read the local time zone, using UTC for routines: {e}");
TimeZone::UTC
});
let since = Timestamp::now()
let since = clock::timestamp()
.to_zoned(tz.clone())
.date()
.checked_sub(3.days())
Expand Down Expand Up @@ -148,7 +147,7 @@ impl Core {
runs,
routine_retry_at: None,
last,
last_wall: Timestamp::now(),
last_wall: clock::timestamp(),
last_boot: boottime(),
tunnels: tunnel::Reporter::default(),
bank,
Expand Down Expand Up @@ -448,7 +447,7 @@ impl Core {
}

fn now(&self) -> Zoned {
Timestamp::now().to_zoned(self.tz.clone())
clock::timestamp().to_zoned(self.tz.clone())
}

fn occurrences(&self, now: &Zoned) -> Vec<Occurrence> {
Expand Down Expand Up @@ -651,7 +650,7 @@ impl Core {
});
Ok(self
.city()?
.world(running.as_ref(), Timestamp::now(), &self.tz))
.world(running.as_ref(), clock::timestamp(), &self.tz))
}

/// The shop and the plan stay shut while a session runs: the session is
Expand Down Expand Up @@ -906,7 +905,7 @@ impl Core {
.import_backup(&b)
.map_err(|e| format!("could not import the progress: {e:#}"))?;
// Refresh what the daemon mirrors in memory.
let since = Timestamp::now()
let since = clock::timestamp()
.to_zoned(self.tz.clone())
.date()
.checked_sub(3.days())
Expand Down Expand Up @@ -1086,11 +1085,12 @@ impl Core {

/// Logs a wall-clock change, which could move a routine out of the way.
fn check_clock(&mut self) {
let wall = Timestamp::now();
let wall = clock::timestamp();
let boot = boottime();
let wall_delta = wall.duration_since(self.last_wall);
let boot_delta = SignedDuration::try_from(boot.saturating_sub(self.last_boot))
.unwrap_or(SignedDuration::ZERO);
let boot_delta =
SignedDuration::try_from(clock::scale(boot.saturating_sub(self.last_boot)))
.unwrap_or(SignedDuration::ZERO);
self.last_wall = wall;
self.last_boot = boot;
let drift = wall_delta - boot_delta;
Expand Down Expand Up @@ -1211,7 +1211,7 @@ impl Core {

pub async fn tick(&mut self) {
let now = Instant::now();
let delta = now - self.last_tick;
let delta = clock::scale(now - self.last_tick);
self.last_tick = now;
self.check_clock();
self.check_pending_config();
Expand Down
13 changes: 9 additions & 4 deletions crates/daemon/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod backup;
mod cfgstate;
mod clock;
mod config;
mod dns;
mod dot;
Expand Down Expand Up @@ -99,7 +100,12 @@ fn notify_ready() {
fn default_paths(dry_run: bool) -> (PathBuf, PathBuf) {
if !dry_run {
return (
PathBuf::from("/var/lib/deepwork"),
// A speedrun's ledger must never mix with the real one.
PathBuf::from(if cfg!(feature = "speedrun") {
"/var/lib/deepwork-speedrun"
} else {
"/var/lib/deepwork"
}),
PathBuf::from(deepwork_proto::DEFAULT_SOCKET),
);
}
Expand Down Expand Up @@ -170,9 +176,8 @@ async fn main() -> Result<()> {
std::fs::create_dir_all(&state_dir)
.with_context(|| format!("creating {}", state_dir.display()))?;
let store = Store::open(&state_dir.join("deepwork.db"))?;
let unix_now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64);
clock::init(&state_dir);
let unix_now = clock::unix_now();
let (cfg_state, outcome) = cfgstate::sync(&store, &args.config, unix_now)?;
let cfg = cfg_state.config.clone();

Expand Down
8 changes: 8 additions & 0 deletions docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,14 @@ systemctl --user enable --now deepwork-agent.service
**Never install or apply nft/tc/resolved changes on the host without the
user's go-ahead.**

### Speedrun build

To play through the progression fast: `cargo build --release -p deepworkd
--features speedrun`. The daemon's clock runs `SPEED` (`clock.rs`) times
faster, so a focused hour passes in seconds and a day in minutes, and it
keeps its own ledger in `/var/lib/deepwork-speedrun`. Enforcement is real.
Swap only `/usr/local/bin/deepworkd` and restart the service; never ship it.

## Releases

- CI (`ci.yml`): fmt, clippy `-D warnings`, `cargo test` on Rust changes;
Expand Down
Loading