bacnet-objects 0.12.0

BACnet object model: traits, database, and standard object types
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! Buffer_Size writes and the application's purge of an Audit Log (#1238).

use std::sync::atomic::Ordering;
use std::sync::Arc;

use bacnet_types::bitstring::LogStatus;
use bacnet_types::constructed::{BACnetAuditLogDatum, BACnetAuditLogQueryParameters};
use bacnet_types::enums::{
    BACnetSuccessFilter, ErrorClass, ErrorCode, ObjectType, PropertyIdentifier,
};
use bacnet_types::error::Error;
use bacnet_types::primitives::{ObjectIdentifier, PropertyValue};

use crate::durable::{DurableWrites, PendingWrite, StageStep};
use crate::traits::BACnetObject;

use super::staging_tests::{
    block_on, log, notification, receipt, staged, staged_write, SlowPersistence, WAIT,
};
use super::{
    AuditBatchStage, AuditLogNotificationSink, AuditLogObject, AuditLogSnapshot, AuditLogStorage,
    ConfirmedAuditNotificationOutcome, MAX_AUDIT_RECORDS,
};

fn write(
    log: &mut AuditLogObject,
    property: PropertyIdentifier,
    value: PropertyValue,
) -> Result<(), Error> {
    log.write_property(property, None, value, None)
}

fn resize(log: &mut AuditLogObject, size: u64) -> Result<(), Error> {
    write(
        log,
        PropertyIdentifier::BUFFER_SIZE,
        PropertyValue::Unsigned(size),
    )
}

fn enable(log: &mut AuditLogObject, on: bool) {
    write(
        log,
        PropertyIdentifier::LOG_ENABLE,
        PropertyValue::Boolean(on),
    )
    .unwrap();
}

fn read(log: &AuditLogObject, property: PropertyIdentifier) -> PropertyValue {
    log.read_property(property, None).unwrap()
}

fn assert_operational_problem(error: Error) {
    assert!(
        matches!(error, Error::Protocol { class, code }
            if class == ErrorClass::DEVICE.to_raw() as u32
                && code == ErrorCode::OPERATIONAL_PROBLEM.to_raw() as u32),
        "expected DEVICE / OPERATIONAL_PROBLEM, got {error:?}"
    );
}

fn assert_property_error(error: Error, expected: ErrorCode) {
    assert!(
        matches!(error, Error::Protocol { class, code }
            if class == ErrorClass::PROPERTY.to_raw() as u32
                && code == expected.to_raw() as u32),
        "expected PROPERTY / {expected:?}, got {error:?}"
    );
}

/// The sequence numbers of the records the log holds, oldest first: the
/// Log_Buffer that ReadRange pages.
fn held(log: &AuditLogObject) -> Vec<u64> {
    log.retained_records()
        .iter()
        .map(|record| record.sequence_number)
        .collect()
}

/// The log-status flags of the record with `sequence_number`.
fn status_of(log: &AuditLogObject, sequence_number: u64) -> LogStatus {
    let record = log
        .records()
        .iter()
        .find(|record| record.sequence_number == sequence_number)
        .expect("the record is held");
    match &record.record.datum {
        BACnetAuditLogDatum::LogStatus(status) => *status,
        other => panic!("record {sequence_number} is not a log-status record: {other:?}"),
    }
}

/// The sequence numbers an AuditLogQuery for every report on target Device 2
/// returns, newest first.
fn queried(log: &AuditLogObject) -> Vec<u64> {
    let parameters = BACnetAuditLogQueryParameters::ByTarget {
        target_device_identifier: ObjectIdentifier::new(ObjectType::DEVICE, 2).unwrap(),
        target_device_address: None,
        target_object_identifier: None,
        target_property_identifier: None,
        target_array_index: None,
        target_priority: None,
        operations: None,
        successful_actions_only: BACnetSuccessFilter::ALL,
    };
    log.query(&parameters, None, 100)
        .records
        .iter()
        .map(|record| record.sequence_number)
        .collect()
}

/// Store one target report for each invoke ID, each its own record.
fn fill(log: &mut AuditLogObject, invoke_ids: std::ops::Range<u8>) {
    for invoke_id in invoke_ids {
        log.store_notifications(&[notification(invoke_id)], 3_000)
            .unwrap();
    }
}

/// The log serves what `before` holds, and storage still holds it.
fn assert_unchanged(log: &AuditLogObject, storage: &SlowPersistence, before: &AuditLogSnapshot) {
    log.wait_for_commits();
    assert_eq!(log.generation(), before.generation);
    assert_eq!(log.buffer_size(), before.capacity);
    assert_eq!(log.log_enable(), before.log_enable);
    assert_eq!(log.total_record_count(), before.total_record_count);
    assert_eq!(
        log.records().iter().cloned().collect::<Vec<_>>(),
        before.records
    );
    assert_eq!(&storage.committed(), before);
}

fn reopen(storage: &Arc<SlowPersistence>, configured: u32) -> AuditLogObject {
    let mut log = AuditLogObject::new(1, "audit", configured, Arc::clone(storage) as _).unwrap();
    log.bind_clock_internal(Some(Arc::new(super::staging_tests::FixedClock)));
    log
}

#[test]
fn buffer_size_takes_a_write_only_while_logging_is_off() {
    let (mut log, storage) = log();
    fill(&mut log, 1..4);
    let before = storage.committed();
    // While logging is on every write is refused, the current size too.
    for value in [
        PropertyValue::Unsigned(10),
        PropertyValue::Unsigned(5),
        PropertyValue::Boolean(true),
    ] {
        assert_property_error(
            write(&mut log, PropertyIdentifier::BUFFER_SIZE, value).unwrap_err(),
            ErrorCode::WRITE_ACCESS_DENIED,
        );
    }
    assert_unchanged(&log, &storage, &before);

    enable(&mut log, false);
    let before = storage.committed();
    for (value, code) in [
        (PropertyValue::Boolean(true), ErrorCode::INVALID_DATA_TYPE),
        (PropertyValue::Real(5.0), ErrorCode::INVALID_DATA_TYPE),
        (
            PropertyValue::Unsigned(u64::from(MAX_AUDIT_RECORDS) + 1),
            ErrorCode::VALUE_OUT_OF_RANGE,
        ),
        // Clause 12.64.9 sets 2^32-1 aside for a size bounded only by memory.
        (
            PropertyValue::Unsigned(u64::from(u32::MAX)),
            ErrorCode::VALUE_OUT_OF_RANGE,
        ),
        (
            PropertyValue::Unsigned(u64::from(u32::MAX) + 1),
            ErrorCode::VALUE_OUT_OF_RANGE,
        ),
    ] {
        assert_property_error(
            write(&mut log, PropertyIdentifier::BUFFER_SIZE, value).unwrap_err(),
            code,
        );
    }
    // Writing the current size commits nothing.
    resize(&mut log, 10).unwrap();
    assert_unchanged(&log, &storage, &before);

    // A larger buffer keeps every record, and storage has it first.
    resize(&mut log, u64::from(MAX_AUDIT_RECORDS)).unwrap();
    assert_eq!(
        read(&log, PropertyIdentifier::BUFFER_SIZE),
        PropertyValue::Unsigned(u64::from(MAX_AUDIT_RECORDS))
    );
    assert_eq!(held(&log), [1, 2, 3, 4]);
    assert_eq!(storage.committed().capacity, MAX_AUDIT_RECORDS);
    assert_eq!(storage.committed().generation, before.generation + 1);

    enable(&mut log, true);
    assert_property_error(
        resize(&mut log, 4).unwrap_err(),
        ErrorCode::WRITE_ACCESS_DENIED,
    );
    assert_eq!(log.buffer_size(), MAX_AUDIT_RECORDS);
}

#[test]
fn a_shrink_below_the_record_count_keeps_the_newest_records() {
    let (mut log, storage) = log();
    fill(&mut log, 1..6);
    enable(&mut log, false);
    assert_eq!(held(&log), [1, 2, 3, 4, 5, 6]);

    resize(&mut log, 2).unwrap();
    assert_eq!(held(&log), [5, 6]);
    assert_eq!(status_of(&log, 6), LogStatus::LOG_DISABLED);
    assert_eq!(
        read(&log, PropertyIdentifier::RECORD_COUNT),
        PropertyValue::Unsigned(2)
    );
    assert_eq!(
        read(&log, PropertyIdentifier::TOTAL_RECORD_COUNT),
        PropertyValue::Unsigned(6)
    );
    // AuditLogQuery scans the same ring: only the newest report is left.
    assert_eq!(queried(&log), [5]);
    let committed = storage.committed();
    assert_eq!(committed.capacity, 2);
    assert_eq!(committed.total_record_count, 6);
    assert_eq!(
        committed
            .records
            .iter()
            .map(|record| record.sequence_number)
            .collect::<Vec<_>>(),
        [5, 6]
    );

    // Reopened, the log keeps the written size over the configured one.
    drop(log);
    let mut log = reopen(&storage, 10);
    assert_eq!(log.buffer_size(), 2);
    assert_eq!(held(&log), [5, 6]);

    // Growing again makes room but brings nothing back.
    resize(&mut log, 4).unwrap();
    enable(&mut log, true);
    assert_eq!(held(&log), [5, 6, 7]);

    // Down to zero only the count is left, and a log grown from zero holds
    // no records until the next one arrives; storage loads it so.
    enable(&mut log, false);
    resize(&mut log, 0).unwrap();
    assert!(held(&log).is_empty());
    resize(&mut log, 3).unwrap();
    assert!(held(&log).is_empty());
    assert_eq!(log.total_record_count(), 8);
    drop(log);
    let mut log = reopen(&storage, 10);
    assert_eq!(log.buffer_size(), 3);
    assert!(held(&log).is_empty());
    assert_eq!(log.total_record_count(), 8);
    enable(&mut log, true);
    assert_eq!(held(&log), [9]);
}

#[test]
fn a_purge_leaves_one_buffer_purged_record_and_nothing_to_query() {
    let (mut log, storage) = log();
    let batch =
        staged(log.stage_notification_batch(&[notification(1)], 3_000, Some(receipt(b"kept"))));
    block_on(batch.saved());
    log.finish_notification_batch(batch).unwrap();
    fill(&mut log, 2..4);
    assert_eq!(queried(&log), [3, 2, 1]);

    // A peer cannot purge it: Record_Count stays read-only (Clause 12.64.11).
    let before = storage.committed();
    assert_property_error(
        write(
            &mut log,
            PropertyIdentifier::RECORD_COUNT,
            PropertyValue::Unsigned(0),
        )
        .unwrap_err(),
        ErrorCode::WRITE_ACCESS_DENIED,
    );
    assert_unchanged(&log, &storage, &before);

    assert_eq!(log.purge().unwrap(), 4);
    assert_eq!(held(&log), [4]);
    assert_eq!(status_of(&log, 4), LogStatus::BUFFER_PURGED);
    assert_eq!(
        read(&log, PropertyIdentifier::RECORD_COUNT),
        PropertyValue::Unsigned(1)
    );
    assert_eq!(
        read(&log, PropertyIdentifier::TOTAL_RECORD_COUNT),
        PropertyValue::Unsigned(4)
    );
    // AuditLogQuery returns notifications only, and none is left.
    assert!(queried(&log).is_empty());
    let committed = storage.committed();
    assert_eq!(
        committed.records,
        log.records().iter().cloned().collect::<Vec<_>>()
    );
    assert_eq!(committed.total_record_count, 4);
    assert_eq!(committed.generation, before.generation + 1);

    // The completed receipts survive: the confirmed batch sent again is still a
    // duplicate, and a new report follows the purge record.
    assert!(matches!(
        log.stage_notification_batch(&[notification(1)], 3_000, Some(receipt(b"kept"))),
        Ok(AuditBatchStage::Done(
            ConfirmedAuditNotificationOutcome::Duplicate,
            false
        ))
    ));
    fill(&mut log, 9..10);
    assert_eq!(held(&log), [4, 5]);
    assert_eq!(queried(&log), [5]);

    // Purged while logging is off, the record says that too.
    enable(&mut log, false);
    assert_eq!(log.purge().unwrap(), 7);
    assert_eq!(held(&log), [7]);
    assert_eq!(
        status_of(&log, 7),
        LogStatus::BUFFER_PURGED | LogStatus::LOG_DISABLED
    );
}

#[test]
fn a_purge_without_a_valid_clock_changes_nothing() {
    let storage = Arc::new(SlowPersistence::default());
    let mut log = AuditLogObject::new(1, "audit", 10, Arc::clone(&storage) as _).unwrap();
    let before = storage.committed();
    assert_operational_problem(log.purge().unwrap_err());
    assert!(matches!(log.stage_purge(), StageStep::Skip));
    assert_unchanged(&log, &storage, &before);
}

#[test]
fn a_failing_store_refuses_a_resize_or_purge_and_leaves_the_log_unchanged() {
    let (mut log, storage) = log();
    fill(&mut log, 1..4);
    enable(&mut log, false);
    let before = storage.committed();
    storage.fail.store(true, Ordering::SeqCst);

    // In place, as application code holding the guard makes them. Each is
    // refused as a change the device cannot make now.
    assert_operational_problem(resize(&mut log, 1).unwrap_err());
    assert_unchanged(&log, &storage, &before);
    assert_operational_problem(log.purge().unwrap_err());
    assert_unchanged(&log, &storage, &before);
    assert_operational_problem(
        write(
            &mut log,
            PropertyIdentifier::LOG_ENABLE,
            PropertyValue::Boolean(true),
        )
        .unwrap_err(),
    );
    assert_unchanged(&log, &storage, &before);

    // Staged, as the server makes them.
    let wait = staged_write(log.stage_write(
        PropertyIdentifier::BUFFER_SIZE,
        None,
        &PropertyValue::Unsigned(1),
    ));
    block_on(wait.clone());
    assert_operational_problem(resize(&mut log, 1).unwrap_err());
    log.release_staged_write(&wait);
    assert_unchanged(&log, &storage, &before);
    let wait = staged_write(log.stage_purge());
    block_on(wait.clone());
    assert_operational_problem(log.commit_purge().unwrap_err());
    log.release_staged_write(&wait);
    assert_unchanged(&log, &storage, &before);

    // With storage back the same changes go through.
    storage.fail.store(false, Ordering::SeqCst);
    resize(&mut log, 1).unwrap();
    assert_eq!(held(&log), [4]);
    assert_eq!(log.purge().unwrap(), 5);
    assert_eq!(held(&log), [5]);
}

#[test]
fn a_staged_resize_or_purge_commits_while_the_log_serves_its_committed_state() {
    let (mut log, storage) = log();
    fill(&mut log, 1..4);
    enable(&mut log, false);
    let generation = log.generation();
    let commits = storage.commits.load(Ordering::SeqCst);
    let (started, go) = storage.hold();

    let wait = staged_write(log.stage_write(
        PropertyIdentifier::BUFFER_SIZE,
        None,
        &PropertyValue::Unsigned(2),
    ));
    assert_eq!(started.recv_timeout(WAIT).unwrap(), generation + 1);
    assert_eq!(
        read(&log, PropertyIdentifier::BUFFER_SIZE),
        PropertyValue::Unsigned(10)
    );
    assert_eq!(held(&log), [1, 2, 3, 4]);
    go.send(()).unwrap();
    block_on(wait.clone());
    resize(&mut log, 2).unwrap();
    log.release_staged_write(&wait);
    assert_eq!(log.buffer_size(), 2);
    assert_eq!(held(&log), [3, 4]);

    let wait = staged_write(log.stage_purge());
    assert_eq!(started.recv_timeout(WAIT).unwrap(), generation + 2);
    assert_eq!(held(&log), [3, 4]);
    go.send(()).unwrap();
    block_on(wait.clone());
    log.commit_purge().unwrap();
    log.release_staged_write(&wait);
    assert_eq!(held(&log), [5]);
    assert_eq!(
        status_of(&log, 5),
        LogStatus::BUFFER_PURGED | LogStatus::LOG_DISABLED
    );
    assert_eq!(log.generation(), generation + 2);
    // Each request took its staged commit and committed nothing more.
    assert_eq!(storage.commits.load(Ordering::SeqCst), commits + 2);
}

#[test]
fn a_purge_staged_behind_a_batch_lands_after_it() {
    let (mut log, storage) = log();
    let (started, go) = storage.hold();
    let batch =
        staged(log.stage_notification_batch(&[notification(1)], 3_000, Some(receipt(b"first"))));
    started.recv_timeout(WAIT).unwrap();
    // The purge waits for the batch's commit, then builds on the batch.
    let StageStep::Busy(wait) = log.stage_purge() else {
        panic!("the purge should wait while the batch commits");
    };
    assert!(!wait.is_ready());
    go.send(()).unwrap();
    block_on(wait);
    let purge = staged_write(log.stage_purge());
    started.recv_timeout(WAIT).unwrap();
    go.send(()).unwrap();
    block_on(purge.clone());
    log.commit_purge().unwrap();
    log.release_staged_write(&purge);

    // The batch's request still gets its outcome, and its record went with
    // the purge.
    assert_eq!(
        log.finish_notification_batch(batch).unwrap(),
        (ConfirmedAuditNotificationOutcome::Stored, true)
    );
    assert_eq!(held(&log), [2]);
    assert_eq!(status_of(&log, 2), LogStatus::BUFFER_PURGED);
    assert!(queried(&log).is_empty());
    assert_eq!(storage.committed().total_record_count, 2);
}

#[test]
fn a_batch_that_arrives_during_a_purge_lands_after_it() {
    let (mut log, storage) = log();
    fill(&mut log, 1..2);
    let (started, go) = storage.hold();
    let purge = staged_write(log.stage_purge());
    started.recv_timeout(WAIT).unwrap();
    // The batch waits until the purge's request takes the purge, even once
    // the purge's commit has run.
    let AuditBatchStage::Busy(wait) = log
        .stage_notification_batch(&[notification(2)], 3_000, None)
        .unwrap()
    else {
        panic!("the batch should wait while the purge is staged");
    };
    go.send(()).unwrap();
    block_on(purge.clone());
    assert!(!wait.is_ready());
    log.commit_purge().unwrap();
    log.release_staged_write(&purge);
    block_on(wait);

    let batch = staged(log.stage_notification_batch(&[notification(2)], 3_000, None));
    started.recv_timeout(WAIT).unwrap();
    go.send(()).unwrap();
    block_on(batch.saved());
    assert_eq!(
        log.finish_notification_batch(batch).unwrap(),
        (ConfirmedAuditNotificationOutcome::Stored, true)
    );
    assert_eq!(held(&log), [2, 3]);
    assert_eq!(status_of(&log, 2), LogStatus::BUFFER_PURGED);
    assert_eq!(queried(&log), [3]);
}

#[test]
fn staging_skips_a_resize_the_write_would_refuse_or_not_need() {
    let (mut log, storage) = log();
    let skipped = |step| matches!(step, StageStep::Skip);
    let size = |size| PropertyValue::Unsigned(size);
    assert!(skipped(log.stage_write(
        PropertyIdentifier::BUFFER_SIZE,
        None,
        &size(5)
    )));
    enable(&mut log, false);
    let commits = storage.commits.load(Ordering::SeqCst);
    for (property, index, value) in [
        (PropertyIdentifier::BUFFER_SIZE, None, size(10)),
        (
            PropertyIdentifier::BUFFER_SIZE,
            None,
            PropertyValue::Boolean(true),
        ),
        (
            PropertyIdentifier::BUFFER_SIZE,
            None,
            size(u64::from(MAX_AUDIT_RECORDS) + 1),
        ),
        (PropertyIdentifier::BUFFER_SIZE, Some(1), size(5)),
        (PropertyIdentifier::RECORD_COUNT, None, size(0)),
    ] {
        assert!(
            skipped(log.stage_write(property, index, &value)),
            "{property:?} {index:?} {value:?}"
        );
    }
    log.wait_for_commits();
    assert_eq!(storage.commits.load(Ordering::SeqCst), commits);
}

#[test]
fn an_object_without_a_log_refuses_a_purge() {
    let mut forwarder =
        crate::notification_forwarder::NotificationForwarderObject::new(1, "NF").unwrap();
    let writes = forwarder.durable_writes_internal().unwrap();
    assert!(matches!(writes.stage_purge(), StageStep::Skip));
    let error = writes.commit_purge().unwrap_err();
    assert!(
        matches!(error, Error::Protocol { class, code }
            if class == ErrorClass::OBJECT.to_raw() as u32
                && code == ErrorCode::OPTIONAL_FUNCTIONALITY_NOT_SUPPORTED.to_raw() as u32),
        "{error:?}"
    );
}

fn pending(property: PropertyIdentifier, value: PropertyValue) -> PendingWrite {
    PendingWrite {
        property,
        array_index: None,
        value,
    }
}

/// A WritePropertyMultiple that turns logging off, writes Description and
/// then resizes.
fn off_then_resize(size: u64) -> [PendingWrite; 3] {
    [
        pending(
            PropertyIdentifier::LOG_ENABLE,
            PropertyValue::Boolean(false),
        ),
        pending(
            PropertyIdentifier::DESCRIPTION,
            PropertyValue::CharacterString("resized".into()),
        ),
        pending(
            PropertyIdentifier::BUFFER_SIZE,
            PropertyValue::Unsigned(size),
        ),
    ]
}

#[test]
fn a_request_folds_its_log_enable_and_buffer_size_writes_into_one_commit() {
    let (mut log, storage) = log();
    fill(&mut log, 1..4);
    let generation = log.generation();
    let commits = storage.commits.load(Ordering::SeqCst);
    let (started, go) = storage.hold();
    let wait = staged_write(log.stage_writes(&off_then_resize(2)));
    assert_eq!(started.recv_timeout(WAIT).unwrap(), generation + 1);
    // One commit holds both changes, while the log serves what it had.
    assert!(log.log_enable());
    assert_eq!(log.buffer_size(), 10);
    assert_eq!(held(&log), [1, 2, 3]);
    go.send(()).unwrap();
    block_on(wait.clone());
    let committed = storage.committed();
    assert!(!committed.log_enable);
    assert_eq!(committed.capacity, 2);

    // The request makes its writes in order, each taking its own step.
    enable(&mut log, false);
    assert_eq!(log.buffer_size(), 10);
    assert_eq!(held(&log), [1, 2, 3, 4]);
    write(
        &mut log,
        PropertyIdentifier::DESCRIPTION,
        PropertyValue::CharacterString("resized".into()),
    )
    .unwrap();
    resize(&mut log, 2).unwrap();
    log.release_staged_write(&wait);
    log.wait_for_commits();
    assert_eq!(held(&log), [3, 4]);
    assert_eq!(log.generation(), generation + 1);
    assert_eq!(storage.commits.load(Ordering::SeqCst), commits + 1);
    assert_eq!(storage.committed(), committed);
}

#[test]
fn a_request_that_stops_between_its_staged_writes_puts_the_served_log_in_storage() {
    let (mut log, storage) = log();
    fill(&mut log, 1..4);
    let wait = staged_write(log.stage_writes(&off_then_resize(2)));
    block_on(wait.clone());
    assert_eq!(storage.committed().capacity, 2);
    // Logging goes off, then the request fails before its resize.
    enable(&mut log, false);
    log.release_staged_write(&wait);
    log.wait_for_commits();
    let committed = storage.committed();
    assert!(!committed.log_enable);
    assert_eq!(committed.capacity, 10);
    assert_eq!(
        committed.records,
        log.records().iter().cloned().collect::<Vec<_>>()
    );
    drop(log);
    let log = reopen(&storage, 10);
    assert_eq!(log.buffer_size(), 10);
    assert!(!log.log_enable());
    assert_eq!(held(&log), [1, 2, 3, 4]);
}

#[test]
fn a_request_that_resizes_before_turning_logging_off_stages_nothing() {
    let (mut log, storage) = log();
    let commits = storage.commits.load(Ordering::SeqCst);
    // The resize is refused while logging is on, so the request ends there.
    let writes = [
        pending(PropertyIdentifier::BUFFER_SIZE, PropertyValue::Unsigned(2)),
        pending(
            PropertyIdentifier::LOG_ENABLE,
            PropertyValue::Boolean(false),
        ),
    ];
    assert!(matches!(log.stage_writes(&writes), StageStep::Skip));
    log.wait_for_commits();
    assert_eq!(storage.commits.load(Ordering::SeqCst), commits);
}

#[test]
fn a_request_goes_on_past_a_null_the_log_leaves_unchanged() {
    let null = |property| pending(property, PropertyValue::Null);
    // The server leaves a NULL to either property as it is (#1396), so the
    // writes after one still stage. With logging off, a NULL resize is no
    // refusal either.
    let (mut log, storage) = log();
    let writes = [
        null(PropertyIdentifier::LOG_ENABLE),
        pending(
            PropertyIdentifier::LOG_ENABLE,
            PropertyValue::Boolean(false),
        ),
        null(PropertyIdentifier::BUFFER_SIZE),
        pending(PropertyIdentifier::BUFFER_SIZE, PropertyValue::Unsigned(2)),
    ];
    let wait = staged_write(log.stage_writes(&writes));
    block_on(wait.clone());
    let committed = storage.committed();
    assert!(!committed.log_enable);
    assert_eq!(committed.capacity, 2);
    log.release_staged_write(&wait);
    log.wait_for_commits();

    // With logging on, a resize is refused whatever its value, a NULL too,
    // so the request ends there.
    let (mut log, storage) = self::log();
    let commits = storage.commits.load(Ordering::SeqCst);
    let writes = [
        null(PropertyIdentifier::BUFFER_SIZE),
        pending(
            PropertyIdentifier::LOG_ENABLE,
            PropertyValue::Boolean(false),
        ),
    ];
    assert!(matches!(log.stage_writes(&writes), StageStep::Skip));
    log.wait_for_commits();
    assert_eq!(storage.commits.load(Ordering::SeqCst), commits);
}