type-bridge 2.0.1

Public client SDK for TypeBridge
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};

use crate::__codegen::{
    self, CompleteModel, EncodedCreate, EncodedReference, EncodedScalar, EntityModel, HydratedRow,
    HydrationCapability, IntoEncodedCreate, MaterializeModel, Model, RelationModel, ThingModel,
    ValidationError, ValidationPath,
};
use crate::schema::{Schema, sealed};
use type_bridge_contract::fingerprint::SemanticProfileId;
use type_bridge_contract::projection::{BindingTarget, ProjectionConfig};
use type_bridge_contract::schema::DocumentId;
use type_bridge_orm::session::backend::{
    BoxFuture, DriverBackend, QueryResult, TransactionOps, TxType,
};
use type_bridge_orm::{Database as OrmDatabase, OrmError};
use type_bridge_schema::{SchemaDocumentSet, normalize_documents, project, resolve};
use type_bridge_schema_codegen::RustEmitter;

struct TestSchema;
impl sealed::Sealed for TestSchema {}
impl Schema for TestSchema {}

const PERSON_JSON: &str = r#"{"kind":"entity","label":"person"}"#;
const NAME_OWNS: &str = r#"{"attribute":"name","owner":{"kind":"entity","label":"person"}}"#;
const ASSIGNMENT_JSON: &str = r#"{"kind":"relation","label":"assignment"}"#;
const POSITION_OWNS: &str =
    r#"{"attribute":"position","owner":{"kind":"relation","label":"assignment"}}"#;

fn worker_role() -> &'static str {
    Box::leak(
        String::from_utf8(
            type_bridge_contract::codec::to_canonical_json(
                &type_bridge_contract::id::RoleId::new("assignment", "worker").unwrap(),
            )
            .unwrap(),
        )
        .unwrap()
        .into_boxed_str(),
    )
}

#[derive(Debug)]
struct WorkerCreate {
    name: String,
}
impl sealed::Sealed for WorkerCreate {}
impl IntoEncodedCreate for WorkerCreate {
    fn into_encoded_create(self) -> Result<EncodedCreate, ValidationError> {
        Ok(EncodedCreate::new(
            PERSON_JSON,
            vec![(NAME_OWNS, vec![EncodedScalar::String(self.name)])],
            vec![],
        ))
    }
}

#[derive(Debug)]
struct Worker {
    iid: String,
    name: String,
}
impl sealed::Sealed for Worker {}
impl Model for Worker {
    type Schema = TestSchema;
    const TYPE_ID_JSON: &'static str = PERSON_JSON;
}
impl ThingModel for Worker {
    fn thing_kind() -> __codegen::ThingKind {
        __codegen::ThingKind::Entity
    }
}
impl EntityModel for Worker {}
impl CompleteModel for Worker {
    type Create = WorkerCreate;
    fn iid(&self) -> &str {
        &self.iid
    }
}
impl MaterializeModel for Worker {
    fn materialize(row: &HydratedRow, _cap: &HydrationCapability) -> Result<Self, ValidationError> {
        row.validate_shape(
            Self::TYPE_ID_JSON,
            &[NAME_OWNS],
            &[],
            &__codegen::ValidationPath::root(),
        )?;
        let name = match row.fields().first().and_then(|(_, values)| values.first()) {
            Some(EncodedScalar::String(value)) => value.clone(),
            _ => return Err(ValidationError::new("name", "missing_name")),
        };
        Ok(Self {
            iid: row.iid().to_owned(),
            name,
        })
    }
}

#[derive(Debug)]
struct AssignmentCreate {
    position: String,
    worker_iid: String,
}
impl sealed::Sealed for AssignmentCreate {}
impl IntoEncodedCreate for AssignmentCreate {
    fn into_encoded_create(self) -> Result<EncodedCreate, ValidationError> {
        let reference = EncodedReference::try_new(
            PERSON_JSON,
            Some(self.worker_iid),
            vec![],
            &ValidationPath::root(),
        )?;
        Ok(EncodedCreate::new(
            ASSIGNMENT_JSON,
            vec![(POSITION_OWNS, vec![EncodedScalar::String(self.position)])],
            vec![(worker_role(), vec![reference])],
        ))
    }
}

#[derive(Debug)]
struct Assignment {
    iid: String,
    position: String,
}
impl sealed::Sealed for Assignment {}
impl Model for Assignment {
    type Schema = TestSchema;
    const TYPE_ID_JSON: &'static str = ASSIGNMENT_JSON;
}
impl ThingModel for Assignment {
    fn thing_kind() -> __codegen::ThingKind {
        __codegen::ThingKind::Relation
    }
}
impl RelationModel for Assignment {}
impl CompleteModel for Assignment {
    type Create = AssignmentCreate;
    fn iid(&self) -> &str {
        &self.iid
    }
}
impl MaterializeModel for Assignment {
    fn materialize(row: &HydratedRow, _cap: &HydrationCapability) -> Result<Self, ValidationError> {
        row.validate_shape(
            Self::TYPE_ID_JSON,
            &[POSITION_OWNS],
            &[worker_role()],
            &__codegen::ValidationPath::root(),
        )?;
        let position = match row.fields().first().and_then(|(_, values)| values.first()) {
            Some(EncodedScalar::String(value)) => value.clone(),
            _ => return Err(ValidationError::new("position", "missing_position")),
        };
        Ok(Self {
            iid: row.iid().to_owned(),
            position,
        })
    }
}

fn minimal_fixture() -> type_bridge_orm::InstalledRuntimeProjection {
    let docs = SchemaDocumentSet::parse([(
        DocumentId::new("t01.yaml").unwrap(),
        r#"format: typebridge.schema/v2
attributes:
  name: { value: string }
  position: { value: string }
entities:
  person:
    owns:
      name: { key: true }
relations:
  assignment:
    owns:
      position: { key: true }
    relates:
      worker: { card: 1 }
plays:
  person:
    assignment: [worker]
"#,
    )])
    .unwrap();
    let resolved = resolve(
        &normalize_documents(&docs).unwrap(),
        &SemanticProfileId::new("typedb-3.12.1/v1").unwrap(),
    )
    .unwrap();
    let emitter = RustEmitter::new();
    let projection = project(
        &resolved,
        BindingTarget::Rust,
        &ProjectionConfig::rust(),
        &emitter.generator_handlers(),
        &emitter.code_resources().unwrap(),
    )
    .unwrap();
    type_bridge_orm::InstalledRuntimeProjection::try_new(projection).unwrap()
}

#[derive(Default)]
struct State {
    events: Vec<Event>,
    query_modes: Vec<&'static str>,
}
#[derive(Debug, PartialEq, Eq)]
enum Event {
    Open(TxType),
    Query(String),
    Commit,
    Rollback,
    Close,
}
enum Response {
    Result(QueryResult),
    Error(String),
}

struct Backend {
    state: Arc<Mutex<State>>,
    responses: Arc<Mutex<VecDeque<Response>>>,
}

impl DriverBackend for Backend {
    fn open_transaction(
        &self,
        _db: &str,
        ty: TxType,
    ) -> BoxFuture<'_, Result<Box<dyn TransactionOps>, OrmError>> {
        self.state.lock().unwrap().events.push(Event::Open(ty));
        let tx = Tx {
            state: Arc::clone(&self.state),
            responses: Arc::clone(&self.responses),
        };
        Box::pin(async move { Ok(Box::new(tx) as Box<dyn TransactionOps>) })
    }
    fn is_open(&self) -> bool {
        true
    }
}

struct Tx {
    state: Arc<Mutex<State>>,
    responses: Arc<Mutex<VecDeque<Response>>>,
}

impl TransactionOps for Tx {
    fn query(&mut self, q: &str) -> BoxFuture<'_, Result<QueryResult, OrmError>> {
        self.state.lock().unwrap().query_modes.push("legacy");
        self.query_recorded(q)
    }
    fn query_canonical(&mut self, q: &str) -> BoxFuture<'_, Result<QueryResult, OrmError>> {
        self.state.lock().unwrap().query_modes.push("canonical");
        self.query_recorded(q)
    }
    fn commit(&mut self) -> BoxFuture<'_, Result<(), OrmError>> {
        self.state.lock().unwrap().events.push(Event::Commit);
        Box::pin(async { Ok(()) })
    }
    fn rollback(&mut self) -> BoxFuture<'_, Result<(), OrmError>> {
        self.state.lock().unwrap().events.push(Event::Rollback);
        Box::pin(async { Ok(()) })
    }
    fn close(&mut self) -> BoxFuture<'_, Result<(), OrmError>> {
        self.state.lock().unwrap().events.push(Event::Close);
        Box::pin(async { Ok(()) })
    }
}

impl Tx {
    fn query_recorded(&mut self, q: &str) -> BoxFuture<'_, Result<QueryResult, OrmError>> {
        self.state
            .lock()
            .unwrap()
            .events
            .push(Event::Query(q.to_owned()));
        let result = self
            .responses
            .lock()
            .unwrap()
            .pop_front()
            .unwrap_or_else(|| panic!("unexpected recording query: {q}"));
        Box::pin(async move {
            match result {
                Response::Result(value) => Ok(value),
                Response::Error(error) => Err(OrmError::QueryExecution(error)),
            }
        })
    }
}

fn test_db(responses: Vec<Response>) -> (crate::session::Database<TestSchema>, Arc<Mutex<State>>) {
    let state = Arc::new(Mutex::new(State::default()));
    let backend = Backend {
        state: Arc::clone(&state),
        responses: Arc::new(Mutex::new(responses.into())),
    };
    (
        crate::session::Database::<TestSchema>::from_test_parts(
            OrmDatabase::with_backend(Box::new(backend), "t01"),
            minimal_fixture(),
        ),
        state,
    )
}

fn iid_doc(iid: &str) -> Response {
    Response::Result(QueryResult::Documents(vec![serde_json::json!({
        "iid": iid
    })]))
}

fn worker_fetch(iid: &str, name: &str) -> Response {
    Response::Result(QueryResult::Documents(vec![serde_json::json!({
        "_iid": iid,
        "_type": "person",
        "attributes": {"name": [name]}
    })]))
}

fn assignment_fetch(iid: &str, position: &str, worker_iid: &str) -> Response {
    Response::Result(QueryResult::Documents(vec![serde_json::json!({
        "_iid": iid,
        "_type": "assignment",
        "attributes": {"position": [position]},
        "_role_0_iid": worker_iid,
        "_role_0_type": "person",
        "_role_0_attributes": {}
    })]))
}

fn assert_model_error(
    error: crate::Error,
    phase: crate::error::ModelValidationPhase,
    code: &str,
    path: &[&str],
) {
    let crate::Error::ModelValidation {
        phase: actual_phase,
        code: actual,
        path: actual_path,
        ..
    } = error
    else {
        panic!("expected model validation error")
    };
    assert_eq!(actual_phase, phase);
    assert_eq!(actual, code);
    assert_eq!(
        actual_path,
        path.iter().map(|v| (*v).to_owned()).collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn write_transaction_requires_schema_binding_before_io() {
    let state = Arc::new(Mutex::new(State::default()));
    let backend = Backend {
        state: Arc::clone(&state),
        responses: Arc::new(Mutex::new(VecDeque::new())),
    };
    let db = crate::session::Database::<TestSchema>::from_test_unbound_parts(
        OrmDatabase::with_backend(Box::new(backend), "t01"),
    );
    assert_model_error(
        db.write().await.unwrap_err(),
        crate::error::ModelValidationPhase::Input,
        "schema_not_bound",
        &[],
    );
    assert_eq!(state.lock().unwrap().events.as_slice(), &[] as &[Event]);
}

#[tokio::test]
async fn read_transaction_requires_schema_binding_before_io() {
    let state = Arc::new(Mutex::new(State::default()));
    let backend = Backend {
        state: Arc::clone(&state),
        responses: Arc::new(Mutex::new(VecDeque::new())),
    };
    let db = crate::session::Database::<TestSchema>::from_test_unbound_parts(
        OrmDatabase::with_backend(Box::new(backend), "t01"),
    );
    assert_model_error(
        db.read().await.unwrap_err(),
        crate::error::ModelValidationPhase::Input,
        "schema_not_bound",
        &[],
    );
    assert_eq!(state.lock().unwrap().events.as_slice(), &[] as &[Event]);
}

#[tokio::test]
async fn read_transaction_reuses_one_borrowed_context_and_closes_without_commit() {
    let (db, state) = test_db(vec![]);
    let read = db.read().await.unwrap();
    let mut session = read.query();
    let worker = session.exact::<Worker>().unwrap();
    let query = session.query(worker).unwrap();

    // The recording backend does not advertise the selected-query
    // capability. Both terminals therefore fail at preflight, but must route
    // through and preserve the same caller-owned read context.
    assert!(query.count().await.is_err());
    assert!(query.count().await.is_err());
    {
        let guard = state.lock().unwrap();
        assert_eq!(
            guard
                .events
                .iter()
                .filter(|event| matches!(event, Event::Open(TxType::Read)))
                .count(),
            1
        );
        assert!(
            !guard
                .events
                .iter()
                .any(|event| matches!(event, Event::Commit | Event::Rollback | Event::Close))
        );
    }

    drop(query);
    drop(session);
    read.close().await.unwrap();
    let guard = state.lock().unwrap();
    assert!(matches!(guard.events.last(), Some(Event::Close)));
    assert!(
        !guard
            .events
            .iter()
            .any(|event| matches!(event, Event::Commit | Event::Rollback))
    );
}

#[tokio::test]
async fn write_transaction_commits_multiple_operations_in_one_context() {
    let (db, state) = test_db(vec![
        iid_doc("0x1"),
        worker_fetch("0x1", "alice"),
        iid_doc("0x2"),
        assignment_fetch("0x2", "captain", "0x1"),
    ]);
    let tx = db.write().await.unwrap();
    let worker = tx
        .entities::<Worker>()
        .insert(WorkerCreate {
            name: "alice".into(),
        })
        .await
        .unwrap();
    assert_eq!(worker.iid, "0x1");
    assert_eq!(worker.name, "alice");
    let assignment = tx
        .relations::<Assignment>()
        .insert(AssignmentCreate {
            position: "captain".into(),
            worker_iid: worker.iid.clone(),
        })
        .await
        .unwrap();
    assert_eq!(assignment.iid, "0x2");
    assert_eq!(assignment.position, "captain");
    tx.commit().await.unwrap();
    let guard = state.lock().unwrap();
    let opens = guard
        .events
        .iter()
        .filter(|event| matches!(event, Event::Open(_)))
        .count();
    assert_eq!(opens, 1);
    assert!(matches!(
        guard.events.first(),
        Some(Event::Open(TxType::Write))
    ));
    assert!(matches!(guard.events.last(), Some(Event::Commit)));
    let commits = guard
        .events
        .iter()
        .filter(|event| matches!(event, Event::Commit))
        .count();
    assert_eq!(commits, 1);
    assert!(
        !guard
            .events
            .iter()
            .any(|event| matches!(event, Event::Rollback | Event::Close))
    );
    assert!(guard.query_modes.iter().all(|mode| *mode == "canonical"));
}

#[tokio::test]
async fn write_transaction_explicit_rollback_discards_operations() {
    let (db, state) = test_db(vec![iid_doc("0x1"), worker_fetch("0x1", "alice")]);
    let tx = db.write().await.unwrap();
    tx.entities::<Worker>()
        .insert(WorkerCreate {
            name: "alice".into(),
        })
        .await
        .unwrap();
    tx.rollback().await.unwrap();
    let guard = state.lock().unwrap();
    assert!(matches!(guard.events.last(), Some(Event::Rollback)));
    assert!(
        !guard
            .events
            .iter()
            .any(|event| matches!(event, Event::Commit))
    );
}

#[tokio::test]
async fn write_transaction_uncommitted_drop_releases_without_commit() {
    let (db, state) = test_db(vec![iid_doc("0x1"), worker_fetch("0x1", "alice")]);
    let tx = db.write().await.unwrap();
    tx.entities::<Worker>()
        .insert(WorkerCreate {
            name: "alice".into(),
        })
        .await
        .unwrap();
    drop(tx);
    let guard = state.lock().unwrap();
    assert!(
        !guard
            .events
            .iter()
            .any(|event| matches!(event, Event::Commit | Event::Rollback))
    );
}

#[tokio::test]
async fn write_transaction_error_leaves_terminal_control_with_caller() {
    let (db, state) = test_db(vec![Response::Error("insert failed".into())]);
    let tx = db.write().await.unwrap();
    let error = tx
        .entities::<Worker>()
        .insert(WorkerCreate {
            name: "alice".into(),
        })
        .await
        .unwrap_err();
    assert!(matches!(error, crate::Error::QueryExecution { .. }));
    {
        let guard = state.lock().unwrap();
        assert!(
            !guard
                .events
                .iter()
                .any(|event| matches!(event, Event::Commit | Event::Rollback | Event::Close))
        );
    }
    tx.rollback().await.unwrap();
    let guard = state.lock().unwrap();
    assert!(matches!(guard.events.last(), Some(Event::Rollback)));
}

#[tokio::test]
async fn write_transaction_preflight_and_reads_share_the_open_context() {
    let (db, state) = test_db(vec![
        Response::Result(QueryResult::Documents(Vec::new())),
        Response::Result(QueryResult::Rows(vec![serde_json::json!({"$count": 0})])),
    ]);
    let tx = db.write().await.unwrap();
    assert_model_error(
        tx.entities::<Worker>().get_by_iid("bad").await.unwrap_err(),
        crate::error::ModelValidationPhase::Input,
        "invalid_iid",
        &["iid"],
    );
    assert_model_error(
        tx.relations::<Assignment>()
            .update(
                "bad",
                AssignmentCreate {
                    position: "p".into(),
                    worker_iid: "0x1".into(),
                },
            )
            .await
            .unwrap_err(),
        crate::error::ModelValidationPhase::Input,
        "invalid_iid",
        &["iid"],
    );
    {
        let guard = state.lock().unwrap();
        assert_eq!(guard.events.len(), 1);
        assert!(matches!(guard.events[0], Event::Open(TxType::Write)));
    }
    assert!(
        tx.entities::<Worker>()
            .get_by_iid("0x9")
            .await
            .unwrap()
            .is_none()
    );
    assert_eq!(tx.relations::<Assignment>().count().await.unwrap(), 0);
    tx.rollback().await.unwrap();
    let guard = state.lock().unwrap();
    let opens = guard
        .events
        .iter()
        .filter(|event| matches!(event, Event::Open(_)))
        .count();
    assert_eq!(opens, 1);
    assert!(matches!(guard.events.last(), Some(Event::Rollback)));
}