native-ipc-core 0.6.3

Platform-neutral, pointer-free protocol and sequencing primitives for native-ipc
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
use super::*;
use crate::layout::{
    AcknowledgementRouteSpec, Endpoint, LayoutLimits, RegionSetLayout, RegionSpec, RoleId,
    ValidationExpectations,
};
use std::alloc::{Layout, alloc_zeroed, dealloc};

#[derive(Debug)]
struct Allocation {
    base: NonNull<u8>,
    len: usize,
}

impl Allocation {
    fn new(len: usize) -> Self {
        let layout = Layout::from_size_align(len, 64).unwrap();
        let base = NonNull::new(unsafe { alloc_zeroed(layout) }).unwrap();
        Self { base, len }
    }
    fn bytes_mut(&mut self) -> &mut [u8] {
        unsafe { core::slice::from_raw_parts_mut(self.base.as_ptr(), self.len) }
    }
    fn bytes(&self) -> &[u8] {
        unsafe { core::slice::from_raw_parts(self.base.as_ptr(), self.len) }
    }
}
impl Drop for Allocation {
    fn drop(&mut self) {
        unsafe {
            dealloc(
                self.base.as_ptr(),
                Layout::from_size_align(self.len, 64).unwrap(),
            )
        }
    }
}

#[derive(Debug)]
struct ReaderWitness<'a>(&'a Allocation);
#[derive(Debug)]
struct WriterWitness<'a>(&'a mut Allocation);
unsafe impl ReadOnlyMapping for ReaderWitness<'_> {
    fn base(&self) -> NonNull<u8> {
        self.0.base
    }
    fn len(&self) -> usize {
        self.0.len
    }
}
unsafe impl SoleWriterMapping for WriterWitness<'_> {
    fn base(&self) -> NonNull<u8> {
        self.0.base
    }
    fn len(&self) -> usize {
        self.0.len
    }
}

#[test]
fn initialize_validate_bind_publish_recheck_and_acknowledge() {
    let producer = RoleId::new(1).unwrap();
    let acknowledger = RoleId::new(2).unwrap();
    let specs = [
        RegionSpec {
            role: producer,
            writer: Endpoint::Initiator,
            slot_count: 1,
            payload_bytes: 16,
            acknowledgement_count: 1,
        },
        RegionSpec {
            role: acknowledger,
            writer: Endpoint::Responder,
            slot_count: 1,
            payload_bytes: 16,
            acknowledgement_count: 1,
        },
    ];
    let route_specs = [
        AcknowledgementRouteSpec {
            owner: acknowledger,
            target: producer,
            slot_index: 0,
            cell_index: 0,
        },
        AcknowledgementRouteSpec {
            owner: producer,
            target: acknowledger,
            slot_index: 0,
            cell_index: 0,
        },
    ];
    let limits = LayoutLimits {
        maximum_mapping_size: 4096,
        maximum_slot_count: 2,
        maximum_acknowledgement_count: 2,
        maximum_payload_bytes: 64,
    };
    let set = RegionSetLayout::calculate([7; 32], 9, &specs, &route_specs, limits).unwrap();
    let producer_layout = set.region(producer).unwrap();
    let mut producer_memory = Allocation::new(producer_layout.total_size() as usize);
    producer_layout
        .encode_into(producer_memory.bytes_mut())
        .unwrap();
    let producer_validated = unsafe {
        ValidatedRegionLayout::validate(
            producer_memory.bytes(),
            ValidationExpectations {
                schema_id: [7; 32],
                generation: 9,
                role: producer,
                writer: Endpoint::Initiator,
                maximum_mapping_size: 4096,
            },
            &set,
        )
    }
    .unwrap();

    let ack_layout = set.region(acknowledger).unwrap();
    let mut ack_memory = Allocation::new(ack_layout.total_size() as usize);
    ack_layout.encode_into(ack_memory.bytes_mut()).unwrap();
    let ack_validated = unsafe {
        ValidatedRegionLayout::validate(
            ack_memory.bytes(),
            ValidationExpectations {
                schema_id: [7; 32],
                generation: 9,
                role: acknowledger,
                writer: Endpoint::Responder,
                maximum_mapping_size: 4096,
            },
            &set,
        )
    }
    .unwrap();

    {
        let mut writer = WriterRegion::new(
            WriterWitness(&mut producer_memory),
            producer_validated.clone(),
            set.clone(),
        )
        .unwrap();
        writer.publish(0, 1, None, b"ping").unwrap();
    }
    let reader = ReaderRegion::new(
        ReaderWitness(&producer_memory),
        producer_validated,
        set.clone(),
    )
    .unwrap();
    let observation = reader.slot(0).unwrap().observe(1).unwrap();
    reader.slot(0).unwrap().recheck(observation).unwrap();
    assert_eq!(reader.copy_payload(0, 1).unwrap(), b"ping");

    {
        let mut ack_writer = WriterRegion::new(
            WriterWitness(&mut ack_memory),
            ack_validated.clone(),
            set.clone(),
        )
        .unwrap();
        ack_writer
            .acknowledgement(producer, 0)
            .unwrap()
            .acknowledge(observation)
            .unwrap();
    }
    let ack_reader = ReaderRegion::new(ReaderWitness(&ack_memory), ack_validated, set).unwrap();
    let acknowledged = ack_reader.acknowledgement(producer, 0).unwrap().observe();
    assert_eq!(acknowledged.sequence(), 1);
    assert_eq!(acknowledged.slot_index(), 0);
    assert_eq!(acknowledged.cell_index(), 0);
}

const SLOT: u32 = 0;
const SEQUENCE: u64 = 1;
const PAYLOAD: &[u8] = b"ping";

/// Builds the two-role producer/acknowledger topology used by the fixtures
/// below, mirroring the shape composed inline in the test above.
fn build_topology(schema_id: [u8; 32], generation: u64) -> RegionSetLayout {
    build_topology_with_producer_capacity(schema_id, generation, 64)
}

fn build_topology_with_producer_capacity(
    schema_id: [u8; 32],
    generation: u64,
    producer_payload_bytes: u32,
) -> RegionSetLayout {
    let producer = RoleId::new(1).unwrap();
    let acknowledger = RoleId::new(2).unwrap();
    let specs = [
        RegionSpec {
            role: producer,
            writer: Endpoint::Initiator,
            slot_count: 1,
            payload_bytes: producer_payload_bytes,
            acknowledgement_count: 1,
        },
        RegionSpec {
            role: acknowledger,
            writer: Endpoint::Responder,
            slot_count: 1,
            payload_bytes: 16,
            acknowledgement_count: 1,
        },
    ];
    let route_specs = [
        AcknowledgementRouteSpec {
            owner: acknowledger,
            target: producer,
            slot_index: 0,
            cell_index: 0,
        },
        AcknowledgementRouteSpec {
            owner: producer,
            target: acknowledger,
            slot_index: 0,
            cell_index: 0,
        },
    ];
    let limits = LayoutLimits {
        maximum_mapping_size: 4096,
        maximum_slot_count: 2,
        maximum_acknowledgement_count: 2,
        maximum_payload_bytes: producer_payload_bytes.max(64),
    };
    RegionSetLayout::calculate(schema_id, generation, &specs, &route_specs, limits).unwrap()
}

/// Owned memory, validated layout, and topology for the producer role, with
/// `payload` already published at [`SLOT`]/[`SEQUENCE`].
struct ProducerFixture {
    memory: Allocation,
    layout: ValidatedRegionLayout,
    topology: RegionSetLayout,
}

fn build_producer_fixture(schema_id: [u8; 32], generation: u64, payload: &[u8]) -> ProducerFixture {
    build_producer_fixture_with_capacity(schema_id, generation, 64, payload)
}

fn build_producer_fixture_with_capacity(
    schema_id: [u8; 32],
    generation: u64,
    producer_payload_bytes: u32,
    payload: &[u8],
) -> ProducerFixture {
    let producer = RoleId::new(1).unwrap();
    let set = build_topology_with_producer_capacity(schema_id, generation, producer_payload_bytes);
    let producer_layout = set.region(producer).unwrap();
    let mut producer_memory = Allocation::new(producer_layout.total_size() as usize);
    producer_layout
        .encode_into(producer_memory.bytes_mut())
        .unwrap();
    let producer_validated = unsafe {
        ValidatedRegionLayout::validate(
            producer_memory.bytes(),
            ValidationExpectations {
                schema_id,
                generation,
                role: producer,
                writer: Endpoint::Initiator,
                maximum_mapping_size: 4096,
            },
            &set,
        )
    }
    .unwrap();

    {
        let mut writer = WriterRegion::new(
            WriterWitness(&mut producer_memory),
            producer_validated.clone(),
            set.clone(),
        )
        .unwrap();
        writer.publish(SLOT, SEQUENCE, None, payload).unwrap();
    }

    ProducerFixture {
        memory: producer_memory,
        layout: producer_validated,
        topology: set,
    }
}

#[test]
fn copy_payload_into_returns_payload_length_without_allocating() {
    let fixture = build_producer_fixture([7; 32], 9, PAYLOAD);
    let reader = ReaderRegion::new(
        ReaderWitness(&fixture.memory),
        fixture.layout.clone(),
        fixture.topology.clone(),
    )
    .unwrap();
    let mut destination = [0_u8; 64];
    let copied = reader
        .copy_payload_into(SLOT, SEQUENCE, &mut destination)
        .unwrap();
    assert_eq!(copied, PAYLOAD.len());
    assert_eq!(&destination[..copied], PAYLOAD);
}

#[test]
fn copy_payload_into_rejects_short_destination() {
    let fixture = build_producer_fixture([7; 32], 9, PAYLOAD);
    let reader = ReaderRegion::new(
        ReaderWitness(&fixture.memory),
        fixture.layout.clone(),
        fixture.topology.clone(),
    )
    .unwrap();
    let mut destination = [0_u8; 1]; // shorter than the published payload
    let error = reader
        .copy_payload_into(SLOT, SEQUENCE, &mut destination)
        .unwrap_err();
    assert!(matches!(
        error,
        BindingError::DestinationTooSmall { required, provided }
            if required == PAYLOAD.len() && provided == 1
    ));
}

#[test]
fn copy_payload_into_matches_copy_payload_bytes() {
    let fixture = build_producer_fixture([7; 32], 9, PAYLOAD);
    let reader = ReaderRegion::new(
        ReaderWitness(&fixture.memory),
        fixture.layout.clone(),
        fixture.topology.clone(),
    )
    .unwrap();
    let owned = reader.copy_payload(SLOT, SEQUENCE).unwrap();
    let mut destination = vec![0_u8; owned.len() + 8];
    let copied = reader
        .copy_payload_into(SLOT, SEQUENCE, &mut destination)
        .unwrap();
    assert_eq!(&destination[..copied], owned.as_slice());
}

#[test]
fn reader_region_into_mapping_returns_witness() {
    let fixture = build_producer_fixture([7; 32], 9, PAYLOAD);
    let reader = ReaderRegion::new(
        ReaderWitness(&fixture.memory),
        fixture.layout.clone(),
        fixture.topology.clone(),
    )
    .unwrap();
    let mapping = reader.into_mapping();
    // Rebind proves the witness is intact.
    let rebound =
        ReaderRegion::new(mapping, fixture.layout.clone(), fixture.topology.clone()).unwrap();
    let _ = rebound.slot(SLOT).unwrap();
}

#[test]
fn writer_region_into_mapping_returns_witness() {
    let mut fixture = build_producer_fixture([7; 32], 9, PAYLOAD);
    let writer = WriterRegion::new(
        WriterWitness(&mut fixture.memory),
        fixture.layout.clone(),
        fixture.topology.clone(),
    )
    .unwrap();
    let mapping = writer.into_mapping();
    let rebound =
        WriterRegion::new(mapping, fixture.layout.clone(), fixture.topology.clone()).unwrap();
    drop(rebound);
}

#[test]
fn reader_region_new_returns_witness_on_rejected_bind() {
    let fixture = build_producer_fixture([7; 32], 9, PAYLOAD);
    // A topology validated against a different schema does not match the
    // already-validated producer layout, so the bind is rejected.
    let mismatched_topology = build_topology([9; 32], 9);
    let (witness, error) = match ReaderRegion::new(
        ReaderWitness(&fixture.memory),
        fixture.layout.clone(),
        mismatched_topology,
    ) {
        Ok(_) => panic!("expected the mismatched topology bind to be rejected"),
        Err(pair) => pair,
    };
    assert!(matches!(error, BindingError::TopologyMismatch));
    // The rejected bind returns the witness intact; rebinding with the
    // correct topology proves it is still usable.
    let rebound =
        ReaderRegion::new(witness, fixture.layout.clone(), fixture.topology.clone()).unwrap();
    let _ = rebound.slot(SLOT).unwrap();
}

#[test]
fn writer_region_new_returns_witness_on_rejected_bind() {
    let mut fixture = build_producer_fixture([7; 32], 9, PAYLOAD);
    let mismatched_topology = build_topology([9; 32], 9);
    let (witness, error) = match WriterRegion::new(
        WriterWitness(&mut fixture.memory),
        fixture.layout.clone(),
        mismatched_topology,
    ) {
        Ok(_) => panic!("expected the mismatched topology bind to be rejected"),
        Err(pair) => pair,
    };
    assert!(matches!(error, BindingError::TopologyMismatch));
    // The rejected bind returns the witness intact; rebinding with the
    // correct topology and binding the producer slot proves it is still
    // usable.
    let mut rebound =
        WriterRegion::new(witness, fixture.layout.clone(), fixture.topology.clone()).unwrap();
    let _ = rebound.slot(SLOT).unwrap();
}

#[test]
fn writer_region_new_returns_usable_witness_on_mapping_size_mismatch() {
    let mut fixture = build_producer_fixture([7; 32], 9, PAYLOAD);
    let larger_fixture = build_producer_fixture_with_capacity([7; 32], 9, 128, PAYLOAD);
    let actual = fixture.layout.mapping_size();
    let expected = larger_fixture.layout.mapping_size();
    assert_ne!(actual, expected);

    let (witness, error) = match WriterRegion::new(
        WriterWitness(&mut fixture.memory),
        larger_fixture.layout,
        larger_fixture.topology,
    ) {
        Ok(_) => panic!("expected the differently sized layout bind to be rejected"),
        Err(pair) => pair,
    };
    assert!(matches!(
        error,
        BindingError::MappingSizeMismatch {
            expected: error_expected,
            actual: error_actual,
        } if error_expected == expected && error_actual == actual
    ));

    // The returned witness still owns the original mapping: rebinding it to
    // that mapping's layout and binding its producer slot proves it is usable.
    let mut rebound =
        WriterRegion::new(witness, fixture.layout.clone(), fixture.topology.clone()).unwrap();
    let _ = rebound.slot(SLOT).unwrap();
}