Skip to main content

graphrt_core/
coordination.rs

1//! Versioned key-value objects for coordinating writers that share one store.
2//!
3//! A [`CoordinationStore`] keeps small values (JSON documents, markers) under
4//! slash-separated keys, each with a version number that changes on every
5//! write. The only ways to write are *create if absent* and *compare and
6//! swap*, which map onto what every backend can do atomically: a local
7//! transaction (SQLite), an OS lock (a directory), or a conditional PUT
8//! (`If-None-Match: *` / `If-Match` on S3 and R2, `x-goog-if-generation-match`
9//! on GCS).
10//!
11//! It is what a gateway uses for idempotency markers (webhook deliveries, cron
12//! fires: create-if-absent), leases and fencing (compare-and-swap), and
13//! anything else that must be decided exactly once across restarts.
14//!
15//! Keys are namespaced per deployment with [`deployment_key`], e.g.
16//! `d/<deployment>/runs/<run_id>`.
17
18use std::fmt;
19
20use futures::future::BoxFuture;
21
22use crate::store::{StoreError, StoreResult};
23
24/// Largest key, in bytes.
25pub const MAX_KEY_BYTES: usize = 512;
26/// Largest value, in bytes. Coordination objects stay well below the single-PUT
27/// limits of object stores (5 MiB), so no backend needs multipart uploads.
28pub const MAX_VALUE_BYTES: usize = 1024 * 1024;
29
30/// A stored value and its version. Versions start at 1 and increase by one per
31/// write of the key.
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct Versioned {
34    pub value: Vec<u8>,
35    pub version: u64,
36}
37
38/// Versioned objects written only with create-if-absent and compare-and-swap.
39///
40/// Implementations must make every write atomic: of two concurrent
41/// `create_if_absent` calls (or two `compare_and_swap` calls with the same
42/// expected version) on one key, exactly one succeeds. A successful write is
43/// visible to every later `get` and `list` (read-after-write). The
44/// `store-conformance` feature of this crate ships the test suite.
45pub trait CoordinationStore: Send + Sync + fmt::Debug {
46    /// Store `value` under `key` at version 1. Fails with [`StoreError::Conflict`]
47    /// when the key exists.
48    fn create_if_absent<'a>(&'a self, key: &'a str, value: Vec<u8>) -> BoxFuture<'a, StoreResult<u64>>;
49    /// Replace the value of `key` if it is at `expected_version`, and return the
50    /// new version. Fails with [`StoreError::Precondition`] when the version
51    /// moved, [`StoreError::NotFound`] when the key does not exist.
52    fn compare_and_swap<'a>(
53        &'a self,
54        key: &'a str,
55        expected_version: u64,
56        value: Vec<u8>,
57    ) -> BoxFuture<'a, StoreResult<u64>>;
58    /// The value of `key`, if any.
59    fn get_object<'a>(&'a self, key: &'a str) -> BoxFuture<'a, StoreResult<Option<Versioned>>>;
60    /// Every key starting with `prefix`, in ascending key order.
61    fn list_objects<'a>(&'a self, prefix: &'a str) -> BoxFuture<'a, StoreResult<Vec<(String, Versioned)>>>;
62    /// Delete `key` if it is at `expected_version`. Returns whether it existed;
63    /// fails with [`StoreError::Precondition`] when the version moved.
64    fn delete_object<'a>(&'a self, key: &'a str, expected_version: u64) -> BoxFuture<'a, StoreResult<bool>>;
65}
66
67/// Validate a coordination key: 1–[`MAX_KEY_BYTES`] bytes of `/`-separated
68/// segments of `[A-Za-z0-9_.:=-]`, none empty, `.` or `..`.
69///
70/// @throws StoreError::InvalidId - When the key breaks one of these rules.
71pub fn validate_key(key: &str) -> StoreResult<()> {
72    let segment_ok = |segment: &str| {
73        !segment.is_empty()
74            && segment != "."
75            && segment != ".."
76            && segment.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':' | '='))
77    };
78    if !key.is_empty() && key.len() <= MAX_KEY_BYTES && key.split('/').all(segment_ok) {
79        Ok(())
80    } else {
81        Err(StoreError::InvalidId(key.chars().take(64).collect()))
82    }
83}
84
85/// Validate a value size.
86///
87/// @throws StoreError::Conflict - When the value is larger than [`MAX_VALUE_BYTES`].
88pub fn validate_value(value: &[u8]) -> StoreResult<()> {
89    if value.len() <= MAX_VALUE_BYTES {
90        Ok(())
91    } else {
92        Err(StoreError::Conflict(format!("coordination value of {} bytes exceeds {MAX_VALUE_BYTES}", value.len())))
93    }
94}
95
96/// The key of object `id` of `kind` in `deployment`: `d/<deployment>/<kind>/<id>`.
97///
98/// @example
99/// assert_eq!(deployment_key("shop", "runs", "run-1"), "d/shop/runs/run-1");
100pub fn deployment_key(deployment: &str, kind: &str, id: &str) -> String {
101    format!("d/{deployment}/{kind}/{id}")
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn keys_are_validated() {
110        for good in ["d/shop/runs/run-1", "a", "d/x/cron/daily/2026-11-22T00:00:00Z", "k=v"] {
111            assert!(validate_key(good).is_ok(), "{good}");
112        }
113        let long = "x".repeat(MAX_KEY_BYTES + 1);
114        for bad in ["", "/a", "a/", "a//b", "a/../b", "./a", "a b", "a\\b", &long] {
115            assert!(validate_key(bad).is_err(), "{bad}");
116        }
117        assert_eq!(deployment_key("shop", "runs", "r1"), "d/shop/runs/r1");
118        assert!(validate_value(&vec![0; MAX_VALUE_BYTES]).is_ok());
119        assert!(validate_value(&vec![0; MAX_VALUE_BYTES + 1]).is_err());
120    }
121}