apis 0.5.13

Reactive, session-oriented, asynchronous process-calculus framework
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
use std;
use strum;
use vec_map;
use crate::{session, Message};

///////////////////////////////////////////////////////////////////////////////
//  submodules
///////////////////////////////////////////////////////////////////////////////

pub mod backend;

///////////////////////////////////////////////////////////////////////////////
//  structs
///////////////////////////////////////////////////////////////////////////////

/// Main channel struct.
pub struct Channel <CTX : session::Context> {
  pub def          : Def <CTX>,
  pub sourcepoints : vec_map::VecMap <Box <dyn Sourcepoint <CTX>>>,
  pub endpoints    : vec_map::VecMap <Box <dyn Endpoint    <CTX>>>
}

/// Channel definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Def <CTX : session::Context> {
  id              : CTX::CID,
  kind            : Kind,
  producers       : Vec <CTX::PID>,
  consumers       : Vec <CTX::PID>,
  message_type_id : CTX::MID
}

/// Sender disconnected, no further messages will ever be received.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RecvError;

/// Receiver disconnected, message will never be deliverable.
// NB: this representation may need to be changed if a channel backend is used
// that doesn't return the message on a send error
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct SendError <M> (pub M);

///////////////////////////////////////////////////////////////////////////////
//  enums
///////////////////////////////////////////////////////////////////////////////

/// Channel kind defines the connection topology of a channel.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Kind {

  /// An SPSC stream.
  ///
  /// ```text
  /// *----->*
  /// ```
  Simplex,

  /// A sink accepting a single message type from producers.
  ///
  /// ```text
  /// *-----\
  ///        v
  /// *----->*
  ///        ^
  /// *-----/
  /// ```
  Sink,

  /// A source capable of sending messages of a single type directly to
  /// individual consumers.
  ///
  /// ```text
  ///   ---->*
  ///  /
  /// *----->*
  ///  \
  ///   ---->*
  /// ```
  Source

}

/// Error defining `Def`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DefineError {
  ProducerEqConsumer,
  DuplicateProducer,
  DuplicateConsumer,
  MultipleProducers,
  MultipleConsumers,
  ZeroProducers,
  ZeroConsumers
}

/// Error creating concrete `Channel` instance from a given channel def.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CreateError {
  KindMismatch
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TryRecvError {
  Empty,
  /// Sender disconnected, no further messages will be received.
  Disconnected
}

///////////////////////////////////////////////////////////////////////////////
//  traits
///////////////////////////////////////////////////////////////////////////////

pub type IdReprType = u16;
/// Unique identifier with a total mapping to channel infos.
pub trait Id <CTX> : Clone + Ord + Into <usize> + TryFrom <IdReprType> +
  std::fmt::Debug + strum::IntoEnumIterator
where
  CTX : session::Context <CID=Self>
{
  fn def             (&self) -> Def <CTX>;
  fn message_type_id (&self) -> CTX::MID;
  /// Create a new channel.
  fn create (_ : Def <CTX>) -> Channel <CTX>;
}

/// Interface for a channel sourcepoint.
pub trait Sourcepoint <CTX : session::Context> : Send {
  fn send    (&self, message : CTX::GMSG) -> Result <(), SendError <CTX::GMSG>>;
  fn send_to (&self, message : CTX::GMSG, recipient : CTX::PID)
    -> Result <(), SendError <CTX::GMSG>>;
}

/// Interface for a channel endpoint.
pub trait Endpoint <CTX : session::Context> : Send {
  fn recv     (&self) -> Result <CTX::GMSG, RecvError>;
  fn try_recv (&self) -> Result <CTX::GMSG, TryRecvError>;
}

///////////////////////////////////////////////////////////////////////////////
//  impls
///////////////////////////////////////////////////////////////////////////////

impl <CTX : session::Context> Def <CTX> {
  /// The only method for creating valid channel def struct; validates
  /// specification of sourcepoints and endpoints for *well-formedness* (at
  /// least one process at each end, no duplicates or self-loops) and
  /// *compatibility* with channel kind (restricted to single process
  /// sourcepoint or endpoint where appropriate).
  ///
  /// # Errors
  ///
  /// Zero producers or consumers:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # fn main() {
  /// let result = channel::Def::<Mycontext>::define (
  ///   ChannelId::X,
  ///   channel::Kind::Sink,
  ///   vec![],
  ///   vec![ProcessId::B]);
  /// assert_eq!(result, Err (vec![channel::DefineError::ZeroProducers]));
  /// let result = channel::Def::<Mycontext>::define (
  ///   ChannelId::X,
  ///   channel::Kind::Sink,
  ///   vec![ProcessId::A],
  ///   vec![]);
  /// assert_eq!(result, Err (vec![channel::DefineError::ZeroConsumers]));
  /// # }
  /// ```
  ///
  /// Producer equals consumer:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # fn main() {
  /// let result = channel::Def::<Mycontext>::define (
  ///   ChannelId::X,
  ///   channel::Kind::Sink,
  ///   vec![ProcessId::A, ProcessId::B],
  ///   vec![ProcessId::A]);
  /// assert_eq!(result, Err (vec![channel::DefineError::ProducerEqConsumer]));
  /// # }
  /// ```
  ///
  /// Duplicate producer:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # fn main() {
  /// let result = channel::Def::<Mycontext>::define (
  ///   ChannelId::X,
  ///   channel::Kind::Sink,
  ///   vec![ProcessId::A, ProcessId::A],
  ///   vec![ProcessId::B]);
  /// assert_eq!(result, Err (vec![channel::DefineError::DuplicateProducer]));
  /// # }
  /// ```
  ///
  /// Duplicate consumer:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # fn main() {
  /// let result = channel::Def::<Mycontext>::define (
  ///   ChannelId::X,
  ///   channel::Kind::Source,
  ///   vec![ProcessId::A],
  ///   vec![ProcessId::B, ProcessId::B]);
  /// assert_eq!(result, Err (vec![channel::DefineError::DuplicateConsumer]));
  /// # }
  /// ```
  ///
  /// Kind does not support multiple producers and/or consumers:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # fn main() {
  /// let result = channel::Def::<Mycontext>::define (
  ///   ChannelId::X,
  ///   channel::Kind::Source,
  ///   vec![ProcessId::A, ProcessId::B],
  ///   vec![ProcessId::C, ProcessId::D]);
  /// assert_eq!(result, Err (vec![channel::DefineError::MultipleProducers]));
  /// let result = channel::Def::<Mycontext>::define (
  ///   ChannelId::X,
  ///   channel::Kind::Simplex,
  ///   vec![ProcessId::A],
  ///   vec![ProcessId::B, ProcessId::C]);
  /// assert_eq!(result, Err (vec![channel::DefineError::MultipleConsumers]));
  /// # }
  /// ```

  pub fn define (
    id        : CTX::CID,
    kind      : Kind,
    producers : Vec <CTX::PID>,
    consumers : Vec <CTX::PID>
  ) -> Result <Self, Vec <DefineError>> {
    let message_type_id = id.message_type_id();
    let def = Def {
      id, kind, producers, consumers, message_type_id
    };
    def.validate_roles() ?;
    Ok (def)
  }

  pub const fn id (&self) -> &CTX::CID {
    &self.id
  }

  pub const fn kind (&self) -> &Kind {
    &self.kind
  }

  pub const fn producers (&self) -> &Vec <CTX::PID> {
    &self.producers
  }

  pub const fn consumers (&self) -> &Vec <CTX::PID> {
    &self.consumers
  }

  pub fn to_channel <M> (self) -> Channel <CTX> where
    CTX : 'static,
    M   : Message <CTX> + 'static
  {
    match self.kind {
      Kind::Simplex => backend::Simplex::<CTX, M>::try_from (self).unwrap().into(),
      Kind::Sink    => backend::Sink::<CTX, M>::try_from (self).unwrap().into(),
      Kind::Source  => backend::Source::<CTX, M>::try_from (self).unwrap().into()
    }
  }

  fn validate_roles (&self) -> Result <(), Vec <DefineError>> {
    let mut errors = Vec::new();

    // zero producers
    if self.producers.is_empty() {
      errors.push (DefineError::ZeroProducers);
    }

    // zero consumers
    if self.consumers.is_empty() {
      errors.push (DefineError::ZeroConsumers);
    }

    // duplicate sourcepoints
    let mut producers_dedup = self.producers.clone();
    producers_dedup.as_mut_slice().sort();
    producers_dedup.dedup_by (|x,y| x == y);
    if producers_dedup.len() < self.producers.len() {
      errors.push (DefineError::DuplicateProducer);
    }

    // duplicate endpoints
    let mut consumers_dedup = self.consumers.clone();
    consumers_dedup.as_mut_slice().sort();
    consumers_dedup.dedup_by (|x,y| x == y);
    if consumers_dedup.len() < self.consumers.len() {
      errors.push (DefineError::DuplicateConsumer);
    }

    // self-loops
    let mut producers_and_consumers = producers_dedup.clone();
    producers_and_consumers.append (&mut consumers_dedup.clone());
    producers_and_consumers.as_mut_slice().sort();
    producers_and_consumers.dedup_by (|x,y| x == y);
    if producers_and_consumers.len()
      < producers_dedup.len() + consumers_dedup.len()
    {
      errors.push (DefineError::ProducerEqConsumer);
    }

    // validate channel kind
    if let Err (mut errs)
      = self.kind.validate_roles::<CTX> (&self.producers, &self.consumers)
    {
      errors.append (&mut errs);
    }

    if !errors.is_empty() {
      Err (errors)
    } else {
      Ok (())
    }
  }

}

impl Kind {
  /// Ensures number of producers and consumers is valid for this kind of channel.
  fn validate_roles <CTX : session::Context> (&self,
    producers : &[CTX::PID], consumers : &[CTX::PID]
  ) -> Result <(), Vec <DefineError>> {
    let mut errors = Vec::new();

    match *self {
      Kind::Simplex => {
        if 1 < producers.len() {
          errors.push (DefineError::MultipleProducers);
        }
        if 1 < consumers.len() {
          errors.push (DefineError::MultipleConsumers);
        }
      }
      Kind::Sink => {
        if 1 < consumers.len() {
          errors.push (DefineError::MultipleConsumers);
        }
      }
      Kind::Source => {
        if 1 < producers.len() {
          errors.push (DefineError::MultipleProducers);
        }
      }
    }

    if !errors.is_empty() {
      Err (errors)
    } else {
      Ok (())
    }
  }

} // end impl Kind

impl <T> std::fmt::Debug for SendError <T> {
  fn fmt (&self, f : &mut std::fmt::Formatter) -> std::fmt::Result {
    "SendError(..)".fmt (f)
  }
}

impl <T> std::fmt::Display for SendError <T> {
  fn fmt (&self, f : &mut std::fmt::Formatter) -> std::fmt::Result {
    "sending on a closed channel".fmt (f)
  }
}

impl <T> std::error::Error for SendError <T> {
  fn description (&self) -> &'static str {
    "sending on a closed channel"
  }
  fn cause (&self) -> Option <&dyn std::error::Error> {
    None
  }
}

///////////////////////////////////////////////////////////////////////////////
//  functions
///////////////////////////////////////////////////////////////////////////////

pub fn report_sizes <CTX : session::Context> () {
  println!("channel report sizes...");
  println!("  size of channel::Def: {}", size_of::<Def <CTX>>());
  println!("  size of Channel: {}", size_of::<Channel <CTX>>());
  println!("...channel report sizes");
}