tembra-core 0.3.1

Language-neutral ownership and execution kernel for Tembra
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
use super::*;

#[test]
fn identities_cross_u32_and_stop_at_the_javascript_safe_integer_limit() {
    let host = Host::new();
    host.inner.borrow_mut().next = u32::MAX.into();
    assert_eq!(host.allocate_handle().unwrap(), u64::from(u32::MAX));
    assert_eq!(host.allocate_handle().unwrap(), u64::from(u32::MAX) + 1);
    host.inner.borrow_mut().next = 9_007_199_254_740_990;
    assert_eq!(host.allocate_handle().unwrap(), 9_007_199_254_740_990);
    assert_eq!(host.allocate_handle().unwrap(), 9_007_199_254_740_991);
    let next = host.inner.borrow().next;
    for _ in 0..2 {
        let error = host.allocate_handle().unwrap_err();
        assert_eq!(error.code, Code::Exhausted);
        assert_eq!(error.reason, Reason::Identities.as_str());
        assert_eq!(host.inner.borrow().next, next);
    }
}

#[test]
fn multi_identity_reservation_at_the_limit_leaves_preparation_unchanged() {
    let host = Host::new();
    host.inner.borrow_mut().next = MAX_ID;
    let before = host.diagnostics();
    let error = host
        .prepare(vec![Orb::new("limit", 1)], vec![])
        .unwrap_err();
    assert_eq!(error.code, Code::Exhausted);
    assert_eq!(host.diagnostics(), before);
    assert!(host.inner.borrow().pending.is_none());
    assert_eq!(host.allocate_handle().unwrap(), MAX_ID);
}

fn install(host: &Host) -> InstalledOrb {
    let reload = host.prepare(vec![Orb::new("example", 1)], vec![]).unwrap();
    let orb = reload.orbs[0].clone();
    host.commit(reload.id, vec![]).unwrap();
    orb
}

#[test]
fn admitted_roots_retain_old_versions_but_new_task_roots_use_current_code() {
    let host = Host::new();
    let old = install(&host);
    let root = host.begin_root("host").unwrap();
    let task = host.begin_task(Owner::Orb(old.owner)).unwrap();
    let current = install(&host);
    for _ in 0..100 {
        let root = host.begin_root("host").unwrap();
        host.end_root(root).unwrap();
    }
    assert_eq!(host.inner.borrow().versions.len(), 2);
    assert!(host.orb(old.id).is_ok());
    let retained = host.task_root(task, "host").unwrap();
    assert_eq!(
        host.inner.borrow().roots[&retained].version,
        current.code_version
    );
    host.end_root(root).unwrap();
    assert!(host.orb(old.id).is_err());
    host.finish_task(task).unwrap();
    host.end_root(retained).unwrap();
    assert_eq!(host.inner.borrow().versions.len(), 1);
    assert!(host.orb(old.id).is_err());
    assert!(host.orb(current.id).is_ok());
    assert!(host.inner.borrow().version_users.is_empty());
    assert!(host.drain().contains(&Action::RetireOrb(old.id)));
}

#[test]
fn an_unrelated_task_does_not_exhaust_the_retained_version_limit() {
    let host = Host::new();
    let owner = install(&host).owner;
    let task = host.begin_task(Owner::Orb(owner)).unwrap();
    for _ in 0..40 {
        let orb = install(&host);
        let root = host.task_root(task, "host").unwrap();
        assert_eq!(host.inner.borrow().roots[&root].version, orb.code_version);
        host.end_root(root).unwrap();
        assert_eq!(host.inner.borrow().versions.len(), 1);
    }
    host.finish_task(task).unwrap();
}

fn lingering_object(host: &Host, linger_ms: u32) -> Acquisition {
    let mut orb = Orb::new("linger", 1);
    let mut service = Service::new("linger", ["read"]);
    service.linger_ms = linger_ms;
    orb.services.push(service);
    let reload = host.prepare(vec![orb], vec![]).unwrap();
    host.commit(reload.id, vec![]).unwrap();
    let claim = host
        .acquire(
            Address {
                service: "linger".into(),
                key: vec!["main".into()],
                principal: "host".into(),
            },
            1,
            BTreeSet::new(),
        )
        .unwrap();
    host.ready(claim.object).unwrap();
    host.drain();
    claim
}

#[test]
fn linger_keeps_tasks_alive_and_reacquisition_resets_the_idle_deadline() {
    let host = Host::new();
    let claim = lingering_object(&host, 100);
    let address = host.object_address(claim.object).unwrap();
    let task = host.begin_task(Owner::Object(claim.object)).unwrap();
    host.release(claim.reference).unwrap();
    assert!(host.drain().is_empty());
    assert_eq!(host.next_idle(), Some(100));
    let root = host.task_root(task, "host").unwrap();
    host.end_root(root).unwrap();
    host.tick(50).unwrap();
    let again = host.acquire(address.clone(), 1, BTreeSet::new()).unwrap();
    assert_eq!(again.object, claim.object);
    assert!(!again.activate);
    assert_eq!(host.next_idle(), None);
    host.tick(150).unwrap();
    assert!(host.drain().is_empty());
    host.release(again.reference).unwrap();
    host.tick(249).unwrap();
    assert_eq!(host.next_idle(), Some(1));
    assert!(host.drain().is_empty());
    host.tick(250).unwrap();
    assert_eq!(host.drain(), [Action::CancelTask(task)]);
    assert_eq!(
        host.task_root(task, "host").unwrap_err().code,
        Code::Cancelled
    );
    assert_eq!(
        host.acquire(address.clone(), 1, BTreeSet::new())
            .unwrap_err()
            .reason,
        Reason::Disposing.as_str()
    );
    assert_eq!(
        host.disposed(claim.object).unwrap_err().reason,
        Reason::CleanupBusy.as_str()
    );
    host.tick(251).unwrap();
    assert!(host.drain().is_empty());
    host.finish_task(task).unwrap();
    assert_eq!(host.drain(), [Action::DisposeObject(claim.object)]);
    host.disposed(claim.object).unwrap();
    let next = host.acquire(address, 1, BTreeSet::new()).unwrap();
    assert_ne!(next.object, claim.object);
    host.close();
    assert_eq!(host.drain(), [Action::DisposeObject(next.object)]);
    host.disposed(next.object).unwrap();
    host.finish_close().unwrap();
}

#[test]
fn zero_linger_and_shutdown_cancel_tasks_without_waiting_for_a_linger_deadline() {
    for linger_ms in [0, 60_000] {
        let host = Host::new();
        let claim = lingering_object(&host, linger_ms);
        let task = host.begin_task(Owner::Object(claim.object)).unwrap();
        host.release(claim.reference).unwrap();
        if linger_ms == 0 {
            assert_eq!(host.drain(), [Action::CancelTask(task)]);
        } else {
            assert!(host.drain().is_empty());
            host.close();
            assert_eq!(host.drain(), [Action::CancelTask(task)]);
            assert_eq!(host.next_idle(), None);
        }
        host.finish_task(task).unwrap();
        assert_eq!(host.drain(), [Action::DisposeObject(claim.object)]);
        host.disposed(claim.object).unwrap();
        host.close();
        host.finish_close().unwrap();
    }
}

#[test]
fn a_task_finishing_during_linger_preserves_the_original_deadline() {
    let host = Host::new();
    let claim = lingering_object(&host, 100);
    let task = host.begin_task(Owner::Object(claim.object)).unwrap();
    host.release(claim.reference).unwrap();
    assert!(host.drain().is_empty());
    host.tick(40).unwrap();
    host.finish_task(task).unwrap();
    assert!(host.drain().is_empty());
    assert_eq!(host.next_idle(), Some(60));
    host.tick(100).unwrap();
    assert_eq!(host.drain(), [Action::DisposeObject(claim.object)]);
    host.disposed(claim.object).unwrap();
    host.close();
    host.finish_close().unwrap();
}

#[test]
fn shutdown_releases_only_the_dependents_of_each_object() {
    let host = Host::new();
    let mut orb = Orb::new("example", 1);
    orb.services.push(Service::new("example", ["read"]));
    let reload = host.prepare(vec![orb], vec![]).unwrap();
    host.commit(reload.id, vec![]).unwrap();
    let get = |key: &str| {
        host.acquire(
            Address {
                service: "example".into(),
                key: vec![key.into()],
                principal: "host".into(),
            },
            1,
            BTreeSet::new(),
        )
        .unwrap()
    };
    let consumer = get("consumer");
    let dependency = get("dependency");
    host.ready(consumer.object).unwrap();
    host.ready(dependency.object).unwrap();
    host.dependency(consumer.object, dependency.reference)
        .unwrap();
    host.close();
    assert_eq!(host.drain(), [Action::DisposeObject(consumer.object)]);
    host.disposed(consumer.object).unwrap();
    assert_eq!(host.drain(), [Action::DisposeObject(dependency.object)]);
    host.disposed(dependency.object).unwrap();
    host.finish_close().unwrap();
}

#[test]
fn a_forgotten_dependency_cannot_block_provider_shutdown() {
    let host = Host::new();
    let mut orb = Orb::new("example", 1);
    let mut service = Service::new("example", ["read"]);
    service.linger_ms = 100;
    orb.services.push(service);
    let reload = host.prepare(vec![orb], vec![]).unwrap();
    host.commit(reload.id, vec![]).unwrap();
    let get = |key: &str| {
        host.acquire(
            Address {
                service: "example".into(),
                key: vec![key.into()],
                principal: "host".into(),
            },
            1,
            BTreeSet::new(),
        )
        .unwrap()
    };
    let consumer = get("consumer");
    let provider = get("provider");
    host.ready(consumer.object).unwrap();
    host.ready(provider.object).unwrap();
    host.dependency(consumer.object, provider.reference)
        .unwrap();
    let scope = host.allocate_handle().unwrap();
    host.register_scope(crate::Scope {
        id: scope,
        owner: Owner::Host,
        orb: 0,
        parents: vec![],
        dependencies: vec![provider.reference],
        resources: vec![],
        state_version: None,
        migrate: false,
        active: true,
        closing: false,
    })
    .unwrap();
    host.release(provider.reference).unwrap();
    host.forget_reference(provider.reference).unwrap();
    assert!(
        !host
            .inner
            .borrow()
            .object_dependents
            .contains(&provider.object)
    );
    assert!(
        !host
            .inner
            .borrow()
            .scope_dependencies
            .contains(&provider.object)
    );
    host.close();
    let actions = host.drain();
    assert!(actions.contains(&Action::DisposeObject(provider.object)));
    assert!(actions.contains(&Action::DisposeObject(consumer.object)));
}

/// A live provider object with two declared methods and one claim requiring only `read`.
fn narrowed_claim(host: &Host) -> Acquisition {
    let mut orb = Orb::new("dup", 1);
    orb.services.push(Service::new("dup", ["read", "write"]));
    let reload = host.prepare(vec![orb], vec![]).unwrap();
    host.commit(reload.id, vec![]).unwrap();
    let claim = host
        .acquire(
            Address {
                service: "dup".into(),
                key: vec!["main".into()],
                principal: "host".into(),
            },
            1,
            BTreeSet::from(["read".to_owned()]),
        )
        .unwrap();
    host.ready(claim.object).unwrap();
    host.drain();
    claim
}

#[test]
fn duplicate_is_an_independent_claim_with_the_same_admission_and_no_activation() {
    let host = Host::new();
    let claim = narrowed_claim(&host);
    let objects = host.diagnostics().objects;
    let copy = host.duplicate(claim.reference).unwrap();
    assert_ne!(copy, claim.reference);
    // Same object, nothing activated, resolved or scheduled.
    assert_eq!(host.diagnostics().objects, objects);
    assert!(host.drain().is_empty());
    assert_eq!(
        host.reference_methods(copy).unwrap(),
        host.reference_methods(claim.reference).unwrap()
    );
    // The copy outlives the original and keeps the object live.
    host.release(claim.reference).unwrap();
    host.forget_reference(claim.reference).unwrap();
    assert!(host.drain().is_empty());
    assert_eq!(host.status(copy).unwrap(), Status::Live);
    let root = host.begin_root("host").unwrap();
    let call = host.begin_call(copy, root, "read").unwrap();
    // The required-method narrowing is copied, not re-derived from the service.
    let refused = host.begin_call(copy, root, "write").unwrap_err();
    assert_eq!(refused.code, Code::Forbidden);
    host.finish_call(call.id).unwrap();
    host.end_root(root).unwrap();
    host.release(copy).unwrap();
    assert!(host.drain().contains(&Action::DisposeObject(claim.object)));
}

#[cfg(feature = "views")]
#[test]
fn duplicate_copies_the_view_restriction() {
    let host = Host::new();
    let claim = narrowed_claim(&host);
    host.restrict(claim.reference, BTreeSet::new()).unwrap();
    let copy = host.duplicate(claim.reference).unwrap();
    assert!(host.reference_methods(copy).unwrap().is_empty());
    let root = host.begin_root("host").unwrap();
    let refused = host.begin_call(copy, root, "read").unwrap_err();
    assert_eq!(refused.code, Code::Forbidden);
    host.end_root(root).unwrap();
}

#[test]
fn duplicate_refuses_released_unknown_and_closing() {
    let host = Host::new();
    let claim = narrowed_claim(&host);
    let copy = host.duplicate(claim.reference).unwrap();
    host.release(claim.reference).unwrap();
    assert_eq!(
        host.duplicate(claim.reference).unwrap_err().code,
        Code::Released
    );
    assert_eq!(host.duplicate(9_999).unwrap_err().code, Code::Gone);
    // A closing host disposes live objects and admits no new claim, even from a live one.
    host.close();
    assert!(host.duplicate(copy).is_err());
}

#[test]
fn disposal_waiters_follow_exact_physical_instance_and_unregister_on_drop() {
    use std::{
        future::Future,
        pin::Pin,
        sync::{
            Arc,
            atomic::{AtomicUsize, Ordering},
        },
        task::{Context, Wake, Waker},
    };
    struct Count(AtomicUsize);
    impl Wake for Count {
        fn wake(self: Arc<Self>) {
            self.0.fetch_add(1, Ordering::SeqCst);
        }
    }
    let host = Host::new();
    let claim = lingering_object(&host, 0);
    let address = host.object_address(claim.object).unwrap();
    assert!(host.wait_for_disposal(&address).is_none());
    host.release(claim.reference).unwrap();
    let mut first = host.wait_for_disposal(&address).unwrap();
    let mut second = host.wait_for_disposal(&address).unwrap();
    let abandoned = host.wait_for_disposal(&address).unwrap();
    assert_eq!(host.inner.borrow().disposal_waiters[&claim.object].len(), 3);
    drop(abandoned);
    assert_eq!(host.inner.borrow().disposal_waiters[&claim.object].len(), 2);
    let count = Arc::new(Count(AtomicUsize::new(0)));
    let waker = Waker::from(count.clone());
    let mut context = Context::from_waker(&waker);
    assert!(Pin::new(&mut first).poll(&mut context).is_pending());
    assert!(Pin::new(&mut second).poll(&mut context).is_pending());
    assert_eq!(count.0.load(Ordering::SeqCst), 0);
    assert_eq!(host.drain(), [Action::DisposeObject(claim.object)]);
    assert_eq!(count.0.load(Ordering::SeqCst), 0);
    host.disposed(claim.object).unwrap();
    assert_eq!(count.0.load(Ordering::SeqCst), 2);
    assert!(host.inner.borrow().disposal_waiters.is_empty());
    assert!(Pin::new(&mut first).poll(&mut context).is_ready());
    assert!(Pin::new(&mut second).poll(&mut context).is_ready());
    assert!(host.wait_for_disposal(&address).is_none());
    drop((first, second));
    host.close();
    host.finish_close().unwrap();
}

#[test]
fn shutdown_wakes_disposal_waiters_before_physical_close_finishes() {
    use std::{future::Future, pin::Pin, task::Context};
    let host = Host::new();
    let claim = lingering_object(&host, 0);
    let address = host.object_address(claim.object).unwrap();
    host.release(claim.reference).unwrap();
    let mut waiting = host.wait_for_disposal(&address).unwrap();
    let mut context = Context::from_waker(std::task::Waker::noop());
    assert!(Pin::new(&mut waiting).poll(&mut context).is_pending());
    host.close();
    assert!(host.inner.borrow().disposal_waiters.is_empty());
    assert!(Pin::new(&mut waiting).poll(&mut context).is_ready());
    assert_eq!(host.diagnostics().objects, 1);
    host.disposed(claim.object).unwrap();
    host.finish_close().unwrap();
}