Skip to main content

ojak_postgres/
kv.rs

1//! The key-value store, in a table of its own.
2//!
3//! Entries live in one table, `ojak_kv` unless named otherwise, created by
4//! [`PostgresKvStore::initialize`] if it is not there. A key is stored as the
5//! JSON array of its segments, so that no two keys share a row whatever
6//! their segments hold, and a value as JSON text rather than `jsonb`, which
7//! refuses a string with NUL in it; a cached document is whatever a peer
8//! sent. An expired entry is ignored until [`PostgresKvStore::prune_expired`]
9//! removes it.
10
11use crate::table_name;
12use ojak::kv::{KvError, KvStore};
13use serde_json::Value;
14use sqlx::PgPool;
15use std::time::Duration;
16
17/// A [`KvStore`] in a PostgreSQL table.
18#[derive(Clone, Debug)]
19pub struct PostgresKvStore {
20    pool: PgPool,
21    table: String,
22}
23
24impl PostgresKvStore {
25    /// A store in the table `ojak_kv`.
26    #[must_use]
27    pub fn new(pool: PgPool) -> Self {
28        Self {
29            pool,
30            table: "ojak_kv".to_owned(),
31        }
32    }
33
34    /// A store in the table `table`, which may be prefixed by its schema.
35    ///
36    /// # Errors
37    ///
38    /// When `table` is not a plain SQL identifier.
39    pub fn with_table(pool: PgPool, table: &str) -> Result<Self, KvError> {
40        Ok(Self {
41            pool,
42            table: table_name(table).map_err(KvError)?,
43        })
44    }
45
46    /// Create the table and its index if they do not exist. Safe to run from
47    /// every process at start-up.
48    ///
49    /// # Errors
50    ///
51    /// When the database refuses.
52    pub async fn initialize(&self) -> Result<(), KvError> {
53        for statement in Self::schema(&self.table) {
54            sqlx::query(crate::sql(statement))
55                .execute(&self.pool)
56                .await
57                .map_err(error)?;
58        }
59        Ok(())
60    }
61
62    /// The statements that create a store table named `table` and its
63    /// index, each safe to run again, for an application to put in a
64    /// migration of its own.
65    #[must_use]
66    pub fn schema(table: &str) -> Vec<String> {
67        let index = format!("{}_expires", table.replace('.', "_"));
68        vec![
69            format!(
70                "CREATE TABLE IF NOT EXISTS {table} (
71                    key TEXT PRIMARY KEY,
72                    value TEXT NOT NULL,
73                    expires_at TIMESTAMPTZ
74                )"
75            ),
76            format!(
77                "CREATE INDEX IF NOT EXISTS {index} ON {table} (expires_at) \
78                 WHERE expires_at IS NOT NULL"
79            ),
80        ]
81    }
82
83    /// Delete expired entries.
84    ///
85    /// # Errors
86    ///
87    /// When the database refuses.
88    pub async fn prune_expired(&self) -> Result<u64, KvError> {
89        let result = sqlx::query(crate::sql(format!(
90            "DELETE FROM {} WHERE expires_at <= now()",
91            self.table
92        )))
93        .execute(&self.pool)
94        .await
95        .map_err(error)?;
96        Ok(result.rows_affected())
97    }
98}
99
100fn error(error: sqlx::Error) -> KvError {
101    KvError(error.to_string())
102}
103
104fn encode_key(key: &[&str]) -> Result<String, KvError> {
105    serde_json::to_string(key).map_err(|error| KvError(error.to_string()))
106}
107
108fn encode_value(value: &Value) -> Result<String, KvError> {
109    serde_json::to_string(value).map_err(|error| KvError(error.to_string()))
110}
111
112fn seconds(ttl: Option<Duration>) -> Option<f64> {
113    ttl.map(|ttl| ttl.as_secs_f64())
114}
115
116/// The expiry column's value for a TTL in `$3`.
117const EXPIRES: &str = "CASE WHEN $3::float8 IS NULL THEN NULL \
118                       ELSE now() + make_interval(secs => $3::float8) END";
119
120impl KvStore for PostgresKvStore {
121    async fn get(&self, key: &[&str]) -> Result<Option<Value>, KvError> {
122        let value: Option<String> = sqlx::query_scalar(crate::sql(format!(
123            "SELECT value FROM {} WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())",
124            self.table
125        )))
126        .bind(encode_key(key)?)
127        .fetch_optional(&self.pool)
128        .await
129        .map_err(error)?;
130        value
131            .map(|value| serde_json::from_str(&value).map_err(|error| KvError(error.to_string())))
132            .transpose()
133    }
134
135    async fn set(&self, key: &[&str], value: Value, ttl: Option<Duration>) -> Result<(), KvError> {
136        sqlx::query(crate::sql(format!(
137            "INSERT INTO {} (key, value, expires_at) VALUES ($1, $2, {EXPIRES})
138             ON CONFLICT (key) DO UPDATE
139             SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at",
140            self.table
141        )))
142        .bind(encode_key(key)?)
143        .bind(encode_value(&value)?)
144        .bind(seconds(ttl))
145        .execute(&self.pool)
146        .await
147        .map_err(error)?;
148        Ok(())
149    }
150
151    async fn insert(
152        &self,
153        key: &[&str],
154        value: Value,
155        ttl: Option<Duration>,
156    ) -> Result<bool, KvError> {
157        // Of inserts racing on one key, one inserts; the others wait for it
158        // on the key's uniqueness, then find a live row and update nothing.
159        let table = &self.table;
160        let put: Option<i32> = sqlx::query_scalar(crate::sql(format!(
161            "INSERT INTO {table} (key, value, expires_at) VALUES ($1, $2, {EXPIRES})
162             ON CONFLICT (key) DO UPDATE
163             SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at
164             WHERE {table}.expires_at <= now()
165             RETURNING 1"
166        )))
167        .bind(encode_key(key)?)
168        .bind(encode_value(&value)?)
169        .bind(seconds(ttl))
170        .fetch_optional(&self.pool)
171        .await
172        .map_err(error)?;
173        Ok(put.is_some())
174    }
175
176    async fn delete(&self, key: &[&str]) -> Result<(), KvError> {
177        sqlx::query(crate::sql(format!(
178            "DELETE FROM {} WHERE key = $1",
179            self.table
180        )))
181        .bind(encode_key(key)?)
182        .execute(&self.pool)
183        .await
184        .map_err(error)?;
185        Ok(())
186    }
187}