| 1 | //! leaser.rs — object-storage lease fencing: acquire / renew / release + the |
| 2 | //! expiry→failover protocol, built on a compare-and-swap (conditional write) |
| 3 | //! primitive over ordinary object storage. |
| 4 | //! |
| 5 | //! Ported from [email protected]: |
| 6 | //! - `leaser.go:1-44` — the `Leaser` interface, the `Lease` value type, and the `ErrLeaseNotHeld` / `LeaseExistsError` sentinels. |
| 7 | //! - `heartbeat.go:1-84` — the `HeartbeatClient` liveness-ping companion. |
| 8 | //! - `s3/leaser.go:1-306` — the concrete S3 implementation (`readLease`, `writeLease`, `AcquireLease`, `RenewLease`, `ReleaseLease`, `lockKey`). |
| 9 | //! |
| 10 | //! # Fencing model |
| 11 | //! |
| 12 | //! A node must hold a live lease before writing LTX data to the remote store. The |
| 13 | //! lease is a tiny JSON object (`lock.json`) under the replica prefix. All |
| 14 | //! acquire/renew/release operations are guarded by HTTP conditional writes — |
| 15 | //! `If-None-Match: *` for creation, `If-Match: <etag>` for renewal — which give |
| 16 | //! compare-and-swap semantics over plain object storage with no extra primitives. |
| 17 | //! If a node cannot acquire or renew, it stands by (read-only) until the current |
| 18 | //! lease expires and the key becomes writable again. |
| 19 | //! |
| 20 | //! # `object_store` mapping (see the porting brief T15.md §2/§3/§5) |
| 21 | //! |
| 22 | //! | Go (aws-sdk + smithy) | Rust (`object_store` 0.11) | |
| 23 | //! |------------------------------|--------------------------------------------------| |
| 24 | //! | `PutObject{IfNoneMatch:"*"}` | `PutMode::Create` → `Error::AlreadyExists` on loss | |
| 25 | //! | `PutObject{IfMatch:etag}` | `PutMode::Update(UpdateVersion{e_tag})` → `Error::Precondition` | |
| 26 | //! | `GetObject` | `get` → `GetResult { meta.e_tag, .. }` | |
| 27 | //! | `os.ErrNotExist` | `Error::NotFound` | |
| 28 | //! | `PreconditionFailed` (412) | `Error::Precondition` / `Error::AlreadyExists` | |
| 29 | //! |
| 30 | //! # DEVIATION from Go — conditional DELETE |
| 31 | //! |
| 32 | //! Go's `ReleaseLease` issues `DeleteObject` with `IfMatch:<etag>` (s3/leaser.go:180-184) |
| 33 | //! so the delete is atomic. `object_store 0.11`'s `delete(&path)` takes **no** |
| 34 | //! options and has no conditional-delete variant (lib.rs:660). We therefore |
| 35 | //! implement release as **read-then-delete**: read the current lock object (and |
| 36 | //! its ETag), compare it to the held lease's ETag, and only then delete. The three |
| 37 | //! Go outcomes are preserved exactly: |
| 38 | //! |
| 39 | //! - key absent → `LeaseAlreadyReleased` (Go's 404 path, s3/leaser.go:186-188). |
| 40 | //! - ETag mismatch → `LeaseNotHeld` (Go's 412 path, s3/leaser.go:189-191). |
| 41 | //! - ETag matches → unconditional delete; a NotFound during the delete is treated as success (the object is already gone). |
| 42 | //! |
| 43 | //! This opens a ~1-RTT TOCTOU window between the read and the delete, but it is |
| 44 | //! benign under the single-owner-handle model (brief §5.11): the lock object can |
| 45 | //! only move off our ETag if *we* renew it, and a node about to release is not |
| 46 | //! concurrently renewing the same handle. No other node can mutate the object from |
| 47 | //! our ETag because ETags are unique per write and only we hold ours. `// DECISION` |
| 48 | //! logged in OPEN_QUESTIONS.md. |
| 49 | |
| 50 | use std::sync::Mutex; |
| 51 | use std::time::{Duration, Instant, SystemTime}; |
| 52 | |
| 53 | use serde::{Deserialize, Serialize}; |
| 54 | |
| 55 | use crate::error::{Error, Result}; |
| 56 | |
| 57 | // ── Constants (s3/leaser.go:21-25, heartbeat.go:11-15) ──────────────────────── |
| 58 | |
| 59 | /// Default lease time-to-live. Ported from `DefaultLeaseTTL` (s3/leaser.go:22). |
| 60 | pub const DEFAULT_LEASE_TTL: Duration = Duration::from_secs(30); |
| 61 | |
| 62 | /// Lock-object filename appended to the replica prefix. |
| 63 | /// Ported from `DefaultLeasePath` (s3/leaser.go:23). |
| 64 | pub const DEFAULT_LEASE_PATH: &str = "lock.json"; |
| 65 | |
| 66 | /// Backend type tag for the S3 leaser. Ported from `LeaserType` (s3/leaser.go:24). |
| 67 | pub const LEASER_TYPE: &str = "s3"; |
| 68 | |
| 69 | /// Default heartbeat interval. Ported from `DefaultHeartbeatInterval` (heartbeat.go:12). |
| 70 | pub const DEFAULT_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5 * 60); |
| 71 | |
| 72 | /// Default heartbeat HTTP timeout. Ported from `DefaultHeartbeatTimeout` (heartbeat.go:13). |
| 73 | pub const DEFAULT_HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(30); |
| 74 | |
| 75 | /// Floor on the heartbeat interval, enforced by the constructor regardless of the |
| 76 | /// caller's value. Ported from `MinHeartbeatInterval` (heartbeat.go:14). |
| 77 | pub const MIN_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(60); |
| 78 | |
| 79 | // ── Sentinel errors (leaser.go:10-22, s3/leaser.go:30-33) ───────────────────── |
| 80 | |
| 81 | /// The caller no longer holds the lease — a concurrent writer took over, or the |
| 82 | /// conditional write failed on an ETag mismatch. |
| 83 | /// |
| 84 | /// Maps to `litestream.ErrLeaseNotHeld` (leaser.go:10). |
| 85 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 86 | pub struct LeaseNotHeld; |
| 87 | |
| 88 | impl std::fmt::Display for LeaseNotHeld { |
| 89 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 90 | f.write_str("lease not held") |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | impl std::error::Error for LeaseNotHeld {} |
| 95 | |
| 96 | /// A lease was supplied with no ETag, so it cannot be renewed or released. |
| 97 | /// |
| 98 | /// Maps to `s3.ErrLeaseETagRequired` (s3/leaser.go:31). |
| 99 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 100 | pub struct LeaseETagRequired; |
| 101 | |
| 102 | impl std::fmt::Display for LeaseETagRequired { |
| 103 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 104 | f.write_str("lease etag required") |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | impl std::error::Error for LeaseETagRequired {} |
| 109 | |
| 110 | /// The lock object was already gone when release attempted to delete it. |
| 111 | /// |
| 112 | /// Maps to `s3.ErrLeaseAlreadyReleased` (s3/leaser.go:32). |
| 113 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 114 | pub struct LeaseAlreadyReleased; |
| 115 | |
| 116 | impl std::fmt::Display for LeaseAlreadyReleased { |
| 117 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 118 | f.write_str("lease already released") |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | impl std::error::Error for LeaseAlreadyReleased {} |
| 123 | |
| 124 | /// Another node currently holds a live, unexpired lease. |
| 125 | /// |
| 126 | /// Maps to `litestream.LeaseExistsError` (leaser.go:12-22). The `Display` form is |
| 127 | /// a byte-for-byte port of the Go `Error()` method (leaser.go:17-21), including |
| 128 | /// the RFC-3339 rendering of `expires_at` and the with/without-owner branch. |
| 129 | #[derive(Debug, Clone)] |
| 130 | pub struct LeaseExistsError { |
| 131 | /// Identity string of the current holder; may be empty. |
| 132 | pub owner: String, |
| 133 | /// Absolute wall-clock expiry of the current holder's lease. |
| 134 | pub expires_at: SystemTime, |
| 135 | } |
| 136 | |
| 137 | impl std::fmt::Display for LeaseExistsError { |
| 138 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 139 | // Go: if e.Owner != "" { "lease already held by %s until %s" } |
| 140 | // else { "lease already held until %s" } |
| 141 | // with %s == e.ExpiresAt.Format(time.RFC3339). |
| 142 | let until = rfc3339::format(self.expires_at); |
| 143 | if self.owner.is_empty() { |
| 144 | write!(f, "lease already held until {until}") |
| 145 | } else { |
| 146 | write!(f, "lease already held by {} until {until}", self.owner) |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | impl std::error::Error for LeaseExistsError {} |
| 152 | |
| 153 | // Allow `?` to lift the concrete sentinels into the crate-wide `Error` via the |
| 154 | // `Other` boxed-error variant. This mirrors Go returning the bare sentinel values |
| 155 | // from the `Leaser` interface methods; callers recover the concrete type with the |
| 156 | // `Error::is_lease_*` / `Error::as_lease_exists` helpers below (the analogue of |
| 157 | // Go's `errors.Is` / `errors.As`). |
| 158 | impl From<LeaseNotHeld> for Error { |
| 159 | fn from(e: LeaseNotHeld) -> Self { |
| 160 | Error::Other(Box::new(e)) |
| 161 | } |
| 162 | } |
| 163 | impl From<LeaseETagRequired> for Error { |
| 164 | fn from(e: LeaseETagRequired) -> Self { |
| 165 | Error::Other(Box::new(e)) |
| 166 | } |
| 167 | } |
| 168 | impl From<LeaseAlreadyReleased> for Error { |
| 169 | fn from(e: LeaseAlreadyReleased) -> Self { |
| 170 | Error::Other(Box::new(e)) |
| 171 | } |
| 172 | } |
| 173 | impl From<LeaseExistsError> for Error { |
| 174 | fn from(e: LeaseExistsError) -> Self { |
| 175 | Error::Other(Box::new(e)) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | impl Error { |
| 180 | /// Returns `true` when this error is (or wraps) [`LeaseNotHeld`]. |
| 181 | /// |
| 182 | /// The analogue of Go's `errors.Is(err, ErrLeaseNotHeld)` (s3/leaser.go:156). |
| 183 | pub fn is_lease_not_held(&self) -> bool { |
| 184 | matches!(self, Error::Other(b) if b.downcast_ref::<LeaseNotHeld>().is_some()) |
| 185 | } |
| 186 | |
| 187 | /// Returns `true` when this error is (or wraps) [`LeaseAlreadyReleased`]. |
| 188 | /// |
| 189 | /// The analogue of `errors.Is(err, ErrLeaseAlreadyReleased)` (s3/leaser.go:187). |
| 190 | pub fn is_lease_already_released(&self) -> bool { |
| 191 | matches!(self, Error::Other(b) if b.downcast_ref::<LeaseAlreadyReleased>().is_some()) |
| 192 | } |
| 193 | |
| 194 | /// Returns `true` when this error is (or wraps) [`LeaseETagRequired`]. |
| 195 | pub fn is_lease_etag_required(&self) -> bool { |
| 196 | matches!(self, Error::Other(b) if b.downcast_ref::<LeaseETagRequired>().is_some()) |
| 197 | } |
| 198 | |
| 199 | /// Borrows the inner [`LeaseExistsError`] if this error is one. |
| 200 | /// |
| 201 | /// The analogue of Go's `errors.As(err, &leaseErr)` (s3/leaser.go:117, 154). |
| 202 | pub fn as_lease_exists(&self) -> Option<&LeaseExistsError> { |
| 203 | match self { |
| 204 | Error::Other(b) => b.downcast_ref::<LeaseExistsError>(), |
| 205 | _ => None, |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | // ── Lease value type (leaser.go:31-44) ──────────────────────────────────────── |
| 211 | |
| 212 | /// A snapshot of a held lease. |
| 213 | /// |
| 214 | /// Maps to `litestream.Lease` (leaser.go:31-36). The JSON shape matches Go's |
| 215 | /// struct tags exactly: `generation` (i64), `expires_at` (RFC-3339 string), |
| 216 | /// `owner` (omitted when empty), and `e_tag` is **not** serialised (`json:"-"`). |
| 217 | /// |
| 218 | /// `expires_at` is a wall-clock [`SystemTime`] (not a monotonic `Instant`) because |
| 219 | /// it is serialised into the lock object and compared *across nodes* whose clocks |
| 220 | /// may differ (brief §5.7). |
| 221 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 222 | pub struct Lease { |
| 223 | /// Monotonically increasing acquisition counter (split-brain detector). |
| 224 | pub generation: i64, |
| 225 | /// Absolute wall-clock expiry, serialised as RFC-3339 (Go `time.RFC3339Nano`). |
| 226 | #[serde(with = "rfc3339")] |
| 227 | pub expires_at: SystemTime, |
| 228 | /// Owner identity (`hostname:pid`); omitted from JSON when empty. |
| 229 | #[serde(default, skip_serializing_if = "String::is_empty")] |
| 230 | pub owner: String, |
| 231 | /// Object-store ETag of the lock object this lease was read/written from. |
| 232 | /// Not serialised (matches Go's `json:"-"`). |
| 233 | #[serde(skip)] |
| 234 | pub e_tag: String, |
| 235 | } |
| 236 | |
| 237 | impl Lease { |
| 238 | /// Returns `true` once the wall clock has passed `expires_at`. |
| 239 | /// |
| 240 | /// Ported from `Lease.IsExpired` (leaser.go:38-40): `time.Now().After(ExpiresAt)`. |
| 241 | /// Note Go uses strict `After`, so a lease is *not* expired at the exact instant |
| 242 | /// `now == expires_at`; we match that with `SystemTime::now() > self.expires_at`. |
| 243 | pub fn is_expired(&self) -> bool { |
| 244 | SystemTime::now() > self.expires_at |
| 245 | } |
| 246 | |
| 247 | /// Returns the remaining time until expiry, or `None` once expired. |
| 248 | /// |
| 249 | /// Ported from `Lease.TTL` (leaser.go:42-44): `time.Until(ExpiresAt)`. Go |
| 250 | /// returns a *negative* duration past expiry; Rust `Duration` is unsigned, so |
| 251 | /// we surface the past-expiry case as `None` rather than a wrapped value. |
| 252 | pub fn ttl(&self) -> Option<Duration> { |
| 253 | self.expires_at.duration_since(SystemTime::now()).ok() |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | // ── Leaser trait (leaser.go:24-29) ──────────────────────────────────────────── |
| 258 | |
| 259 | /// Object-storage lease provider. |
| 260 | /// |
| 261 | /// Maps to the `litestream.Leaser` interface (leaser.go:24-29). Object-safe so |
| 262 | /// alternate backends can be added behind feature flags later. |
| 263 | #[async_trait::async_trait] |
| 264 | pub trait Leaser: Send + Sync { |
| 265 | /// Short identifier for the backend (`"s3"`, …). Ported from `Type()`. |
| 266 | fn leaser_type(&self) -> &str; |
| 267 | |
| 268 | /// Attempt to acquire the lease. Returns an [`Error`] wrapping |
| 269 | /// [`LeaseExistsError`] when another node holds a live, unexpired lease. |
| 270 | async fn acquire_lease(&self) -> Result<Lease>; |
| 271 | |
| 272 | /// Renew a held lease. Returns an [`Error`] wrapping [`LeaseNotHeld`] when the |
| 273 | /// conditional write fails (ETag mismatch — another node took over). |
| 274 | async fn renew_lease(&self, lease: &Lease) -> Result<Lease>; |
| 275 | |
| 276 | /// Release a held lease. Returns [`LeaseNotHeld`] on ETag mismatch and |
| 277 | /// [`LeaseAlreadyReleased`] when the lock object is already gone. |
| 278 | async fn release_lease(&self, lease: &Lease) -> Result<()>; |
| 279 | } |
| 280 | |
| 281 | // ── S3 implementation (s3/leaser.go:42-266) ─────────────────────────────────── |
| 282 | |
| 283 | /// S3-backed lease using the `object_store` crate as the transport. |
| 284 | /// |
| 285 | /// Maps to `s3.Leaser` (s3/leaser.go:42-50). Backend-agnostic: any |
| 286 | /// `Arc<dyn ObjectStore>` that honours `PutMode::Create` / `PutMode::Update` |
| 287 | /// (S3/MinIO/R2 via `object_store/aws`, or the in-memory store in tests) works. |
| 288 | pub struct S3Leaser { |
| 289 | store: std::sync::Arc<dyn object_store::ObjectStore>, |
| 290 | /// Prefix under which the lock object lives; the key is `path/lock.json` |
| 291 | /// (or just `lock.json` when empty). See [`S3Leaser::lock_key`]. |
| 292 | path: String, |
| 293 | /// Lease time-to-live; `expires_at = now() + ttl` is stamped at write time. |
| 294 | ttl: Duration, |
| 295 | /// Owner identity written into the lease (default `hostname:pid`). |
| 296 | owner: String, |
| 297 | } |
| 298 | |
| 299 | impl S3Leaser { |
| 300 | /// Creates a leaser over the given object store with the defaults from |
| 301 | /// `NewLeaser` (s3/leaser.go:52-65): empty path, 30 s TTL, owner `hostname:pid`. |
| 302 | pub fn new(store: std::sync::Arc<dyn object_store::ObjectStore>) -> Self { |
| 303 | S3Leaser { |
| 304 | store, |
| 305 | path: String::new(), |
| 306 | ttl: DEFAULT_LEASE_TTL, |
| 307 | owner: default_owner(), |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | /// Sets the object-store prefix the lock object lives under. |
| 312 | pub fn with_path(mut self, path: impl Into<String>) -> Self { |
| 313 | self.path = path.into(); |
| 314 | self |
| 315 | } |
| 316 | |
| 317 | /// Overrides the lease TTL (default [`DEFAULT_LEASE_TTL`]). |
| 318 | pub fn with_ttl(mut self, ttl: Duration) -> Self { |
| 319 | self.ttl = ttl; |
| 320 | self |
| 321 | } |
| 322 | |
| 323 | /// Overrides the owner identity (default `hostname:pid`). |
| 324 | pub fn with_owner(mut self, owner: impl Into<String>) -> Self { |
| 325 | self.owner = owner.into(); |
| 326 | self |
| 327 | } |
| 328 | |
| 329 | /// The owner identity this leaser stamps into acquired leases. |
| 330 | pub fn owner(&self) -> &str { |
| 331 | &self.owner |
| 332 | } |
| 333 | |
| 334 | /// The configured lease TTL. |
| 335 | pub fn ttl(&self) -> Duration { |
| 336 | self.ttl |
| 337 | } |
| 338 | |
| 339 | /// Builds the lock-object key: `lock.json` when `path` is empty, else |
| 340 | /// `<path>/lock.json`. Ported byte-for-byte from `lockKey` (s3/leaser.go:83-88). |
| 341 | fn lock_key(&self) -> object_store::path::Path { |
| 342 | let key = if self.path.is_empty() { |
| 343 | DEFAULT_LEASE_PATH.to_string() |
| 344 | } else { |
| 345 | format!("{}/{}", self.path, DEFAULT_LEASE_PATH) |
| 346 | }; |
| 347 | object_store::path::Path::from(key) |
| 348 | } |
| 349 | |
| 350 | /// Reads the current lock object. Returns `Ok(None)` when the object is absent |
| 351 | /// (the Go `os.ErrNotExist` path, s3/leaser.go:210-212); otherwise the decoded |
| 352 | /// [`Lease`] with its `e_tag` populated from the object metadata. |
| 353 | /// |
| 354 | /// Ported from `readLease` (s3/leaser.go:202-229). |
| 355 | async fn read_lease(&self) -> Result<Option<Lease>> { |
| 356 | let key = self.lock_key(); |
| 357 | let result = match self.store.get(&key).await { |
| 358 | Ok(r) => r, |
| 359 | Err(object_store::Error::NotFound { .. }) => return Ok(None), |
| 360 | Err(e) => { |
| 361 | return Err(Error::Other(format!("get lock file: {e}").into())); |
| 362 | } |
| 363 | }; |
| 364 | |
| 365 | // Capture the ETag before consuming the body (s3/leaser.go:222-226). |
| 366 | let etag = result.meta.e_tag.clone().unwrap_or_default(); |
| 367 | let bytes = result |
| 368 | .bytes() |
| 369 | .await |
| 370 | .map_err(|e| Error::Other(format!("read lock file: {e}").into()))?; |
| 371 | |
| 372 | let mut lease: Lease = serde_json::from_slice(&bytes) |
| 373 | .map_err(|e| Error::Other(format!("decode lock file: {e}").into()))?; |
| 374 | lease.e_tag = etag; |
| 375 | Ok(Some(lease)) |
| 376 | } |
| 377 | |
| 378 | /// Writes `lease` to the lock object under compare-and-swap: |
| 379 | /// |
| 380 | /// - `current_e_tag == ""` → `PutMode::Create` (`If-None-Match: *`). |
| 381 | /// - `current_e_tag == etag` → `PutMode::Update(If-Match: etag)`. |
| 382 | /// |
| 383 | /// Returns the new ETag on success. A failed CAS (`AlreadyExists` from a losing |
| 384 | /// Create, or `Precondition` from a losing Update) is surfaced as a *blank* |
| 385 | /// [`LeaseExistsError`] for the caller to enrich via a re-read — exactly as |
| 386 | /// Go's `writeLease` returns `&LeaseExistsError{}` on 412 (s3/leaser.go:254-256). |
| 387 | /// |
| 388 | /// Ported from `writeLease` (s3/leaser.go:231-266). |
| 389 | async fn write_lease(&self, lease: &Lease, current_e_tag: &str) -> Result<String> { |
| 390 | let key = self.lock_key(); |
| 391 | let data = serde_json::to_vec(lease) |
| 392 | .map_err(|e| Error::Other(format!("marshal lock file: {e}").into()))?; |
| 393 | |
| 394 | // s3/leaser.go:246-250: empty etag → IfNoneMatch:"*" (Create), else |
| 395 | // IfMatch:<etag> (Update). |
| 396 | let mode = if current_e_tag.is_empty() { |
| 397 | object_store::PutMode::Create |
| 398 | } else { |
| 399 | object_store::PutMode::Update(object_store::UpdateVersion { |
| 400 | e_tag: Some(current_e_tag.to_string()), |
| 401 | version: None, |
| 402 | }) |
| 403 | }; |
| 404 | |
| 405 | // Match the Go uploader's `ContentType: application/json` (s3/leaser.go:243) |
| 406 | // via the object_store attribute of the same name. |
| 407 | let mut attributes = object_store::Attributes::new(); |
| 408 | attributes.insert( |
| 409 | object_store::Attribute::ContentType, |
| 410 | object_store::AttributeValue::from("application/json"), |
| 411 | ); |
| 412 | |
| 413 | let opts = object_store::PutOptions { |
| 414 | mode, |
| 415 | attributes, |
| 416 | ..Default::default() |
| 417 | }; |
| 418 | |
| 419 | let result = match self |
| 420 | .store |
| 421 | .put_opts(&key, object_store::PutPayload::from(data), opts) |
| 422 | .await |
| 423 | { |
| 424 | Ok(r) => r, |
| 425 | // Both map to Go's `isPreconditionFailed` → `&LeaseExistsError{}`: |
| 426 | // * `AlreadyExists` — losing `Create` (S3 returns 412 for a |
| 427 | // conflicting If-None-Match:*; object_store's |
| 428 | // InMemory store surfaces it as AlreadyExists). |
| 429 | // * `Precondition` — losing `Update` (If-Match mismatch / 412). |
| 430 | // The brief (§5.1) requires mapping BOTH (s3/leaser.go:254-256). |
| 431 | Err(object_store::Error::AlreadyExists { .. }) |
| 432 | | Err(object_store::Error::Precondition { .. }) => { |
| 433 | return Err(Error::Other(Box::new(LeaseExistsError { |
| 434 | owner: String::new(), |
| 435 | expires_at: SystemTime::UNIX_EPOCH, |
| 436 | }))); |
| 437 | } |
| 438 | Err(e) => { |
| 439 | return Err(Error::Other(format!("put lock file: {e}").into())); |
| 440 | } |
| 441 | }; |
| 442 | |
| 443 | Ok(result.e_tag.unwrap_or_default()) |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | #[async_trait::async_trait] |
| 448 | impl Leaser for S3Leaser { |
| 449 | fn leaser_type(&self) -> &str { |
| 450 | LEASER_TYPE |
| 451 | } |
| 452 | |
| 453 | /// Ported from `AcquireLease` (s3/leaser.go:90-136). |
| 454 | async fn acquire_lease(&self) -> Result<Lease> { |
| 455 | // Read any existing lease. Absence (None) is fine; any other read error |
| 456 | // propagates (s3/leaser.go:91-94). |
| 457 | let existing = self.read_lease().await?; |
| 458 | let existing_etag = existing |
| 459 | .as_ref() |
| 460 | .map(|l| l.e_tag.clone()) |
| 461 | .unwrap_or_default(); |
| 462 | |
| 463 | // A live unexpired lease blocks acquisition (s3/leaser.go:96-101). |
| 464 | if let Some(ref ex) = existing { |
| 465 | if !ex.is_expired() { |
| 466 | return Err(Error::Other(Box::new(LeaseExistsError { |
| 467 | owner: ex.owner.clone(), |
| 468 | expires_at: ex.expires_at, |
| 469 | }))); |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | // generation = existing+1, or 1 when there was no prior lease |
| 474 | // (s3/leaser.go:103-107). |
| 475 | let generation = match existing { |
| 476 | Some(ref ex) => ex.generation + 1, |
| 477 | None => 1, |
| 478 | }; |
| 479 | |
| 480 | let new_lease = Lease { |
| 481 | generation, |
| 482 | expires_at: SystemTime::now() + self.ttl, |
| 483 | owner: self.owner.clone(), |
| 484 | e_tag: String::new(), |
| 485 | }; |
| 486 | |
| 487 | // CAS-write. On a losing CAS, re-read to populate the winner's identity in |
| 488 | // the returned LeaseExistsError (s3/leaser.go:114-126) — never surface the |
| 489 | // blank error writeLease produced. |
| 490 | let new_etag = match self.write_lease(&new_lease, &existing_etag).await { |
| 491 | Ok(etag) => etag, |
| 492 | Err(e) if e.as_lease_exists().is_some() => { |
| 493 | if let Ok(Some(current)) = self.read_lease().await { |
| 494 | return Err(Error::Other(Box::new(LeaseExistsError { |
| 495 | owner: current.owner, |
| 496 | expires_at: current.expires_at, |
| 497 | }))); |
| 498 | } |
| 499 | return Err(e); |
| 500 | } |
| 501 | Err(e) => return Err(e), |
| 502 | }; |
| 503 | |
| 504 | let mut acquired = new_lease; |
| 505 | acquired.e_tag = new_etag; |
| 506 | tracing::debug!( |
| 507 | generation = acquired.generation, |
| 508 | owner = %acquired.owner, |
| 509 | etag = %acquired.e_tag, |
| 510 | "lease acquired" |
| 511 | ); |
| 512 | Ok(acquired) |
| 513 | } |
| 514 | |
| 515 | /// Ported from `RenewLease` (s3/leaser.go:138-169). |
| 516 | async fn renew_lease(&self, lease: &Lease) -> Result<Lease> { |
| 517 | // Go guards nil-lease before ETag; our `&Lease` cannot be null, so the |
| 518 | // `ErrLeaseRequired` guard (s3/leaser.go:139-141) is unrepresentable here. |
| 519 | // The empty-ETag guard remains load-bearing (s3/leaser.go:142-144). |
| 520 | if lease.e_tag.is_empty() { |
| 521 | return Err(LeaseETagRequired.into()); |
| 522 | } |
| 523 | |
| 524 | // Renewal keeps the same generation, only extends the TTL (s3/leaser.go:146-150). |
| 525 | let new_lease = Lease { |
| 526 | generation: lease.generation, |
| 527 | expires_at: SystemTime::now() + self.ttl, |
| 528 | owner: self.owner.clone(), |
| 529 | e_tag: String::new(), |
| 530 | }; |
| 531 | |
| 532 | // A failed CAS (someone wrote the key since we last saw it) → LeaseNotHeld |
| 533 | // (s3/leaser.go:152-159). |
| 534 | let new_etag = match self.write_lease(&new_lease, &lease.e_tag).await { |
| 535 | Ok(etag) => etag, |
| 536 | Err(e) if e.as_lease_exists().is_some() => return Err(LeaseNotHeld.into()), |
| 537 | Err(e) => return Err(e), |
| 538 | }; |
| 539 | |
| 540 | let mut renewed = new_lease; |
| 541 | renewed.e_tag = new_etag; |
| 542 | tracing::debug!( |
| 543 | generation = renewed.generation, |
| 544 | owner = %renewed.owner, |
| 545 | etag = %renewed.e_tag, |
| 546 | "lease renewed" |
| 547 | ); |
| 548 | Ok(renewed) |
| 549 | } |
| 550 | |
| 551 | /// Ported from `ReleaseLease` (s3/leaser.go:171-200), via the read-then-delete |
| 552 | /// strategy documented in the module header (object_store has no conditional |
| 553 | /// DELETE). |
| 554 | async fn release_lease(&self, lease: &Lease) -> Result<()> { |
| 555 | if lease.e_tag.is_empty() { |
| 556 | return Err(LeaseETagRequired.into()); |
| 557 | } |
| 558 | |
| 559 | // DEVIATION from Go: read-then-delete to emulate DeleteObject{IfMatch}. |
| 560 | // Absent object → already released (Go 404 path, s3/leaser.go:186-188). |
| 561 | let current = match self.read_lease().await? { |
| 562 | Some(c) => c, |
| 563 | None => return Err(LeaseAlreadyReleased.into()), |
| 564 | }; |
| 565 | |
| 566 | // ETag mismatch → another node owns the key now (Go 412 path, |
| 567 | // s3/leaser.go:189-191). |
| 568 | if current.e_tag != lease.e_tag { |
| 569 | return Err(LeaseNotHeld.into()); |
| 570 | } |
| 571 | |
| 572 | // ETag matches: delete. A NotFound during the delete means the object was |
| 573 | // removed in the TOCTOU window — treat as success (the lock is gone, which |
| 574 | // is the post-condition release wants). |
| 575 | let key = self.lock_key(); |
| 576 | match self.store.delete(&key).await { |
| 577 | Ok(()) => {} |
| 578 | Err(object_store::Error::NotFound { .. }) => {} |
| 579 | Err(e) => return Err(Error::Other(format!("delete lease: {e}").into())), |
| 580 | } |
| 581 | |
| 582 | tracing::debug!( |
| 583 | generation = lease.generation, |
| 584 | owner = %lease.owner, |
| 585 | "lease released" |
| 586 | ); |
| 587 | Ok(()) |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | /// Default owner identity `hostname:pid`, falling back to `pid-<pid>` when the |
| 592 | /// hostname is unavailable. Ported from `NewLeaser` (s3/leaser.go:53-58). |
| 593 | fn default_owner() -> String { |
| 594 | let pid = std::process::id(); |
| 595 | match hostname() { |
| 596 | Some(h) if !h.is_empty() => format!("{h}:{pid}"), |
| 597 | _ => format!("pid-{pid}"), |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | /// Best-effort hostname lookup with no external crate. Returns `None` when |
| 602 | /// unavailable, mirroring Go's `os.Hostname()` returning an error |
| 603 | /// (s3/leaser.go:53-54), which the caller treats as the empty string. |
| 604 | /// |
| 605 | /// The owner string is purely informational (it populates `LeaseExistsError` for |
| 606 | /// operators); it is never used in a correctness decision, so an env-based |
| 607 | /// best-effort source is acceptable and avoids a libc/`hostname` dependency |
| 608 | /// (AGENTS.md §7). |
| 609 | fn hostname() -> Option<String> { |
| 610 | std::env::var("HOSTNAME") |
| 611 | .ok() |
| 612 | .filter(|h| !h.is_empty()) |
| 613 | .or_else(|| std::env::var("COMPUTERNAME").ok().filter(|h| !h.is_empty())) |
| 614 | } |
| 615 | |
| 616 | // ── HeartbeatClient (heartbeat.go:17-84) ────────────────────────────────────── |
| 617 | |
| 618 | /// Optional HTTP liveness-ping companion for the renew loop. |
| 619 | /// |
| 620 | /// Maps to `litestream.HeartbeatClient` (heartbeat.go:17-26). It fires a throttled |
| 621 | /// HTTP GET at a configurable URL; an empty URL makes [`HeartbeatClient::ping`] a |
| 622 | /// no-op. It does not interact with the lease protocol itself (brief §1). |
| 623 | /// |
| 624 | /// The throttle state machine ([`should_ping`](Self::should_ping) / |
| 625 | /// [`record_ping`](Self::record_ping) / [`last_ping_at`](Self::last_ping_at)) and |
| 626 | /// the [`MIN_HEARTBEAT_INTERVAL`] clamp are always available; the actual HTTP GET |
| 627 | /// in `ping()` is compiled only when the `s3` feature is on (that is where |
| 628 | /// `reqwest` — already a transitive dependency of `object_store/aws` — is present). |
| 629 | /// Under `--no-default-features` `ping()` still exists and still honours the |
| 630 | /// empty-URL no-op; a non-empty URL there returns an error rather than silently |
| 631 | /// doing nothing, so the contract is never weakened. |
| 632 | pub struct HeartbeatClient { |
| 633 | /// Target URL; empty = disabled. |
| 634 | url: String, |
| 635 | /// Minimum spacing between pings (clamped to `>= MIN_HEARTBEAT_INTERVAL`). |
| 636 | interval: Duration, |
| 637 | /// HTTP request timeout. |
| 638 | timeout: Duration, |
| 639 | /// Monotonic instant of the last recorded ping (`None` until first). |
| 640 | last_ping_at: Mutex<Option<Instant>>, |
| 641 | } |
| 642 | |
| 643 | impl HeartbeatClient { |
| 644 | /// Constructs a heartbeat client, clamping `interval` up to |
| 645 | /// [`MIN_HEARTBEAT_INTERVAL`]. Ported from `NewHeartbeatClient` (heartbeat.go:28-43). |
| 646 | pub fn new(url: impl Into<String>, interval: Duration) -> Self { |
| 647 | let interval = if interval < MIN_HEARTBEAT_INTERVAL { |
| 648 | MIN_HEARTBEAT_INTERVAL |
| 649 | } else { |
| 650 | interval |
| 651 | }; |
| 652 | HeartbeatClient { |
| 653 | url: url.into(), |
| 654 | interval, |
| 655 | timeout: DEFAULT_HEARTBEAT_TIMEOUT, |
| 656 | last_ping_at: Mutex::new(None), |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | /// The configured target URL. |
| 661 | pub fn url(&self) -> &str { |
| 662 | &self.url |
| 663 | } |
| 664 | |
| 665 | /// The (clamped) ping interval. |
| 666 | pub fn interval(&self) -> Duration { |
| 667 | self.interval |
| 668 | } |
| 669 | |
| 670 | /// The request timeout. |
| 671 | pub fn timeout(&self) -> Duration { |
| 672 | self.timeout |
| 673 | } |
| 674 | |
| 675 | /// Returns `true` once at least `interval` has elapsed since the last ping |
| 676 | /// (always `true` before the first ping). Ported from `ShouldPing` |
| 677 | /// (heartbeat.go:68-72): `time.Since(lastPingAt) >= Interval`. |
| 678 | pub fn should_ping(&self) -> bool { |
| 679 | let last = *self.last_ping_at.lock().expect("heartbeat mutex poisoned"); |
| 680 | match last { |
| 681 | None => true, |
| 682 | Some(t) => t.elapsed() >= self.interval, |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | /// The instant of the last recorded ping, if any. Ported from `LastPingAt` |
| 687 | /// (heartbeat.go:74-78). |
| 688 | pub fn last_ping_at(&self) -> Option<Instant> { |
| 689 | *self.last_ping_at.lock().expect("heartbeat mutex poisoned") |
| 690 | } |
| 691 | |
| 692 | /// Records the current instant as the last ping time. Ported from `RecordPing` |
| 693 | /// (heartbeat.go:80-84). |
| 694 | pub fn record_ping(&self) { |
| 695 | *self.last_ping_at.lock().expect("heartbeat mutex poisoned") = Some(Instant::now()); |
| 696 | } |
| 697 | |
| 698 | /// Fires the liveness GET. A no-op (returns `Ok`) when the URL is empty. |
| 699 | /// A non-2xx response is an error. Ported from `Ping` (heartbeat.go:45-66). |
| 700 | /// |
| 701 | /// This does **not** call [`record_ping`](Self::record_ping); the renew loop |
| 702 | /// records the ping itself, matching the Go split between `Ping` and |
| 703 | /// `RecordPing`. |
| 704 | #[cfg(feature = "s3")] |
| 705 | pub async fn ping(&self) -> Result<()> { |
| 706 | if self.url.is_empty() { |
| 707 | return Ok(()); |
| 708 | } |
| 709 | let client = reqwest::Client::builder() |
| 710 | .timeout(self.timeout) |
| 711 | .build() |
| 712 | .map_err(|e| Error::Other(format!("create request: {e}").into()))?; |
| 713 | let resp = client |
| 714 | .get(&self.url) |
| 715 | .send() |
| 716 | .await |
| 717 | .map_err(|e| Error::Other(format!("http request: {e}").into()))?; |
| 718 | let status = resp.status().as_u16(); |
| 719 | // heartbeat.go:61-63: anything outside [200,300) is an error. |
| 720 | if !(200..300).contains(&status) { |
| 721 | return Err(Error::Other( |
| 722 | format!("unexpected status code: {status}").into(), |
| 723 | )); |
| 724 | } |
| 725 | Ok(()) |
| 726 | } |
| 727 | |
| 728 | /// Fallback when the `s3` feature (and therefore `reqwest`) is absent: the |
| 729 | /// empty-URL no-op is preserved; a non-empty URL is an explicit error so the |
| 730 | /// liveness contract is never silently dropped. |
| 731 | #[cfg(not(feature = "s3"))] |
| 732 | pub async fn ping(&self) -> Result<()> { |
| 733 | if self.url.is_empty() { |
| 734 | return Ok(()); |
| 735 | } |
| 736 | Err(Error::Other( |
| 737 | "heartbeat ping requires the `s3` feature (HTTP client unavailable)".into(), |
| 738 | )) |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | // ── RFC-3339 SystemTime (de)serialisation ───────────────────────────────────── |
| 743 | // |
| 744 | // Go marshals `Lease.ExpiresAt` (a `time.Time`) with the default `time.Time` |
| 745 | // JSON encoder, i.e. RFC-3339 with nanosecond precision (`time.RFC3339Nano`, |
| 746 | // e.g. "2026-05-30T12:34:56.789012345Z"). Critically, the lock object is NOT |
| 747 | // rustyriver-internal: real Litestream and rustyriver can share/migrate/fail-over |
| 748 | // the same `lock.json`, so this code must read whatever the Go binary wrote. |
| 749 | // |
| 750 | // emit vs. parse are asymmetric on purpose: |
| 751 | // * `format` always emits a `…Z` UTC string. (rustyriver never has to match Go's |
| 752 | // bytes here — Go re-parses by value, not by string, and the only Go consumer |
| 753 | // of our serialisation is its own `time.RFC3339Nano` parser, which accepts our |
| 754 | // `Z` form verbatim.) |
| 755 | // * `parse` must accept BOTH `…Z` and the numeric-offset form `…±HH:MM`, because |
| 756 | // Go's `s3.Leaser` stamps `time.Now().Add(TTL)` with no `.UTC()`, so on any |
| 757 | // non-UTC host the marshaller writes the expiry in local time with a numeric |
| 758 | // offset (s3/leaser.go:110,148; confirmed byte-for-byte with Go 1.25). Both |
| 759 | // forms denote the same UTC instant, which is all `is_expired`/`ttl` compare, |
| 760 | // so `parse` normalises the offset away. (Contrast the T7 metadata path, where |
| 761 | // Go calls `.UTC()` explicitly and only `Z` can occur.) |
| 762 | // |
| 763 | // We keep this module self-contained (no `chrono`/`time` dependency, matching the |
| 764 | // T7 precedent logged in OPEN_QUESTIONS.md), preserving nanosecond resolution — |
| 765 | // which `SystemTime::now()` carries and the millisecond-only helper in |
| 766 | // `client/object_store.rs` would truncate. |
| 767 | mod rfc3339 { |
| 768 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 769 | |
| 770 | use serde::{de::Error as _, Deserialize, Deserializer, Serializer}; |
| 771 | |
| 772 | /// serde `serialize_with` entry point for a `SystemTime` field. |
| 773 | pub fn serialize<S: Serializer>(t: &SystemTime, s: S) -> std::result::Result<S::Ok, S::Error> { |
| 774 | s.serialize_str(&format(*t)) |
| 775 | } |
| 776 | |
| 777 | /// serde `deserialize_with` entry point for a `SystemTime` field. |
| 778 | pub fn deserialize<'de, D: Deserializer<'de>>( |
| 779 | d: D, |
| 780 | ) -> std::result::Result<SystemTime, D::Error> { |
| 781 | let s = String::deserialize(d)?; |
| 782 | parse(&s).ok_or_else(|| D::Error::custom(format!("invalid RFC-3339 timestamp: {s:?}"))) |
| 783 | } |
| 784 | |
| 785 | /// Formats a `SystemTime` as an RFC-3339 UTC string (`…Z`), trimming trailing |
| 786 | /// zeros from the fractional-second field (Go `time.RFC3339Nano` behaviour). |
| 787 | /// Pre-epoch times are clamped to the epoch (lease expiries are always future |
| 788 | /// wall-clock values, so this only guards the degenerate UNIX_EPOCH sentinel). |
| 789 | pub fn format(t: SystemTime) -> String { |
| 790 | let dur = t.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); |
| 791 | let secs = dur.as_secs() as i64; |
| 792 | let nanos = dur.subsec_nanos(); |
| 793 | let (year, month, day, hour, min, sec) = civil_from_unix_secs(secs); |
| 794 | if nanos == 0 { |
| 795 | format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}Z") |
| 796 | } else { |
| 797 | // 9-digit nanos, trailing zeros trimmed (matches RFC3339Nano). |
| 798 | let mut frac = format!("{nanos:09}"); |
| 799 | while frac.ends_with('0') { |
| 800 | frac.pop(); |
| 801 | } |
| 802 | format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}.{frac}Z") |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | /// Parses an RFC-3339 timestamp (the trailing zone designator may be `Z` for |
| 807 | /// UTC, or a numeric offset `±HH:MM`) with optional fractional seconds, back |
| 808 | /// into a `SystemTime` normalised to UTC. Returns `None` on any shape we don't |
| 809 | /// recognise. |
| 810 | /// |
| 811 | /// We must accept the numeric-offset form because Go's `s3.Leaser` writes |
| 812 | /// `Lease.ExpiresAt = time.Now().Add(TTL)` (s3/leaser.go:110,148) **without** |
| 813 | /// `.UTC()`, and Go's default `time.Time` JSON marshaller (`time.RFC3339Nano`) |
| 814 | /// serialises in the host's LOCAL timezone — so a lock file written by real |
| 815 | /// Litestream on any non-UTC host carries an offset like `-04:00`/`+05:30`, |
| 816 | /// not a `Z` (empirically confirmed with Go 1.25 across several zones). The |
| 817 | /// grammar here is exactly what Go's `time.Parse(time.RFC3339Nano, …)` accepts |
| 818 | /// (and the marshaller emits): the zone is the literal `Z` or a `±HH:MM` with |
| 819 | /// the colon and 2+2 digits mandatory — basic-format `±HHMM`, offsets carrying |
| 820 | /// seconds (`±HH:MM:SS`), and lowercase `t`/`z` are all rejected by Go and |
| 821 | /// therefore by us. See OPEN_QUESTIONS.md (T15 Go→rustyriver direction). |
| 822 | pub fn parse(s: &str) -> Option<SystemTime> { |
| 823 | let (date, time_and_zone) = s.split_once('T')?; |
| 824 | |
| 825 | let mut dparts = date.split('-'); |
| 826 | let year: i64 = dparts.next()?.parse().ok()?; |
| 827 | let month: u32 = dparts.next()?.parse().ok()?; |
| 828 | let day: u32 = dparts.next()?.parse().ok()?; |
| 829 | if dparts.next().is_some() { |
| 830 | return None; |
| 831 | } |
| 832 | |
| 833 | // Split the trailing zone designator off the time field first, so the |
| 834 | // numeric-offset sign is never mistaken for part of the fractional |
| 835 | // seconds. `offset_secs` is the local-minus-UTC offset in seconds (0 for |
| 836 | // `Z`); the UTC instant is `local_civil_secs - offset_secs`. |
| 837 | let (time, offset_secs) = split_zone(time_and_zone)?; |
| 838 | |
| 839 | let (hms, frac) = match time.split_once('.') { |
| 840 | Some((hms, frac)) => (hms, Some(frac)), |
| 841 | None => (time, None), |
| 842 | }; |
| 843 | let mut tparts = hms.split(':'); |
| 844 | let hour: u32 = tparts.next()?.parse().ok()?; |
| 845 | let min: u32 = tparts.next()?.parse().ok()?; |
| 846 | let sec: u32 = tparts.next()?.parse().ok()?; |
| 847 | if tparts.next().is_some() { |
| 848 | return None; |
| 849 | } |
| 850 | |
| 851 | let civil_secs = unix_secs_from_civil(year, month, day, hour, min, sec)?; |
| 852 | // Normalise to UTC by removing the zone offset, then require a >= epoch |
| 853 | // result (lease expiries are always future wall-clock values). |
| 854 | let secs = civil_secs.checked_sub(offset_secs)?; |
| 855 | if secs < 0 { |
| 856 | return None; |
| 857 | } |
| 858 | let nanos: u32 = match frac { |
| 859 | None => 0, |
| 860 | Some(frac) => { |
| 861 | if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) { |
| 862 | return None; |
| 863 | } |
| 864 | let mut padded = frac.to_string(); |
| 865 | while padded.len() < 9 { |
| 866 | padded.push('0'); |
| 867 | } |
| 868 | padded.parse().ok()? |
| 869 | } |
| 870 | }; |
| 871 | Some(UNIX_EPOCH + Duration::new(secs as u64, nanos)) |
| 872 | } |
| 873 | |
| 874 | /// Strips the RFC-3339 zone designator from the end of the time field, |
| 875 | /// returning `(time_without_zone, offset_seconds)` where `offset_seconds` is |
| 876 | /// the local-minus-UTC offset (`0` for the `Z`/UTC form). Returns `None` for |
| 877 | /// any zone shape Go's `time.RFC3339Nano` rejects (no zone, lowercase `z`, |
| 878 | /// basic-format `±HHMM`, an offset with seconds, or out-of-range fields). |
| 879 | fn split_zone(time_and_zone: &str) -> Option<(&str, i64)> { |
| 880 | // UTC: a trailing uppercase `Z` (Go does not accept lowercase here). |
| 881 | if let Some(time) = time_and_zone.strip_suffix('Z') { |
| 882 | return Some((time, 0)); |
| 883 | } |
| 884 | |
| 885 | // Numeric offset `±HH:MM`. The sign is the last '+'/'-' in the string; in |
| 886 | // the time field proper ("HH:MM:SS[.frac]") neither character can appear, |
| 887 | // so the first such byte unambiguously begins the offset. |
| 888 | let sign_idx = time_and_zone.bytes().position(|b| b == b'+' || b == b'-')?; |
| 889 | let (time, zone) = time_and_zone.split_at(sign_idx); |
| 890 | let sign = if zone.as_bytes()[0] == b'+' { 1 } else { -1 }; |
| 891 | |
| 892 | // After the sign, exactly `HH:MM` (2 digits, ':', 2 digits) — matching |
| 893 | // Go's `Z07:00` layout. Reject `±HHMM` (no colon) and `±HH:MM:SS`. |
| 894 | let body = &zone[1..]; |
| 895 | let (hh, mm) = body.split_once(':')?; |
| 896 | if hh.len() != 2 |
| 897 | || mm.len() != 2 |
| 898 | || !hh.bytes().all(|b| b.is_ascii_digit()) |
| 899 | || !mm.bytes().all(|b| b.is_ascii_digit()) |
| 900 | { |
| 901 | return None; |
| 902 | } |
| 903 | let off_h: i64 = hh.parse().ok()?; |
| 904 | let off_m: i64 = mm.parse().ok()?; |
| 905 | if off_h > 23 || off_m > 59 { |
| 906 | return None; |
| 907 | } |
| 908 | Some((time, sign * (off_h * 3600 + off_m * 60))) |
| 909 | } |
| 910 | |
| 911 | /// Unix seconds (>= 0) → civil `(year, month, day, hour, min, sec)` in UTC. |
| 912 | /// Howard Hinnant's `civil_from_days` (public-domain), exact for all dates. |
| 913 | /// Mirrors the helper in `client/object_store.rs` (kept local to avoid a |
| 914 | /// cross-module private coupling). |
| 915 | fn civil_from_unix_secs(secs: i64) -> (i64, u32, u32, u32, u32, u32) { |
| 916 | let days = secs.div_euclid(86_400); |
| 917 | let rem = secs.rem_euclid(86_400); |
| 918 | let hour = (rem / 3600) as u32; |
| 919 | let min = ((rem % 3600) / 60) as u32; |
| 920 | let sec = (rem % 60) as u32; |
| 921 | |
| 922 | let z = days + 719_468; |
| 923 | let era = if z >= 0 { z } else { z - 146_096 } / 146_097; |
| 924 | let doe = z - era * 146_097; |
| 925 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; |
| 926 | let y = yoe + era * 400; |
| 927 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 928 | let mp = (5 * doy + 2) / 153; |
| 929 | let d = (doy - (153 * mp + 2) / 5 + 1) as u32; |
| 930 | let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; |
| 931 | let year = if m <= 2 { y + 1 } else { y }; |
| 932 | (year, m, d, hour, min, sec) |
| 933 | } |
| 934 | |
| 935 | /// Inverse of [`civil_from_unix_secs`]: civil UTC → Unix seconds. Returns |
| 936 | /// `None` for an out-of-range month/day. Howard Hinnant's `days_from_civil`. |
| 937 | fn unix_secs_from_civil( |
| 938 | year: i64, |
| 939 | month: u32, |
| 940 | day: u32, |
| 941 | hour: u32, |
| 942 | min: u32, |
| 943 | sec: u32, |
| 944 | ) -> Option<i64> { |
| 945 | if !(1..=12).contains(&month) |
| 946 | || !(1..=31).contains(&day) |
| 947 | || hour > 23 |
| 948 | || min > 59 |
| 949 | || sec > 60 |
| 950 | { |
| 951 | return None; |
| 952 | } |
| 953 | let y = if month <= 2 { year - 1 } else { year }; |
| 954 | let era = if y >= 0 { y } else { y - 399 } / 400; |
| 955 | let yoe = y - era * 400; |
| 956 | let m = month as i64; |
| 957 | let d = day as i64; |
| 958 | let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; |
| 959 | let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; |
| 960 | let days = era * 146_097 + doe - 719_468; |
| 961 | Some(days * 86_400 + hour as i64 * 3600 + min as i64 * 60 + sec as i64) |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | #[cfg(test)] |
| 966 | mod tests { |
| 967 | use super::*; |
| 968 | use object_store::memory::InMemory; |
| 969 | use object_store::ObjectStore; |
| 970 | use std::sync::Arc; |
| 971 | |
| 972 | // ── Lease value-type & serde ────────────────────────────────────────────── |
| 973 | |
| 974 | #[test] |
| 975 | fn lease_json_shape_matches_go() { |
| 976 | // Go marshals `{generation, expires_at (RFC-3339), owner?}` and drops ETag. |
| 977 | let lease = Lease { |
| 978 | generation: 7, |
| 979 | // 2021-01-01T00:00:00Z exactly (no fractional part). |
| 980 | expires_at: SystemTime::UNIX_EPOCH + Duration::from_secs(1_609_459_200), |
| 981 | owner: "host-a:42".to_string(), |
| 982 | e_tag: "\"should-not-appear\"".to_string(), |
| 983 | }; |
| 984 | let json = serde_json::to_string(&lease).unwrap(); |
| 985 | assert_eq!( |
| 986 | json, |
| 987 | r#"{"generation":7,"expires_at":"2021-01-01T00:00:00Z","owner":"host-a:42"}"# |
| 988 | ); |
| 989 | // ETag must not be serialised (Go json:"-"). |
| 990 | assert!(!json.contains("should-not-appear")); |
| 991 | assert!(!json.contains("e_tag")); |
| 992 | } |
| 993 | |
| 994 | #[test] |
| 995 | fn lease_owner_omitted_when_empty() { |
| 996 | let lease = Lease { |
| 997 | generation: 1, |
| 998 | expires_at: SystemTime::UNIX_EPOCH + Duration::from_secs(1_609_459_200), |
| 999 | owner: String::new(), |
| 1000 | e_tag: String::new(), |
| 1001 | }; |
| 1002 | let json = serde_json::to_string(&lease).unwrap(); |
| 1003 | assert_eq!( |
| 1004 | json, |
| 1005 | r#"{"generation":1,"expires_at":"2021-01-01T00:00:00Z"}"# |
| 1006 | ); |
| 1007 | } |
| 1008 | |
| 1009 | #[test] |
| 1010 | fn lease_serde_round_trips_with_nanos() { |
| 1011 | // SystemTime::now() carries sub-millisecond precision; ensure it survives. |
| 1012 | let original = Lease { |
| 1013 | generation: 99, |
| 1014 | expires_at: SystemTime::UNIX_EPOCH + Duration::new(1_700_000_000, 123_456_789), |
| 1015 | owner: "n:1".to_string(), |
| 1016 | e_tag: "\"etag-x\"".to_string(), |
| 1017 | }; |
| 1018 | let json = serde_json::to_string(&original).unwrap(); |
| 1019 | assert!(json.contains("2023-11-14T22:13:20.123456789Z")); |
| 1020 | let mut decoded: Lease = serde_json::from_str(&json).unwrap(); |
| 1021 | // ETag is not serialised, so re-attach before comparing the rest. |
| 1022 | assert_eq!(decoded.e_tag, ""); |
| 1023 | decoded.e_tag = original.e_tag.clone(); |
| 1024 | assert_eq!(decoded, original); |
| 1025 | } |
| 1026 | |
| 1027 | #[test] |
| 1028 | fn lease_parses_go_style_timestamp() { |
| 1029 | // A timestamp Go would emit (RFC3339Nano, fractional trimmed) must parse. |
| 1030 | let json = r#"{"generation":3,"expires_at":"2023-11-14T22:13:20.5Z","owner":"x"}"#; |
| 1031 | let lease: Lease = serde_json::from_str(json).unwrap(); |
| 1032 | let expected = SystemTime::UNIX_EPOCH + Duration::new(1_700_000_000, 500_000_000); |
| 1033 | assert_eq!(lease.expires_at, expected); |
| 1034 | assert_eq!(lease.generation, 3); |
| 1035 | } |
| 1036 | |
| 1037 | /// `rfc3339::parse` must accept the numeric-offset forms Go's local-timezone |
| 1038 | /// marshaller emits on non-UTC hosts and resolve each to the SAME UTC instant |
| 1039 | /// as the equivalent `Z` form. Every string below is the verbatim |
| 1040 | /// `json.Marshal` output for one fixed instant rendered in a different zone, |
| 1041 | /// captured from the Go 1.25 toolchain (`UTC`, `America/New_York`, |
| 1042 | /// `Asia/Kolkata`, `Asia/Kathmandu`, `Pacific/Chatham` — note the offset rolls |
| 1043 | /// the civil date to May 31 — and `America/St_Johns`). Go's |
| 1044 | /// `time.Parse(time.RFC3339Nano, …)` maps all six to unix=32485077296.789. |
| 1045 | #[test] |
| 1046 | fn parse_accepts_go_numeric_offsets_as_same_instant() { |
| 1047 | // 2999-05-30T16:34:56.789Z, the shared UTC instant. |
| 1048 | let expected = SystemTime::UNIX_EPOCH + Duration::new(32_485_077_296, 789_000_000); |
| 1049 | let go_emitted = [ |
| 1050 | "2999-05-30T16:34:56.789Z", // UTC |
| 1051 | "2999-05-30T12:34:56.789-04:00", // America/New_York |
| 1052 | "2999-05-30T22:04:56.789+05:30", // Asia/Kolkata |
| 1053 | "2999-05-30T22:19:56.789+05:45", // Asia/Kathmandu |
| 1054 | "2999-05-31T05:19:56.789+12:45", // Pacific/Chatham (date rolled +1) |
| 1055 | "2999-05-30T14:04:56.789-02:30", // America/St_Johns |
| 1056 | ]; |
| 1057 | for s in go_emitted { |
| 1058 | assert_eq!( |
| 1059 | rfc3339::parse(s), |
| 1060 | Some(expected), |
| 1061 | "offset form {s:?} must resolve to the canonical UTC instant" |
| 1062 | ); |
| 1063 | } |
| 1064 | |
| 1065 | // A whole-second offset value (no fractional part) Go also emits. |
| 1066 | assert_eq!( |
| 1067 | rfc3339::parse("2999-05-30T12:34:56-04:00"), |
| 1068 | Some(SystemTime::UNIX_EPOCH + Duration::from_secs(32_485_077_296)), |
| 1069 | ); |
| 1070 | } |
| 1071 | |
| 1072 | /// The parser must reject exactly the zone shapes Go's `time.RFC3339Nano` |
| 1073 | /// rejects, so we never silently accept input the real binary would refuse: |
| 1074 | /// missing zone, lowercase `z`/`t`, basic-format `±HHMM` (no colon), and an |
| 1075 | /// offset carrying seconds `±HH:MM:SS`. (All confirmed to fail `time.Parse` |
| 1076 | /// under Go 1.25.) |
| 1077 | #[test] |
| 1078 | fn parse_rejects_zone_forms_go_rejects() { |
| 1079 | let rejected = [ |
| 1080 | "2999-05-30T12:34:56.789", // no zone designator |
| 1081 | "2999-05-30t16:34:56.789z", // lowercase t and z |
| 1082 | "2999-05-30T16:34:56.789z", // lowercase z only |
| 1083 | "2999-05-30T12:34:56.789-0400", // basic-format offset (no colon) |
| 1084 | "2999-05-30T12:34:56.789-04:00:00", // offset with seconds |
| 1085 | "2999-05-30T12:34:56.789-4:00", // single-digit offset hour |
| 1086 | "2999-05-30T12:34:56.789+24:00", // out-of-range offset hour |
| 1087 | ]; |
| 1088 | for s in rejected { |
| 1089 | assert_eq!(rfc3339::parse(s), None, "{s:?} must be rejected like Go"); |
| 1090 | } |
| 1091 | } |
| 1092 | |
| 1093 | #[test] |
| 1094 | fn lease_is_expired_and_ttl() { |
| 1095 | let past = Lease { |
| 1096 | generation: 1, |
| 1097 | expires_at: SystemTime::now() - Duration::from_secs(60), |
| 1098 | owner: String::new(), |
| 1099 | e_tag: String::new(), |
| 1100 | }; |
| 1101 | assert!(past.is_expired()); |
| 1102 | assert!(past.ttl().is_none()); |
| 1103 | |
| 1104 | let future = Lease { |
| 1105 | generation: 1, |
| 1106 | expires_at: SystemTime::now() + Duration::from_secs(60), |
| 1107 | owner: String::new(), |
| 1108 | e_tag: String::new(), |
| 1109 | }; |
| 1110 | assert!(!future.is_expired()); |
| 1111 | let ttl = future.ttl().expect("future lease has positive ttl"); |
| 1112 | assert!(ttl <= Duration::from_secs(60) && ttl > Duration::from_secs(50)); |
| 1113 | } |
| 1114 | |
| 1115 | // ── LeaseExistsError Display (port of leaser.go:17-21) ───────────────────── |
| 1116 | |
| 1117 | #[test] |
| 1118 | fn lease_exists_error_display() { |
| 1119 | let t = SystemTime::UNIX_EPOCH + Duration::from_secs(1_609_459_200); |
| 1120 | let with_owner = LeaseExistsError { |
| 1121 | owner: "host-a:7".to_string(), |
| 1122 | expires_at: t, |
| 1123 | }; |
| 1124 | assert_eq!( |
| 1125 | with_owner.to_string(), |
| 1126 | "lease already held by host-a:7 until 2021-01-01T00:00:00Z" |
| 1127 | ); |
| 1128 | let no_owner = LeaseExistsError { |
| 1129 | owner: String::new(), |
| 1130 | expires_at: t, |
| 1131 | }; |
| 1132 | assert_eq!( |
| 1133 | no_owner.to_string(), |
| 1134 | "lease already held until 2021-01-01T00:00:00Z" |
| 1135 | ); |
| 1136 | } |
| 1137 | |
| 1138 | // ── lockKey (port of TestLeaser_LockKey, leaser_test.go:536-569) ─────────── |
| 1139 | |
| 1140 | #[test] |
| 1141 | fn lock_key_table() { |
| 1142 | let cases = [ |
| 1143 | ("", "lock.json"), |
| 1144 | ("replica", "replica/lock.json"), |
| 1145 | ("my/db/replica", "my/db/replica/lock.json"), |
| 1146 | ]; |
| 1147 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1148 | for (path, want) in cases { |
| 1149 | let leaser = S3Leaser::new(store.clone()).with_path(path); |
| 1150 | assert_eq!(leaser.lock_key().as_ref(), want, "path={path:?}"); |
| 1151 | } |
| 1152 | } |
| 1153 | |
| 1154 | // ── Type (port of TestLeaser_Type, leaser_test.go:571-577) ───────────────── |
| 1155 | |
| 1156 | #[test] |
| 1157 | fn leaser_type_is_s3() { |
| 1158 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1159 | let leaser = S3Leaser::new(store); |
| 1160 | assert_eq!(leaser.leaser_type(), "s3"); |
| 1161 | } |
| 1162 | |
| 1163 | // ── Acquire (ports of the four AcquireLease tests) ───────────────────────── |
| 1164 | |
| 1165 | /// Helper: read the lock object's stored lease (panics if absent). |
| 1166 | async fn stored_lease(store: &Arc<dyn ObjectStore>, key: &str) -> Lease { |
| 1167 | let r = store |
| 1168 | .get(&object_store::path::Path::from(key)) |
| 1169 | .await |
| 1170 | .expect("lock object present"); |
| 1171 | let bytes = r.bytes().await.unwrap(); |
| 1172 | serde_json::from_slice(&bytes).unwrap() |
| 1173 | } |
| 1174 | |
| 1175 | /// Port of TestLeaser_AcquireLease_NewLease (leaser_test.go:19-76): first |
| 1176 | /// acquire writes generation=1 via Create (If-None-Match:*) and returns a TTL |
| 1177 | /// close to the configured value. |
| 1178 | #[tokio::test] |
| 1179 | async fn acquire_new_lease() { |
| 1180 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1181 | let leaser = S3Leaser::new(store.clone()) |
| 1182 | .with_owner("me") |
| 1183 | .with_ttl(Duration::from_secs(10)); |
| 1184 | |
| 1185 | let lease = leaser.acquire_lease().await.expect("acquire"); |
| 1186 | assert_eq!(lease.generation, 1); |
| 1187 | assert!(!lease.e_tag.is_empty(), "ETag returned from PUT"); |
| 1188 | assert_eq!(lease.owner, "me"); |
| 1189 | let ttl = lease.ttl().expect("positive ttl"); |
| 1190 | assert!( |
| 1191 | ttl > Duration::from_secs(9) && ttl <= Duration::from_secs(10), |
| 1192 | "ttl={ttl:?}" |
| 1193 | ); |
| 1194 | |
| 1195 | // The persisted lock object carries the same generation. |
| 1196 | let persisted = stored_lease(&store, "lock.json").await; |
| 1197 | assert_eq!(persisted.generation, 1); |
| 1198 | assert_eq!(persisted.owner, "me"); |
| 1199 | } |
| 1200 | |
| 1201 | /// Port of TestLeaser_AcquireLease_ExpiredLease (leaser_test.go:78-122): an |
| 1202 | /// expired lease (gen 5) is taken over via Update (If-Match:<old-etag>) with |
| 1203 | /// generation incremented to 6. |
| 1204 | #[tokio::test] |
| 1205 | async fn acquire_over_expired_lease() { |
| 1206 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1207 | let key = object_store::path::Path::from("lock.json"); |
| 1208 | |
| 1209 | // Seed an expired lease (no CAS, just place it). |
| 1210 | let expired = Lease { |
| 1211 | generation: 5, |
| 1212 | expires_at: SystemTime::now() - Duration::from_secs(3600), |
| 1213 | owner: "previous-owner".to_string(), |
| 1214 | e_tag: String::new(), |
| 1215 | }; |
| 1216 | store |
| 1217 | .put(&key, serde_json::to_vec(&expired).unwrap().into()) |
| 1218 | .await |
| 1219 | .unwrap(); |
| 1220 | |
| 1221 | let leaser = S3Leaser::new(store.clone()) |
| 1222 | .with_owner("me") |
| 1223 | .with_ttl(Duration::from_secs(30)); |
| 1224 | let lease = leaser.acquire_lease().await.expect("acquire over expired"); |
| 1225 | assert_eq!(lease.generation, 6, "previous generation + 1"); |
| 1226 | assert_eq!(lease.owner, "me"); |
| 1227 | assert!(!lease.is_expired()); |
| 1228 | |
| 1229 | let persisted = stored_lease(&store, "lock.json").await; |
| 1230 | assert_eq!(persisted.generation, 6); |
| 1231 | } |
| 1232 | |
| 1233 | /// Port of TestLeaser_AcquireLease_ActiveLease (leaser_test.go:124-165): an |
| 1234 | /// active (unexpired) lease blocks acquisition with a LeaseExistsError that |
| 1235 | /// carries the holder's owner and a future ExpiresAt; no PUT occurs. |
| 1236 | #[tokio::test] |
| 1237 | async fn acquire_blocked_by_active_lease() { |
| 1238 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1239 | let key = object_store::path::Path::from("lock.json"); |
| 1240 | |
| 1241 | let active = Lease { |
| 1242 | generation: 3, |
| 1243 | expires_at: SystemTime::now() + Duration::from_secs(300), |
| 1244 | owner: "active-owner".to_string(), |
| 1245 | e_tag: String::new(), |
| 1246 | }; |
| 1247 | store |
| 1248 | .put(&key, serde_json::to_vec(&active).unwrap().into()) |
| 1249 | .await |
| 1250 | .unwrap(); |
| 1251 | // Capture the current ETag so we can assert the object was NOT rewritten. |
| 1252 | let etag_before = store.head(&key).await.unwrap().e_tag; |
| 1253 | |
| 1254 | let leaser = S3Leaser::new(store.clone()).with_owner("me"); |
| 1255 | let err = leaser |
| 1256 | .acquire_lease() |
| 1257 | .await |
| 1258 | .expect_err("active lease blocks"); |
| 1259 | let le = err.as_lease_exists().expect("LeaseExistsError"); |
| 1260 | assert_eq!(le.owner, "active-owner"); |
| 1261 | assert!(le.expires_at > SystemTime::now(), "future ExpiresAt"); |
| 1262 | |
| 1263 | // No PUT should have happened (ETag unchanged). |
| 1264 | let etag_after = store.head(&key).await.unwrap().e_tag; |
| 1265 | assert_eq!( |
| 1266 | etag_before, etag_after, |
| 1267 | "active lease must not be rewritten" |
| 1268 | ); |
| 1269 | } |
| 1270 | |
| 1271 | /// Port of TestLeaser_AcquireLease_RaceCondition412 (leaser_test.go:167-211): |
| 1272 | /// a losing CAS (the lock object already holds another, unexpired lease) must |
| 1273 | /// re-read to surface the winner's identity in the LeaseExistsError, never a |
| 1274 | /// blank one. The deterministic in-process analogue of the 412-then-reread |
| 1275 | /// branch; the live N-way race is `two_contenders_exactly_one_primary`. |
| 1276 | #[tokio::test] |
| 1277 | async fn acquire_race_condition_reread_returns_winner() { |
| 1278 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1279 | let key = object_store::path::Path::from("lock.json"); |
| 1280 | |
| 1281 | let winner = Lease { |
| 1282 | generation: 1, |
| 1283 | expires_at: SystemTime::now() + Duration::from_secs(30), |
| 1284 | owner: "race-winner".to_string(), |
| 1285 | e_tag: String::new(), |
| 1286 | }; |
| 1287 | store |
| 1288 | .put(&key, serde_json::to_vec(&winner).unwrap().into()) |
| 1289 | .await |
| 1290 | .unwrap(); |
| 1291 | |
| 1292 | let leaser = S3Leaser::new(store.clone()).with_owner("loser"); |
| 1293 | let err = leaser.acquire_lease().await.expect_err("loser blocked"); |
| 1294 | let le = err.as_lease_exists().expect("LeaseExistsError"); |
| 1295 | assert_eq!(le.owner, "race-winner"); |
| 1296 | assert!( |
| 1297 | le.expires_at > SystemTime::now(), |
| 1298 | "non-zero future ExpiresAt" |
| 1299 | ); |
| 1300 | } |
| 1301 | |
| 1302 | /// REVIEWER (T15 divergence): a lock file written by the real Litestream Go |
| 1303 | /// binary on a node whose LOCAL timezone is not UTC must be readable. |
| 1304 | /// |
| 1305 | /// Go sets `Lease.ExpiresAt = time.Now().Add(TTL)` (s3/leaser.go:110,148) with |
| 1306 | /// **no** `.UTC()` normalisation, and the default `time.Time` JSON marshaller |
| 1307 | /// (`appendStrictRFC3339`, used by `MarshalJSON`) emits the value in the local |
| 1308 | /// timezone — i.e. with a numeric offset such as `-04:00` / `+05:30`, NOT a |
| 1309 | /// `Z` suffix — whenever the host offset is non-zero. The bytes below are the |
| 1310 | /// verbatim output of `json.Marshal` on a `litestream.Lease` in |
| 1311 | /// `America/New_York` (empirically reproduced with the Go toolchain). |
| 1312 | /// |
| 1313 | /// rustyriver's `rfc3339::parse` only accepts a `Z` suffix |
| 1314 | /// (`s.strip_suffix('Z')?`), so `read_lease` fails to decode this object and |
| 1315 | /// `acquire_lease` returns a "decode lock file" error instead of the |
| 1316 | /// Go-faithful `LeaseExistsError`. A rustyriver node therefore cannot fence |
| 1317 | /// against — or take over from — a real Litestream deployment (or a rustyriver |
| 1318 | /// instance reading a lock seeded by one) running on any non-UTC host. |
| 1319 | /// |
| 1320 | /// Expected (Go-faithful) behaviour: acquisition is blocked by the live lease |
| 1321 | /// and a `LeaseExistsError` carrying the holder's owner is returned. |
| 1322 | #[tokio::test] |
| 1323 | async fn acquire_reads_go_lock_written_in_non_utc_timezone() { |
| 1324 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1325 | let key = object_store::path::Path::from("lock.json"); |
| 1326 | |
| 1327 | // Byte-for-byte `json.Marshal(litestream.Lease{...})` output from a Go |
| 1328 | // node in America/New_York. The year is far in the future so the lease is |
| 1329 | // unambiguously active regardless of the parsed offset. |
| 1330 | let go_lock_json = |
| 1331 | br#"{"generation":4,"expires_at":"2999-05-30T12:34:56.789-04:00","owner":"go-host:42"}"#; |
| 1332 | store.put(&key, go_lock_json.to_vec().into()).await.unwrap(); |
| 1333 | |
| 1334 | let leaser = S3Leaser::new(store.clone()).with_owner("rusty"); |
| 1335 | let err = leaser |
| 1336 | .acquire_lease() |
| 1337 | .await |
| 1338 | .expect_err("a live remote lease must block acquisition"); |
| 1339 | |
| 1340 | // Go would surface the holder via LeaseExistsError; rustyriver must too. |
| 1341 | let le = err.as_lease_exists().unwrap_or_else(|| { |
| 1342 | panic!( |
| 1343 | "expected LeaseExistsError for the live Go-written lock, got {err:?} \ |
| 1344 | (the non-UTC offset timestamp failed to parse)" |
| 1345 | ) |
| 1346 | }); |
| 1347 | assert_eq!(le.owner, "go-host:42"); |
| 1348 | assert!(le.expires_at > SystemTime::now(), "future ExpiresAt"); |
| 1349 | } |
| 1350 | |
| 1351 | // ── Renew (ports of the RenewLease tests) ────────────────────────────────── |
| 1352 | |
| 1353 | /// Port of TestLeaser_RenewLease (leaser_test.go:213-268): renewal keeps the |
| 1354 | /// generation, extends the TTL, and forwards If-Match:<old-etag>. |
| 1355 | #[tokio::test] |
| 1356 | async fn renew_lease_extends_ttl_keeps_generation() { |
| 1357 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1358 | let leaser = S3Leaser::new(store.clone()) |
| 1359 | .with_owner("me") |
| 1360 | .with_ttl(Duration::from_secs(30)); |
| 1361 | |
| 1362 | // Acquire first to get a real ETag for the lock object. |
| 1363 | let lease = leaser.acquire_lease().await.expect("acquire"); |
| 1364 | let old_etag = lease.e_tag.clone(); |
| 1365 | assert_eq!(lease.generation, 1); |
| 1366 | |
| 1367 | let renewed = leaser.renew_lease(&lease).await.expect("renew"); |
| 1368 | assert_eq!(renewed.generation, 1, "generation unchanged on renew"); |
| 1369 | assert_ne!(renewed.e_tag, old_etag, "new ETag after rewrite"); |
| 1370 | let ttl = renewed.ttl().expect("positive ttl"); |
| 1371 | assert!(ttl > Duration::from_secs(29), "ttl≈30s, got {ttl:?}"); |
| 1372 | } |
| 1373 | |
| 1374 | /// Port of TestLeaser_RenewLease_LostLease (leaser_test.go:270-292): a stale |
| 1375 | /// ETag → the CAS Update loses → LeaseNotHeld. |
| 1376 | #[tokio::test] |
| 1377 | async fn renew_lease_lost_returns_not_held() { |
| 1378 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1379 | let leaser = S3Leaser::new(store.clone()).with_owner("me"); |
| 1380 | let mut lease = leaser.acquire_lease().await.expect("acquire"); |
| 1381 | // Corrupt the ETag so the If-Match Update fails. |
| 1382 | lease.e_tag = "\"stale-etag\"".to_string(); |
| 1383 | |
| 1384 | let err = leaser |
| 1385 | .renew_lease(&lease) |
| 1386 | .await |
| 1387 | .expect_err("renew should fail"); |
| 1388 | assert!( |
| 1389 | err.is_lease_not_held(), |
| 1390 | "expected LeaseNotHeld, got {err:?}" |
| 1391 | ); |
| 1392 | } |
| 1393 | |
| 1394 | /// Port of TestLeaser_RenewLease_EmptyETag (leaser_test.go:309-328): an empty |
| 1395 | /// ETag is rejected before any I/O. |
| 1396 | #[tokio::test] |
| 1397 | async fn renew_lease_empty_etag_rejected() { |
| 1398 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1399 | let leaser = S3Leaser::new(store).with_owner("me"); |
| 1400 | let lease = Lease { |
| 1401 | generation: 5, |
| 1402 | expires_at: SystemTime::now() + Duration::from_secs(5), |
| 1403 | owner: "me".to_string(), |
| 1404 | e_tag: String::new(), |
| 1405 | }; |
| 1406 | let err = leaser |
| 1407 | .renew_lease(&lease) |
| 1408 | .await |
| 1409 | .expect_err("empty etag rejected"); |
| 1410 | assert!(err.is_lease_etag_required(), "got {err:?}"); |
| 1411 | } |
| 1412 | |
| 1413 | // ── Release (ports of the ReleaseLease tests) ────────────────────────────── |
| 1414 | |
| 1415 | /// Port of TestLeaser_ReleaseLease (leaser_test.go:330-364): a matching ETag |
| 1416 | /// deletes the lock object. |
| 1417 | #[tokio::test] |
| 1418 | async fn release_lease_deletes_object() { |
| 1419 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1420 | let key = object_store::path::Path::from("lock.json"); |
| 1421 | let leaser = S3Leaser::new(store.clone()).with_owner("me"); |
| 1422 | |
| 1423 | let lease = leaser.acquire_lease().await.expect("acquire"); |
| 1424 | assert!(store.head(&key).await.is_ok(), "lock exists after acquire"); |
| 1425 | |
| 1426 | leaser.release_lease(&lease).await.expect("release"); |
| 1427 | let err = store |
| 1428 | .head(&key) |
| 1429 | .await |
| 1430 | .expect_err("lock removed after release"); |
| 1431 | assert!(matches!(err, object_store::Error::NotFound { .. })); |
| 1432 | } |
| 1433 | |
| 1434 | /// Port of TestLeaser_ReleaseLease_StaleETag (leaser_test.go:366-388): a stale |
| 1435 | /// ETag → LeaseNotHeld, and the object is left intact. |
| 1436 | #[tokio::test] |
| 1437 | async fn release_lease_stale_etag_not_held() { |
| 1438 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1439 | let key = object_store::path::Path::from("lock.json"); |
| 1440 | let leaser = S3Leaser::new(store.clone()).with_owner("me"); |
| 1441 | |
| 1442 | let mut lease = leaser.acquire_lease().await.expect("acquire"); |
| 1443 | lease.e_tag = "\"stale-etag\"".to_string(); |
| 1444 | |
| 1445 | let err = leaser |
| 1446 | .release_lease(&lease) |
| 1447 | .await |
| 1448 | .expect_err("stale release fails"); |
| 1449 | assert!(err.is_lease_not_held(), "got {err:?}"); |
| 1450 | assert!(store.head(&key).await.is_ok(), "lock object must survive"); |
| 1451 | } |
| 1452 | |
| 1453 | /// Port of TestLeaser_ReleaseLease_AlreadyDeleted (leaser_test.go:390-412): the |
| 1454 | /// object is already gone → LeaseAlreadyReleased. |
| 1455 | #[tokio::test] |
| 1456 | async fn release_lease_already_deleted() { |
| 1457 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1458 | let leaser = S3Leaser::new(store.clone()).with_owner("me"); |
| 1459 | let lease = Lease { |
| 1460 | generation: 5, |
| 1461 | expires_at: SystemTime::now() + Duration::from_secs(300), |
| 1462 | owner: "me".to_string(), |
| 1463 | e_tag: "\"my-etag\"".to_string(), |
| 1464 | }; |
| 1465 | // No lock object exists. |
| 1466 | let err = leaser |
| 1467 | .release_lease(&lease) |
| 1468 | .await |
| 1469 | .expect_err("already released"); |
| 1470 | assert!(err.is_lease_already_released(), "got {err:?}"); |
| 1471 | } |
| 1472 | |
| 1473 | /// Port of TestLeaser_ReleaseLease_EmptyETag (leaser_test.go:429-448): an empty |
| 1474 | /// ETag is rejected before any I/O. |
| 1475 | #[tokio::test] |
| 1476 | async fn release_lease_empty_etag_rejected() { |
| 1477 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1478 | let leaser = S3Leaser::new(store).with_owner("me"); |
| 1479 | let lease = Lease { |
| 1480 | generation: 5, |
| 1481 | expires_at: SystemTime::now() + Duration::from_secs(300), |
| 1482 | owner: "me".to_string(), |
| 1483 | e_tag: String::new(), |
| 1484 | }; |
| 1485 | let err = leaser |
| 1486 | .release_lease(&lease) |
| 1487 | .await |
| 1488 | .expect_err("empty etag rejected"); |
| 1489 | assert!(err.is_lease_etag_required(), "got {err:?}"); |
| 1490 | } |
| 1491 | |
| 1492 | // ── Concurrency: two/many contenders → exactly one primary ───────────────── |
| 1493 | |
| 1494 | /// Port of TestLeaser_ConcurrentAcquisition (leaser_test.go:450-534): N tasks |
| 1495 | /// race to acquire against one real (in-memory) store; the CAS Create must let |
| 1496 | /// **exactly one** win and the other N-1 see LeaseExistsError. |
| 1497 | /// |
| 1498 | /// This is also the PLAN.md T15 "two contenders → exactly one primary" gate, |
| 1499 | /// run here against `object_store::InMemory` (a faithful CAS store) so it needs |
| 1500 | /// no MinIO; the MinIO mirror is the auto-skipping integration test. |
| 1501 | #[tokio::test] |
| 1502 | async fn two_contenders_exactly_one_primary() { |
| 1503 | const NUM: usize = 10; |
| 1504 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1505 | |
| 1506 | let mut handles = Vec::with_capacity(NUM); |
| 1507 | for i in 0..NUM { |
| 1508 | let store = store.clone(); |
| 1509 | handles.push(tokio::spawn(async move { |
| 1510 | let leaser = S3Leaser::new(store).with_owner(format!("node-{i}")); |
| 1511 | leaser.acquire_lease().await |
| 1512 | })); |
| 1513 | } |
| 1514 | |
| 1515 | let mut success = 0usize; |
| 1516 | let mut failure = 0usize; |
| 1517 | let mut winner_owner = None; |
| 1518 | for h in handles { |
| 1519 | match h.await.expect("task join") { |
| 1520 | Ok(lease) => { |
| 1521 | success += 1; |
| 1522 | winner_owner = Some(lease.owner); |
| 1523 | } |
| 1524 | Err(e) => { |
| 1525 | failure += 1; |
| 1526 | assert!( |
| 1527 | e.as_lease_exists().is_some(), |
| 1528 | "losers must get LeaseExistsError, got {e:?}" |
| 1529 | ); |
| 1530 | } |
| 1531 | } |
| 1532 | } |
| 1533 | assert_eq!(success, 1, "exactly one acquirer wins"); |
| 1534 | assert_eq!(failure, NUM - 1, "the rest stand by"); |
| 1535 | assert!(winner_owner.is_some()); |
| 1536 | } |
| 1537 | |
| 1538 | /// Expiry → failover: once the primary's lease has expired, a standby contender |
| 1539 | /// can take over (generation increments), and the previous holder can no longer |
| 1540 | /// renew (its ETag is now stale → LeaseNotHeld). This is the PLAN.md T15 |
| 1541 | /// "expiry → failover" gate, exercised against a real CAS store with a tiny TTL. |
| 1542 | #[tokio::test] |
| 1543 | async fn expiry_failover_standby_takes_over() { |
| 1544 | let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); |
| 1545 | |
| 1546 | // Primary acquires with a 1 ms TTL so the lease expires almost immediately. |
| 1547 | let primary = S3Leaser::new(store.clone()) |
| 1548 | .with_owner("primary") |
| 1549 | .with_ttl(Duration::from_millis(1)); |
| 1550 | let primary_lease = primary.acquire_lease().await.expect("primary acquires"); |
| 1551 | assert_eq!(primary_lease.generation, 1); |
| 1552 | |
| 1553 | // A standby will take over once the lease lapses. |
| 1554 | let standby = S3Leaser::new(store.clone()) |
| 1555 | .with_owner("standby") |
| 1556 | .with_ttl(Duration::from_secs(30)); |
| 1557 | |
| 1558 | // Wait until the primary's lease is observably expired. |
| 1559 | while !primary_lease.is_expired() { |
| 1560 | tokio::time::sleep(Duration::from_millis(1)).await; |
| 1561 | } |
| 1562 | |
| 1563 | // Once expired, the standby takes over with generation+1. |
| 1564 | let standby_lease = standby |
| 1565 | .acquire_lease() |
| 1566 | .await |
| 1567 | .expect("standby fails over after expiry"); |
| 1568 | assert_eq!( |
| 1569 | standby_lease.generation, 2, |
| 1570 | "failover increments generation" |
| 1571 | ); |
| 1572 | assert_eq!(standby_lease.owner, "standby"); |
| 1573 | |
| 1574 | // The deposed primary can no longer renew: its ETag is stale now. |
| 1575 | let err = primary |
| 1576 | .renew_lease(&primary_lease) |
| 1577 | .await |
| 1578 | .expect_err("deposed primary cannot renew"); |
| 1579 | assert!(err.is_lease_not_held(), "got {err:?}"); |
| 1580 | } |
| 1581 | |
| 1582 | // ── HeartbeatClient (heartbeat.go behaviour) ─────────────────────────────── |
| 1583 | |
| 1584 | /// The constructor clamps the interval up to MIN_HEARTBEAT_INTERVAL |
| 1585 | /// (heartbeat.go:29-31) and leaves a larger interval untouched. |
| 1586 | #[test] |
| 1587 | fn heartbeat_interval_clamped_to_minimum() { |
| 1588 | let c = HeartbeatClient::new("http://x/ping", Duration::from_secs(1)); |
| 1589 | assert_eq!(c.interval(), MIN_HEARTBEAT_INTERVAL); |
| 1590 | |
| 1591 | let big = HeartbeatClient::new("http://x/ping", Duration::from_secs(600)); |
| 1592 | assert_eq!(big.interval(), Duration::from_secs(600)); |
| 1593 | |
| 1594 | assert_eq!(c.timeout(), DEFAULT_HEARTBEAT_TIMEOUT); |
| 1595 | } |
| 1596 | |
| 1597 | /// `should_ping` is true before the first ping and false immediately after a |
| 1598 | /// recorded ping (heartbeat.go:68-72, 80-84). |
| 1599 | #[test] |
| 1600 | fn heartbeat_should_ping_throttle() { |
| 1601 | let c = HeartbeatClient::new("http://x/ping", Duration::from_secs(600)); |
| 1602 | assert!(c.should_ping(), "no prior ping → should ping"); |
| 1603 | assert!(c.last_ping_at().is_none()); |
| 1604 | |
| 1605 | c.record_ping(); |
| 1606 | assert!(c.last_ping_at().is_some()); |
| 1607 | assert!( |
| 1608 | !c.should_ping(), |
| 1609 | "just pinged with a 10-min interval → wait" |
| 1610 | ); |
| 1611 | } |
| 1612 | |
| 1613 | /// An empty URL makes `ping` a no-op success on all feature configurations |
| 1614 | /// (heartbeat.go:46-48). |
| 1615 | #[tokio::test] |
| 1616 | async fn heartbeat_empty_url_is_noop() { |
| 1617 | let c = HeartbeatClient::new("", Duration::from_secs(600)); |
| 1618 | c.ping().await.expect("empty-url ping is a no-op success"); |
| 1619 | } |
| 1620 | |
| 1621 | /// A successful 2xx HTTP GET satisfies `ping`; a non-2xx is an error. Exercises |
| 1622 | /// the real reqwest path against a local one-shot TCP server (only under `s3`, |
| 1623 | /// where reqwest is available). |
| 1624 | #[cfg(feature = "s3")] |
| 1625 | #[tokio::test] |
| 1626 | async fn heartbeat_ping_http_status_handling() { |
| 1627 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 1628 | use tokio::net::TcpListener; |
| 1629 | |
| 1630 | // Spin up a trivial HTTP server that replies with a fixed status line. |
| 1631 | async fn serve_once(status_line: &'static str) -> String { |
| 1632 | let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 1633 | let addr = listener.local_addr().unwrap(); |
| 1634 | tokio::spawn(async move { |
| 1635 | if let Ok((mut sock, _)) = listener.accept().await { |
| 1636 | // Drain the request (best-effort; ignore the bytes). |
| 1637 | let mut buf = [0u8; 1024]; |
| 1638 | let _ = sock.read(&mut buf).await; |
| 1639 | let body = "ok"; |
| 1640 | let resp = format!( |
| 1641 | "{status_line}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", |
| 1642 | body.len() |
| 1643 | ); |
| 1644 | let _ = sock.write_all(resp.as_bytes()).await; |
| 1645 | let _ = sock.shutdown().await; |
| 1646 | } |
| 1647 | }); |
| 1648 | format!("http://{addr}/ping") |
| 1649 | } |
| 1650 | |
| 1651 | // 200 OK → ping succeeds. |
| 1652 | let url_ok = serve_once("HTTP/1.1 200 OK").await; |
| 1653 | let c_ok = HeartbeatClient::new(url_ok, Duration::from_secs(600)); |
| 1654 | c_ok.ping().await.expect("200 → ok"); |
| 1655 | |
| 1656 | // 500 → ping errors. |
| 1657 | let url_err = serve_once("HTTP/1.1 500 Internal Server Error").await; |
| 1658 | let c_err = HeartbeatClient::new(url_err, Duration::from_secs(600)); |
| 1659 | let err = c_err.ping().await.expect_err("500 → error"); |
| 1660 | assert!( |
| 1661 | err.to_string().contains("unexpected status code: 500"), |
| 1662 | "got {err}" |
| 1663 | ); |
| 1664 | } |
| 1665 | } |