allsource-core 0.27.0

High-performance event store core built in 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use super::*;
use crate::infrastructure::web::api;
use axum::{
    Router,
    routing::{get, post},
};
use std::{
    sync::atomic::{AtomicBool, Ordering},
    time::Duration,
};
use tempfile::TempDir;

const TENANT: &str = "synthetic-archive-worker";

#[test]
fn server_warmup_policy_is_explicit_and_preserves_strict_input_limits() {
    assert!(
        EventStoreConfig::default()
            .http_archive_warmup_timeout
            .is_none()
    );
    for data_dir in [None, Some("synthetic-data".to_string())] {
        let (config, _) = EventStoreConfig::from_env_vars(
            data_dir.clone(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        assert_eq!(
            config.http_archive_warmup_timeout,
            data_dir.map(|_| Duration::from_secs(30))
        );
        assert_eq!(config.strict_archive_limits.timeout, Duration::from_secs(4));
        assert_eq!(config.strict_archive_limits.max_files, 50_000);
    }
}

#[test]
fn strict_archive_overrides_parse_and_ignore_invalid_values() {
    let defaults = EventStoreConfig::default().strict_archive_limits;
    let config = EventStoreConfig::default()
        .with_strict_archive_overrides(Some("1073741824".into()), Some("60".into()));
    assert_eq!(config.strict_archive_limits.max_uncompressed_bytes, 1 << 30);
    assert_eq!(
        config.strict_archive_limits.timeout,
        Duration::from_secs(60)
    );
    for invalid in [
        None,
        Some(String::new()),
        Some("0".into()),
        Some("lots".into()),
    ] {
        let config =
            EventStoreConfig::default().with_strict_archive_overrides(invalid.clone(), invalid);
        assert_eq!(
            config.strict_archive_limits.max_uncompressed_bytes,
            defaults.max_uncompressed_bytes
        );
        assert_eq!(config.strict_archive_limits.timeout, defaults.timeout);
    }
}

#[test]
fn raised_decoded_limit_lets_an_oversized_tenant_serve_its_feed() {
    let directory = TempDir::new().unwrap();
    {
        let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
        for _ in 0..3 {
            store.ingest(&event()).unwrap();
        }
        store.flush_storage().unwrap();
    }
    let cold_store = |config: EventStoreConfig| EventStore::with_config(config);
    let mut tight = EventStoreConfig::with_persistence(directory.path());
    tight.strict_archive_limits.max_uncompressed_bytes = 16;
    let refused = cold_store(tight).tenant_feed(TENANT, None, 10).unwrap_err();
    assert!(
        matches!(&refused, AllSourceError::ArchiveBudgetExceeded { dimension } if dimension == "uncompressed bytes"),
        "{refused}"
    );
    let response = axum::response::IntoResponse::into_response(refused);
    assert_eq!(
        response.status(),
        axum::http::StatusCode::SERVICE_UNAVAILABLE
    );
    assert_eq!(response.headers()[axum::http::header::RETRY_AFTER], "300");

    let mut raised = EventStoreConfig::with_persistence(directory.path());
    raised.strict_archive_limits.max_uncompressed_bytes = 16;
    let raised = raised.with_strict_archive_overrides(Some("1048576".into()), None);
    let page = cold_store(raised).tenant_feed(TENANT, None, 10).unwrap();
    assert_eq!(page.events.len(), 3);
}

fn event() -> Event {
    Event::from_strings(
        "synthetic.updated".into(),
        "synthetic-entity".into(),
        TENANT.into(),
        serde_json::json!({"synthetic": true}),
        None,
    )
    .unwrap()
}

#[test]
fn cancelled_conditional_append_does_not_reach_wal_or_cache() {
    let directory = TempDir::new().unwrap();
    let config = EventStoreConfig {
        storage_dir: Some(directory.path().join("storage")),
        wal_dir: Some(directory.path().join("wal")),
        ..Default::default()
    };
    let store = EventStore::with_config(config.clone());
    let mut subscriber = store.subscribe_events();
    let cancellation = Arc::new(AtomicBool::new(true));
    assert!(
        store
            .ingest_with_expected_version_cancellable(&event(), Some(0), Some(&cancellation))
            .is_err()
    );
    assert_eq!(store.total_events(), 0);
    assert!(subscriber.try_recv().is_err());
    drop(store);
    let reopened = EventStore::with_config(config);
    assert_eq!(reopened.total_events(), 0);
    assert_eq!(
        reopened
            .ingest_with_expected_version(&event(), Some(0))
            .unwrap(),
        1
    );
}

#[test]
fn only_the_first_conditional_append_to_an_entity_takes_an_archive_slot() {
    let directory = TempDir::new().unwrap();
    let seed = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
    seed.ingest_with_expected_version(&event(), Some(0))
        .unwrap();
    seed.flush_storage().unwrap();
    drop(seed);

    let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
    assert!(store.conditional_append_reads_archive(TENANT, "synthetic-entity"));
    store
        .ingest_with_expected_version(&event(), Some(1))
        .unwrap();
    assert!(!store.conditional_append_reads_archive(TENANT, "synthetic-entity"));

    assert!(!EventStore::new().conditional_append_reads_archive(TENANT, "synthetic-entity"));
}

#[test]
fn http_append_rejects_corrupt_over_budget_or_read_only_archives() {
    for failure in ["file cap", "corrupt", "read only"] {
        let directory = TempDir::new().unwrap();
        let seed = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
        seed.ingest_with_expected_version(&event(), Some(0))
            .unwrap();
        seed.flush_storage().unwrap();
        drop(seed);
        let mut config = EventStoreConfig {
            http_archive_warmup_timeout: Some(Duration::from_secs(30)),
            ..EventStoreConfig::with_persistence(directory.path())
        };
        match failure {
            "file cap" => config.strict_archive_limits.max_files = 0,
            "corrupt" => std::fs::write(
                directory.path().join(TENANT).join("events-corrupt.parquet"),
                "synthetic invalid parquet",
            )
            .unwrap(),
            "read only" => config.read_only = true,
            _ => unreachable!(),
        }
        let store = EventStore::with_config(config);
        let mut subscriber = store.subscribe_events();
        let cancellation = Arc::new(AtomicBool::new(false));
        // Mirrors archive_work::append: the admission check no longer warms
        // the archive, so a damaged or over-budget one is refused by the
        // conditional write that reads it.
        let error = store
            .prepare_http_append(&event(), &cancellation)
            .and_then(|()| {
                store.ingest_with_expected_version_cancellable(
                    &event(),
                    Some(1),
                    Some(&cancellation),
                )
            })
            .unwrap_err();
        if failure == "file cap" {
            assert!(error.to_string().contains("budget exceeded: files"));
        }
        assert!(!store.tenant_loader.is_complete(TENANT), "{failure}");
        assert_eq!(store.total_events(), 0, "{failure}");
        assert!(subscriber.try_recv().is_err(), "{failure}");
    }
}

#[tokio::test(flavor = "current_thread")]
async fn cancellation_is_checked_after_waiting_for_durability_gate() {
    let store = Arc::new(EventStore::new());
    let gate_store = Arc::clone(&store);
    let (held_tx, held_rx) = tokio::sync::oneshot::channel();
    let (release_tx, release_rx) = std::sync::mpsc::channel();
    let holder = std::thread::spawn(move || {
        let _gate = gate_store.durability_gate.write();
        held_tx.send(()).unwrap();
        // test-hang-allow: bounded synthetic checkpoint contention.
        release_rx.recv_timeout(Duration::from_secs(2))
    });
    held_rx.await.unwrap();
    let cancellation = Arc::new(AtomicBool::new(false));
    let worker_store = Arc::clone(&store);
    let worker_cancel = Arc::clone(&cancellation);
    let worker = tokio::task::spawn_blocking(move || {
        worker_store.ingest_with_expected_version_cancellable(
            &event(),
            Some(0),
            Some(&worker_cancel),
        )
    });
    // The version index resolves after the entry cancellation check and before
    // the held durability gate.
    // test-hang-allow: bounded observation of the real store reaching that boundary.
    tokio::time::timeout(Duration::from_secs(1), async {
        while !store
            .version_index_entities
            .contains_key("synthetic-entity")
        {
            tokio::time::sleep(Duration::from_millis(1)).await;
        }
    })
    .await
    .unwrap();
    cancellation.store(true, Ordering::Release);
    release_tx.send(()).unwrap();
    assert!(worker.await.unwrap().is_err());
    holder.join().unwrap().unwrap();
    assert_eq!(store.total_events(), 0);
    assert_eq!(store.get_entity_version("synthetic-entity"), 0);
}

#[tokio::test(flavor = "current_thread")]
async fn http_health_and_ordinary_writes_survive_a_waiting_conditional_load() {
    let directory = TempDir::new().unwrap();
    let store = Arc::new(EventStore::with_config(EventStoreConfig::with_persistence(
        directory.path(),
    )));
    let lock = store.tenant_loader.lock_for(TENANT);
    let (held_tx, held_rx) = tokio::sync::oneshot::channel();
    let (release_tx, release_rx) = std::sync::mpsc::channel();
    let holder = std::thread::spawn(move || {
        let _guard = lock.lock();
        held_tx.send(()).unwrap();
        // test-hang-allow: synthetic cold-load contention, always releases within three seconds.
        release_rx.recv_timeout(Duration::from_secs(3))
    });
    held_rx.await.unwrap();

    let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
    let entered = Arc::new(parking_lot::Mutex::new(Some(entered_tx)));
    let app = Router::new()
        .route("/health", get(api::health))
        .route("/events", post(api::ingest_event))
        .layer(axum::middleware::from_fn(
            move |request: axum::extract::Request, next: axum::middleware::Next| {
                let entered = Arc::clone(&entered);
                async move {
                    if request.uri().path() == "/events"
                        && let Some(signal) = entered.lock().take()
                    {
                        let _ = signal.send(());
                    }
                    next.run(request).await
                }
            },
        ))
        .with_state(Arc::clone(&store));
    // test-hang-allow: owned ephemeral loopback listener; server aborted and joined below.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let url = format!("http://{}", listener.local_addr().unwrap());
    let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(2))
        .no_proxy()
        .build()
        .unwrap();
    let request = client
        .post(format!("{url}/events"))
        .json(&serde_json::json!({
            "tenant_id": TENANT, "entity_id": "conditional", "event_type": "synthetic.updated",
            "payload": {}, "expected_version": 0
        }));
    let pending = tokio::spawn(async move { request.send().await.unwrap() });
    tokio::time::timeout(Duration::from_secs(1), entered_rx)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        client
            .get(format!("{url}/health"))
            .send()
            .await
            .unwrap()
            .status(),
        200
    );
    assert_eq!(client.post(format!("{url}/events")).json(&serde_json::json!({
        "tenant_id": "synthetic-other", "entity_id": "ordinary", "event_type": "synthetic.updated", "payload": {}
    })).send().await.unwrap().status(), 200);
    // A conditional write resolves its version straight from the archive and
    // never takes the tenant load lock, so holding that lock cannot stall it.
    assert_eq!(pending.await.unwrap().status(), 200);
    release_tx.send(()).unwrap();
    holder.join().unwrap().unwrap();
    server.abort();
    assert!(server.await.unwrap_err().is_cancelled());
    assert_eq!(store.total_events(), 2);
}

#[tokio::test(flavor = "current_thread")]
async fn timed_out_http_append_leaves_no_trace_of_the_cancelled_command() {
    let directory = TempDir::new().unwrap();
    let storage_dir = directory.path().join("storage");
    let seed = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
    seed.ingest_with_expected_version(&event(), Some(0))
        .unwrap();
    seed.flush_storage().unwrap();
    drop(seed);
    let config = EventStoreConfig {
        storage_dir: Some(storage_dir),
        wal_dir: Some(directory.path().join("wal")),
        http_archive_warmup_timeout: Some(Duration::from_secs(10)),
        ..Default::default()
    };
    let store = Arc::new(EventStore::with_config(config.clone()));
    let mut subscriber = store.subscribe_events();
    // Hold the storage lock the version resolve needs, so the conditional
    // append stalls on the archive read rather than on a cache load.
    let lock_store = Arc::clone(&store);
    let (held_tx, held_rx) = tokio::sync::oneshot::channel();
    let (release_tx, release_rx) = std::sync::mpsc::channel();
    let holder = std::thread::spawn(move || {
        let _guard = lock_store.storage.as_ref().unwrap().write();
        held_tx.send(()).unwrap();
        // test-hang-allow: controlled cold-load contention outlives the five-second response.
        release_rx.recv_timeout(Duration::from_secs(8))
    });
    held_rx.await.unwrap();
    let app = Router::new()
        .route("/health", get(api::health))
        .route("/events", post(api::ingest_event))
        .with_state(Arc::clone(&store));
    // test-hang-allow: owned ephemeral listener, aborted and joined before reopening WAL.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let url = format!("http://{}", listener.local_addr().unwrap());
    let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(7))
        .no_proxy()
        .build()
        .unwrap();
    let command = serde_json::json!({
        "tenant_id": TENANT, "entity_id": "synthetic-entity",
        "event_type": "synthetic.updated", "payload": {}, "expected_version": 1
    });
    let response = client
        .post(format!("{url}/events"))
        .json(&command)
        .send()
        .await
        .unwrap();
    assert_eq!(response.status(), 503);
    assert!(
        response
            .text()
            .await
            .unwrap()
            .contains("response deadline exceeded")
    );
    assert!(!store.tenant_loader.is_complete(TENANT));
    assert_eq!(
        client
            .get(format!("{url}/health"))
            .send()
            .await
            .unwrap()
            .status(),
        200
    );
    release_tx.send(()).unwrap();
    holder.join().unwrap().unwrap();
    // Cancellation reaches the archive read, so the abandoned command leaves
    // nothing behind: no event, no broadcast, no half-built version index.
    // Under memory pressure, abandoning the read is the point.
    assert_eq!(store.total_events(), 0);
    assert!(
        !store
            .version_index_entities
            .contains_key("synthetic-entity")
    );
    assert!(subscriber.try_recv().is_err());
    let response = client
        .post(format!("{url}/events"))
        .json(&command)
        .send()
        .await
        .unwrap();
    assert_eq!(response.status(), 200);
    assert_eq!(store.get_entity_version("synthetic-entity"), 2);
    server.abort();
    assert!(server.await.unwrap_err().is_cancelled());
    // test-hang-allow: prove all request/worker store leases ended before reopening WAL.
    tokio::time::timeout(Duration::from_secs(2), async {
        while Arc::strong_count(&store) != 1 {
            tokio::time::sleep(Duration::from_millis(1)).await;
        }
    })
    .await
    .unwrap();
    drop(store);
    let reopened = EventStore::with_config(config);
    let (events, count) = reopened
        .query_retained_entity(TENANT, "synthetic-entity", 10, &ReadScope::unrestricted())
        .unwrap();
    assert_eq!(count, 2);
    assert_eq!(
        events.iter().map(|event| event.version).collect::<Vec<_>>(),
        vec![1, 2]
    );
}