distributed 4.4.2

CQRS/ES framework for Rust using Plain Old Rust Structs — append-only events, replay, snapshots, outbox, service bus, and pluggable infrastructure
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Process-plan read stores for GraphQL.
//!
//! Read **models** stay host-agnostic (`DCS-DEC-008`). The engine mounts a
//! [`ReadStore`] per model: SQL scan (default) or cell GET-by-pk.

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use serde_json::Value;

use crate::command_dispatch::HttpCommandHost;
use crate::microsvc::cell_host::InternalHttpSecret;

/// How one GraphQL model is served by this process.
#[derive(Clone)]
pub enum ReadStore {
    /// SQL scan: list/filter/sort/join/`@live` (playground default).
    Sql,
    /// Sealed cell row by primary key only (`DCS-REQ-009`).
    CellByKey(Arc<dyn CellByKeyGetter>),
}

impl std::fmt::Debug for ReadStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Sql => f.write_str("Sql"),
            Self::CellByKey(_) => f.write_str("CellByKey"),
        }
    }
}

impl PartialEq for ReadStore {
    fn eq(&self, other: &Self) -> bool {
        matches!((self, other), (Self::Sql, Self::Sql))
            || matches!((self, other), (Self::CellByKey(_), Self::CellByKey(_)))
    }
}

/// GET the sealed JSON row for one primary key (`DCS-AC-010.1` cell GET).
#[async_trait]
pub trait CellByKeyGetter: Send + Sync {
    async fn get_sealed_row(
        &self,
        primary_key: &BTreeMap<String, String>,
    ) -> Result<Option<Value>, String>;
}

/// HTTP GET `{base}/{pk}` of the sealed row (Todo `/todo/{id}`, Blob `/blob/{game_id}`).
#[derive(Clone)]
pub struct HttpCellByKey {
    http: HttpCommandHost,
}

impl HttpCellByKey {
    pub fn new(base: impl AsRef<str>, internal_secret: InternalHttpSecret) -> Result<Self, String> {
        Ok(Self {
            http: HttpCommandHost::new_internal(base, internal_secret)
                .map_err(|error| error.to_string())?,
        })
    }
}

#[async_trait]
impl CellByKeyGetter for HttpCellByKey {
    async fn get_sealed_row(
        &self,
        primary_key: &BTreeMap<String, String>,
    ) -> Result<Option<Value>, String> {
        if primary_key.len() != 1 {
            return Err("cell-by-key HTTP GET requires exactly one primary-key field".into());
        }
        let id = primary_key.values().next().expect("length checked");
        let (status, body) = self
            .http
            .get_json(id)
            .await
            .map_err(|error| format!("cell GET failed: {error}"))?;
        if status == 404 {
            return Ok(None);
        }
        if !(200..300).contains(&status) {
            return Err(format!("cell GET returned HTTP {status}"));
        }
        Ok(Some(body))
    }
}

/// In-memory sealed rows for compiler/engine tests.
#[derive(Clone, Default)]
pub struct MapCellByKey {
    rows: Arc<Mutex<BTreeMap<String, Value>>>,
}

impl MapCellByKey {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert(&self, pk: impl Into<String>, row: Value) {
        self.rows
            .lock()
            .expect("cell map lock")
            .insert(pk.into(), row);
    }
}

#[async_trait]
impl CellByKeyGetter for MapCellByKey {
    async fn get_sealed_row(
        &self,
        primary_key: &BTreeMap<String, String>,
    ) -> Result<Option<Value>, String> {
        if primary_key.len() != 1 {
            return Err("cell-by-key map requires exactly one primary-key field".into());
        }
        let id = primary_key.values().next().expect("length checked");
        Ok(self.rows.lock().expect("cell map lock").get(id).cloned())
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ReadStoreKind {
    SqlScan,
    CellByKey,
}

impl ReadStore {
    pub(crate) fn kind(&self) -> ReadStoreKind {
        match self {
            Self::Sql => ReadStoreKind::SqlScan,
            Self::CellByKey(_) => ReadStoreKind::CellByKey,
        }
    }

    pub(crate) fn cell_getter(&self) -> Option<Arc<dyn CellByKeyGetter>> {
        match self {
            Self::Sql => None,
            Self::CellByKey(getter) => Some(Arc::clone(getter)),
        }
    }
}

#[cfg(all(test, feature = "sqlite"))]
mod tests {
    use super::*;
    use crate::graphql::compile::{compile_query, QueryPlan, RootKind, SelectionNode};
    use crate::graphql::{claim, col, read, GraphqlEngine, ModelPermissions, ReadStore};
    use crate::microsvc::Session;
    use crate::ReadModel;
    use async_graphql::Request;
    use serde::{Deserialize, Serialize};
    use serde_json::json;

    #[derive(Clone, Serialize, Deserialize, ReadModel)]
    #[readmodel(primary_key = ["id"])]
    struct Todos {
        #[readmodel(id)]
        id: String,
        title: String,
    }

    #[derive(Clone, Serialize, Deserialize, ReadModel)]
    #[readmodel(primary_key = ["user_id"])]
    struct AuthUsers {
        #[readmodel(id)]
        user_id: String,
    }

    #[derive(Clone, Serialize, Deserialize, ReadModel)]
    #[readmodel(primary_key = ["game_id"])]
    struct BlobGames {
        #[readmodel(id)]
        game_id: String,
        owner_id: String,
        score: i64,
        #[readmodel(belongs_to = "AuthUsers", foreign_key = "owner_id")]
        owner: Option<AuthUsers>,
    }

    fn pool() -> sqlx::SqlitePool {
        sqlx::SqlitePool::connect_lazy("sqlite::memory:").unwrap()
    }

    fn session_user() -> Session {
        let mut session = Session::new();
        session.set(crate::microsvc::ROLE_KEY, "user");
        session.set(crate::microsvc::USER_ID_KEY, "alice");
        session
    }

    fn blob_perms() -> ModelPermissions<BlobGames> {
        ModelPermissions::new().grant(
            "user",
            read()
                .all_columns()
                .rows(col("owner_id").eq(claim("x-user-id"))),
        )
    }

    fn todo_perms() -> ModelPermissions<Todos> {
        ModelPermissions::new().grant(
            "user",
            read().all_columns().rows(col("id").eq(claim("x-user-id"))),
        )
    }

    fn user_perms() -> ModelPermissions<AuthUsers> {
        ModelPermissions::new().grant("user", read().all_columns())
    }

    fn list_selection() -> SelectionNode {
        SelectionNode {
            response_key: "todos".into(),
            field_name: "todos".into(),
            args: BTreeMap::from([(
                "where".into(),
                async_graphql::Value::from_json(json!({"title": {"_eq": "ship"}})).unwrap(),
            )]),
            children: vec![SelectionNode {
                response_key: "id".into(),
                field_name: "id".into(),
                args: BTreeMap::new(),
                children: vec![],
            }],
        }
    }

    fn by_pk_selection(game_id: &str) -> SelectionNode {
        SelectionNode {
            response_key: "blob_games_by_pk".into(),
            field_name: "blob_games_by_pk".into(),
            args: BTreeMap::from([("game_id".into(), async_graphql::Value::from(game_id))]),
            children: vec![
                SelectionNode {
                    response_key: "game_id".into(),
                    field_name: "game_id".into(),
                    args: BTreeMap::new(),
                    children: vec![],
                },
                SelectionNode {
                    response_key: "score".into(),
                    field_name: "score".into(),
                    args: BTreeMap::new(),
                    children: vec![],
                },
            ],
        }
    }

    fn by_pk_with_owner_join(game_id: &str) -> SelectionNode {
        let mut selection = by_pk_selection(game_id);
        selection.children.push(SelectionNode {
            response_key: "owner".into(),
            field_name: "owner".into(),
            args: BTreeMap::new(),
            children: vec![SelectionNode {
                response_key: "user_id".into(),
                field_name: "user_id".into(),
                args: BTreeMap::new(),
                children: vec![],
            }],
        });
        selection
    }

    #[tokio::test]
    async fn sql_store_compiles_todos_list_filter() {
        let engine = GraphqlEngine::builder(pool())
            .roles(&["user"])
            .model::<Todos>(todo_perms())
            .build()
            .unwrap();
        let plan = compile_query(
            &engine.inner,
            &session_user(),
            "user",
            "Todos",
            RootKind::List,
            &list_selection(),
        )
        .expect("SQL list/filter should compile");
        assert!(matches!(plan, QueryPlan::Sql(_)));
    }

    #[tokio::test]
    async fn same_blob_games_type_compiles_as_sql_or_cell() {
        let sql = GraphqlEngine::builder(pool())
            .roles(&["user"])
            .model::<BlobGames>(blob_perms())
            .model::<AuthUsers>(user_perms())
            .read_store::<BlobGames>(ReadStore::Sql)
            .build()
            .unwrap();
        assert!(matches!(
            compile_query(
                &sql.inner,
                &session_user(),
                "user",
                "BlobGames",
                RootKind::ByPk,
                &by_pk_selection("g1"),
            )
            .unwrap(),
            QueryPlan::Sql(_)
        ));

        let cells = MapCellByKey::new();
        let cell = GraphqlEngine::builder(pool())
            .roles(&["user"])
            .model::<BlobGames>(blob_perms())
            .model::<AuthUsers>(user_perms())
            .read_store::<BlobGames>(ReadStore::CellByKey(Arc::new(cells)))
            .build()
            .unwrap();
        assert!(matches!(
            compile_query(
                &cell.inner,
                &session_user(),
                "user",
                "BlobGames",
                RootKind::ByPk,
                &by_pk_selection("g1"),
            )
            .unwrap(),
            QueryPlan::CellByKey { .. }
        ));
    }

    #[tokio::test]
    async fn cell_store_rejects_list_filter_join_and_live() {
        let cells = MapCellByKey::new();
        let engine = GraphqlEngine::builder(pool())
            .roles(&["user"])
            .model::<BlobGames>(blob_perms())
            .model::<AuthUsers>(user_perms())
            .read_store::<BlobGames>(ReadStore::CellByKey(Arc::new(cells)))
            .build()
            .unwrap();
        let list = compile_query(
            &engine.inner,
            &session_user(),
            "user",
            "BlobGames",
            RootKind::List,
            &list_selection(),
        )
        .unwrap_err();
        assert!(list.contains("fan out to N cells"), "{list}");

        let mut filtered = by_pk_selection("g1");
        filtered.args.insert(
            "where".into(),
            async_graphql::Value::from_json(json!({"score": {"_gt": 1}})).unwrap(),
        );
        let filter = compile_query(
            &engine.inner,
            &session_user(),
            "user",
            "BlobGames",
            RootKind::ByPk,
            &filtered,
        )
        .unwrap_err();
        assert!(filter.contains("filter"), "{filter}");

        let join = compile_query(
            &engine.inner,
            &session_user(),
            "user",
            "BlobGames",
            RootKind::ByPk,
            &by_pk_with_owner_join("g1"),
        )
        .unwrap_err();
        assert!(join.contains("join"), "{join}");
    }

    #[tokio::test]
    async fn graphql_by_id_hits_cell_get() {
        let cells = MapCellByKey::new();
        cells.insert(
            "game-1",
            json!({ "game_id": "game-1", "owner_id": "alice", "score": 9 }),
        );
        let engine = GraphqlEngine::builder(pool())
            .roles(&["user"])
            .model::<BlobGames>(blob_perms())
            .model::<AuthUsers>(user_perms())
            .read_store::<BlobGames>(ReadStore::CellByKey(Arc::new(cells)))
            .build()
            .unwrap();
        let mut session = session_user();
        session.set(crate::microsvc::USER_ID_KEY, "alice");
        let response = engine
            .execute(
                &session,
                Request::new(r#"{ blob_games_by_pk(game_id: "game-1") { game_id score } }"#),
            )
            .await;
        assert!(response.errors.is_empty(), "{response:?}");
        let data = response.data.into_json().unwrap();
        assert_eq!(data["blob_games_by_pk"]["game_id"], "game-1");
        assert_eq!(data["blob_games_by_pk"]["score"], 9);
    }

    #[tokio::test]
    async fn graphql_by_id_hides_cell_rows_outside_the_role_policy() {
        let cells = MapCellByKey::new();
        cells.insert(
            "game-bob",
            json!({ "game_id": "game-bob", "owner_id": "bob", "score": 9 }),
        );
        cells.insert(
            "game-malformed",
            json!({ "game_id": "game-malformed", "score": 10 }),
        );
        let engine = GraphqlEngine::builder(pool())
            .roles(&["user"])
            .model::<BlobGames>(blob_perms())
            .model::<AuthUsers>(user_perms())
            .read_store::<BlobGames>(ReadStore::CellByKey(Arc::new(cells)))
            .build()
            .unwrap();

        for game_id in ["game-bob", "game-malformed"] {
            let response = engine
                .execute(
                    &session_user(),
                    Request::new(format!(
                        "{{ blob_games_by_pk(game_id: \"{game_id}\") {{ game_id score }} }}"
                    )),
                )
                .await;
            assert!(response.errors.is_empty(), "{response:?}");
            let data = response.data.into_json().unwrap();
            assert!(data["blob_games_by_pk"].is_null(), "{data}");
        }
    }

    #[tokio::test]
    async fn graphql_owner_join_fails_on_cell_store() {
        let cells = MapCellByKey::new();
        let engine = GraphqlEngine::builder(pool())
            .roles(&["user"])
            .model::<BlobGames>(blob_perms())
            .model::<AuthUsers>(user_perms())
            .read_store::<BlobGames>(ReadStore::CellByKey(Arc::new(cells)))
            .build()
            .unwrap();
        let response = engine
            .execute(
                &session_user(),
                Request::new(
                    r#"{ blob_games_by_pk(game_id: "game-1") { game_id owner { user_id } } }"#,
                ),
            )
            .await;
        assert_eq!(response.errors.len(), 1, "{response:?}");
        assert!(
            response.errors[0]
                .message
                .contains("unsupported on cell store"),
            "{response:?}"
        );
    }

    #[tokio::test]
    async fn http_cell_by_key_gets_sealed_row() {
        use axum::extract::Path;
        use axum::http::{HeaderMap, StatusCode};
        use axum::routing::get;
        use axum::{Json, Router};

        const SECRET: &str = "test-only-cell-by-key-secret-32-bytes";

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let app = Router::new().route(
                "/blob/{id}",
                get(|headers: HeaderMap, Path(id): Path<String>| async move {
                    if headers
                        .get(crate::microsvc::cell_host::CELL_INTERNAL_SECRET_HEADER)
                        .and_then(|value| value.to_str().ok())
                        != Some(SECRET)
                    {
                        return (StatusCode::UNAUTHORIZED, Json(json!({ "error": "no" })));
                    }
                    (StatusCode::OK, Json(json!({ "game_id": id, "score": 3 })))
                }),
            );
            axum::serve(listener, app).await.unwrap();
        });
        let getter = HttpCellByKey::new(
            format!("http://{addr}/blob"),
            InternalHttpSecret::new(SECRET).unwrap(),
        )
        .unwrap();
        let mut pk = BTreeMap::new();
        pk.insert("game_id".into(), "g-http".into());
        let row = getter.get_sealed_row(&pk).await.unwrap().unwrap();
        assert_eq!(row["game_id"], "g-http");
        assert_eq!(row["score"], 3);

        pk.insert("tenant_id".into(), "tenant-1".into());
        assert!(getter.get_sealed_row(&pk).await.is_err());
    }
}