rullst-orm 12.3.0

Fast, un-opinionated, database-agnostic ORM and query builder for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#![cfg(all(
    feature = "redis",
    not(any(feature = "strict-postgres", feature = "strict-mysql"))
))]

use redis::AsyncCommands;
use rullst_orm::schema::{Blueprint, Schema};
use rullst_orm::{FromRow, Orm};

#[derive(Debug, Clone, FromRow, rullst_orm::Orm)]
#[orm(table = "query_cache_live_records")]
struct QueryCacheLiveRecord {
    pub id: i32,
    pub name: String,
}

#[derive(Debug, Clone, FromRow, rullst_orm::Orm)]
#[orm(table = "query_cache_live_secrets")]
struct QueryCacheLiveSecret {
    pub id: i32,
    pub name: String,
    pub cpf: rullst_orm::SecretString,
}

const LIVE_CPF: &str = "123.456.789-00";

#[tokio::test]
async fn redis_cache_is_live_bounded_and_never_replaces_transaction_state() {
    let Ok(redis_url) = std::env::var("RULLST_TEST_REDIS_URL") else {
        eprintln!("RULLST_TEST_REDIS_URL is unset; skipping the opt-in live Redis contract");
        return;
    };
    // This is the only test in this binary, so no other thread reads the
    // process-wide key variables while they are set.
    unsafe {
        std::env::set_var("RULLST_ENCRYPTION_KEY", "0123456789abcdef0123456789abcdef");
        std::env::set_var("RULLST_ENCRYPTION_KEY_ID", "live-cache-2026");
        std::env::remove_var("RULLST_ENCRYPTION_KEYRING");
    }
    let namespace = format!("query-cache-live-{}", rand::random::<u64>());
    let database_path =
        std::env::temp_dir().join(format!("rullst-query-cache-live-{}.db", std::process::id()));
    let _ = std::fs::remove_file(&database_path);
    let database_url = format!("sqlite:{}?mode=rwc", database_path.to_string_lossy());

    Orm::init(&database_url)
        .await
        .expect("initialize isolated SQLite ORM");
    Orm::init_redis_with_namespace(&redis_url, &namespace)
        .await
        .expect("initialize live Redis query cache");
    Schema::create("query_cache_live_records", |table: &mut Blueprint| {
        table.id();
        table.string("name").not_null();
    })
    .await
    .expect("create live cache table");
    sqlx::query("INSERT INTO query_cache_live_records (name) VALUES (?)")
        .bind("first")
        .execute(Orm::pool().expect("ORM should be initialized"))
        .await
        .expect("insert live cache fixture");

    let query = QueryCacheLiveRecord::query().where_id(1).limit(1);
    let cache_key = rullst_orm::query_cache::query_key(
        "query_cache_live_records",
        &query.to_sql(),
        &query.bindings,
    )
    .expect("derive namespaced cache key");
    assert!(cache_key.contains(&namespace));

    let first = query
        .clone()
        .remember(30)
        .first()
        .await
        .expect("populate live Redis cache")
        .expect("fixture should exist");
    assert_eq!(first.name, "first");

    let mut redis = Orm::redis_manager().expect("Redis manager should be initialized");
    let exists: bool = redis.exists(&cache_key).await.expect("inspect cache key");
    let ttl: i64 = redis.ttl(&cache_key).await.expect("inspect cache TTL");
    assert!(exists);
    assert!((1..=30).contains(&ttl));
    // The entry is indexed under its table for commit-time invalidation,
    // scored by its expiry time, and the index lives at least as long as the
    // entry.
    let index_key = index_of(&cache_key);
    let score: Option<f64> = redis
        .zscore(&index_key, &cache_key)
        .await
        .expect("inspect cache index");
    let index_ttl: i64 = redis.ttl(&index_key).await.expect("inspect index TTL");
    let expires_at_ms = server_time_ms(&mut redis).await + 30_000.0;
    let score = score.expect("the entry key should be indexed");
    assert!(
        score > expires_at_ms - 32_000.0 && score <= expires_at_ms,
        "index score {score} should be the entry expiry"
    );
    assert!(index_ttl >= ttl);

    sqlx::query("UPDATE query_cache_live_records SET name = ? WHERE id = ?")
        .bind("second")
        .bind(1_i32)
        .execute(Orm::pool().expect("ORM should be initialized"))
        .await
        .expect("update authoritative row");

    let cached = query
        .clone()
        .remember(30)
        .first()
        .await
        .expect("read populated cache")
        .expect("cached fixture should exist");
    assert_eq!(cached.name, "first");

    let mut explicit = Orm::begin_transaction()
        .await
        .expect("begin explicit transaction");
    let explicit_row = query
        .clone()
        .remember(30)
        .first_with_tx(&mut explicit)
        .await
        .expect("transactional query must bypass cache")
        .expect("authoritative fixture should exist");
    assert_eq!(explicit_row.name, "second");
    explicit.rollback().await.expect("roll back explicit read");

    let task_scoped_name = Orm::transaction(|_| {
        Box::pin(async move {
            let row = QueryCacheLiveRecord::query()
                .where_id(1)
                .remember(30)
                .first()
                .await?
                .ok_or_else(|| {
                    rullst_orm::Error::DatabaseError("live cache fixture disappeared".to_string())
                })?;
            Ok::<String, rullst_orm::Error>(row.name)
        })
    })
    .await
    .expect("task-scoped query must bypass cache");
    assert_eq!(task_scoped_name, "second");

    let _: () = redis
        .set(&cache_key, "{corrupt-json")
        .await
        .expect("install corrupt cache fixture");
    let recovered = query
        .remember(30)
        .first()
        .await
        .expect("corrupt cache must fall back to database")
        .expect("authoritative fixture should exist");
    assert_eq!(recovered.name, "second");
    let repaired: String = redis
        .get(&cache_key)
        .await
        .expect("read repaired cache entry");
    assert!(repaired.contains("second"));

    // Invalidation follows the table index instead of scanning the keyspace:
    // a key that merely matches the table's key pattern is left to its TTL.
    let unindexed_key = format!(
        "{}:{}",
        index_key.trim_end_matches(":index"),
        "0".repeat(64)
    );
    let _: () = redis
        .set_ex(&unindexed_key, "unindexed", 30)
        .await
        .expect("install unindexed key");
    let mut updated = recovered;
    updated.name = "third".to_string();
    updated
        .save()
        .await
        .expect("model save should commit before cache invalidation");
    let exists_after_commit: bool = redis
        .exists(&cache_key)
        .await
        .expect("inspect invalidated cache key");
    assert!(!exists_after_commit);
    assert!(
        !redis
            .exists::<_, bool>(&index_key)
            .await
            .expect("inspect emptied index")
    );
    assert!(
        redis
            .exists::<_, bool>(&unindexed_key)
            .await
            .expect("inspect unindexed key"),
        "a committed write must not scan for keys outside the table index"
    );
    let _: usize = redis
        .del(&unindexed_key)
        .await
        .expect("remove unindexed key");

    let repopulated = QueryCacheLiveRecord::query()
        .where_id(1)
        .limit(1)
        .remember(30)
        .first()
        .await
        .expect("repopulate cache after committed update")
        .expect("updated fixture should exist");
    assert_eq!(repopulated.name, "third");

    let rollback = Orm::transaction(|_| {
        Box::pin(async move {
            let mut model = QueryCacheLiveRecord::query()
                .where_id(1)
                .first()
                .await?
                .ok_or_else(|| {
                    rullst_orm::Error::DatabaseError("live cache fixture disappeared".to_string())
                })?;
            model.name = "rolled back fourth".to_string();
            model.save().await?;
            Err::<(), rullst_orm::Error>(rullst_orm::Error::Validation(
                "force cache invalidation rollback".to_string(),
            ))
        })
    })
    .await;
    assert!(rollback.is_err());
    let exists_after_rollback: bool = redis
        .exists(&cache_key)
        .await
        .expect("cache should survive rolled-back update");
    assert!(exists_after_rollback);
    let still_cached = QueryCacheLiveRecord::query()
        .where_id(1)
        .limit(1)
        .remember(30)
        .first()
        .await
        .expect("read cache after rollback")
        .expect("cached fixture should exist");
    assert_eq!(still_cached.name, "third");

    let _: usize = redis
        .del(&cache_key)
        .await
        .expect("remove isolated live cache key");
    exercise_secret_string_cache(&mut redis).await;
    exercise_expired_index_members(&mut redis).await;
    let _ = std::fs::remove_file(database_path);
}

/// Cached `SecretString` values are ciphertext in Redis and still decrypt to
/// the real value on a cache hit.
async fn exercise_secret_string_cache(redis: &mut rullst_orm::_redis::aio::ConnectionManager) {
    Schema::create("query_cache_live_secrets", |table: &mut Blueprint| {
        table.id();
        table.string("name").not_null();
        table.string("cpf").not_null();
    })
    .await
    .expect("create live secret cache table");
    let mut secret = QueryCacheLiveSecret {
        id: 0,
        name: "cached".to_string(),
        cpf: rullst_orm::SecretString::new(LIVE_CPF),
    };
    secret
        .save()
        .await
        .expect("insert encrypted secret fixture");

    let query = QueryCacheLiveSecret::query().where_id(secret.id).limit(1);
    let cache_key = rullst_orm::query_cache::query_key(
        "query_cache_live_secrets",
        &query.to_sql(),
        &query.bindings,
    )
    .expect("derive secret cache key");
    let first = query
        .clone()
        .remember(30)
        .first()
        .await
        .expect("populate secret cache")
        .expect("secret fixture should exist");
    assert_eq!(first.cpf.reveal_audited(), LIVE_CPF);

    let raw: String = redis.get(&cache_key).await.expect("read raw secret cache");
    assert!(!raw.contains(LIVE_CPF), "cache holds plaintext: {raw}");
    assert!(raw.contains("RULLST:v2:live-cache-2026:"));

    sqlx::query("UPDATE query_cache_live_secrets SET name = ? WHERE id = ?")
        .bind("database changed")
        .bind(secret.id)
        .execute(Orm::pool().expect("ORM should be initialized"))
        .await
        .expect("change authoritative secret row");
    let cached = query
        .remember(30)
        .first()
        .await
        .expect("read secret cache")
        .expect("cached secret should exist");
    assert_eq!(
        cached.name, "cached",
        "the second read must come from Redis"
    );
    assert_eq!(cached.cpf.reveal_audited(), LIVE_CPF);
    let _: usize = redis
        .del(&cache_key)
        .await
        .expect("remove isolated secret cache key");
}

fn index_of(cache_key: &str) -> String {
    format!(
        "{}:index",
        cache_key.rsplit_once(':').expect("generated entry key").0
    )
}

async fn server_time_ms(redis: &mut rullst_orm::_redis::aio::ConnectionManager) -> f64 {
    let (seconds, micros): (u64, u64) = rullst_orm::_redis::cmd("TIME")
        .query_async(redis)
        .await
        .expect("read Redis server time");
    (seconds * 1_000 + micros / 1_000) as f64
}

/// Index members of entries that already expired are pruned when the next
/// entry is stored and never count toward the per-write invalidation cap, so
/// steady reads of many distinct queries cannot grow the index or make the
/// next write fail with `PostCommit`.
async fn exercise_expired_index_members(redis: &mut rullst_orm::_redis::aio::ConnectionManager) {
    let live_query = QueryCacheLiveRecord::query().where_id(1).limit(1);
    let live_key = rullst_orm::query_cache::query_key(
        "query_cache_live_records",
        &live_query.to_sql(),
        &live_query.bindings,
    )
    .expect("derive live cache key");
    let index_key = index_of(&live_key);
    let prefix = index_key.trim_end_matches(":index").to_string();
    let expired = |round: u32| -> Vec<(f64, String)> {
        (0..10_001_u32)
            .map(|member| {
                (
                    1.0,
                    format!(
                        "{prefix}:{:064x}",
                        u64::from(round) << 32 | u64::from(member)
                    ),
                )
            })
            .collect()
    };

    for chunk in expired(1).chunks(1_000) {
        let _: usize = redis
            .zadd_multiple(&index_key, chunk)
            .await
            .expect("index members of expired entries");
    }
    live_query
        .clone()
        .remember(30)
        .first()
        .await
        .expect("store a live entry")
        .expect("fixture should exist");
    let stale: usize = redis
        .zcount(&index_key, 0, 2)
        .await
        .expect("count expired index members");
    assert_eq!(stale, 0, "storing an entry prunes expired index members");
    assert!(
        redis
            .zscore::<_, _, Option<f64>>(&index_key, &live_key)
            .await
            .unwrap()
            .is_some()
    );

    for chunk in expired(2).chunks(1_000) {
        let _: usize = redis
            .zadd_multiple(&index_key, chunk)
            .await
            .expect("index members of expired entries");
    }
    let mut row = QueryCacheLiveRecord::find(1)
        .await
        .expect("load fixture")
        .expect("fixture should exist");
    row.name = "after expired members".to_string();
    row.save()
        .await
        .expect("expired index members must not count toward the invalidation cap");
    assert!(!redis.exists::<_, bool>(&live_key).await.unwrap());
    assert!(
        !redis.exists::<_, bool>(&index_key).await.unwrap(),
        "invalidation removes live and expired members alike"
    );
}