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
//! The input axis of the [`Handle`](super::Handle) trait: what the `In` parameter may be, and
//! what each spelling means to the mount machinery.
//!
//! The form rule is uniform - `&T` is one message, `&[T]` a batch of them - and the lane is the
//! type's own business: a `serde` type rides the codec, a [`Deserialized`] type constructs
//! itself from the payload bytes, a [`Message<H, P>`](Message) pair decodes its typed header
//! contract in the same stage, and a type on the carried lane is lent by the delivery that holds
//! it ([`Carries`](crate::Carries)). The spellings:
//!
//! | `In` | delivery | body parameter |
//! |---|---|---|
//! | `T` | one decoded message | `&T` |
//! | `Message<H, P>` | one decoded message + typed headers | `&Message<H, P>` |
//! | `F<'_>` where `F` is [`Deserialized`] | one payload, self-constructed | `&F<'_>` |
//! | `T` on the carried lane | the value one delivery holds | `&T` |
//! | `[T]` | a batch of decoded messages | `&[T]` |
//! | `[Message<H, P>]` | a batch with typed headers per element | `&[Message<H, P>]` |
//! | `[F<'_>]` where `F` is [`Deserialized`] | a batch of self-constructed payloads | `&[F<'_>]` |
//! | `[T]` on the carried lane | the values one batch holds, as one slice | `&[T]` |
//!
//! Every projection the machinery needs (the decode kind, the verdict family, the schema of the
//! generated document) hangs off the lifetime-free [`Axis`] marker, so definitions can carry the
//! axis without carrying a borrow.
use DeserializeOwned;
use crate;
use DocState;
use ;
/// One incoming message together with its decoded typed header contract.
///
/// As a [`Handle`](super::Handle) input (`Message<OrderHeaders, Order>`), the core decodes the
/// payload and the headers in the same stage, under the same
/// [`on_failure(decode = ..)`](crate::runtime::FailurePolicies) policy as the payload alone, and
/// the body receives ready values. The pairing is structural: each consumer declares the
/// contract it reads, so two subscribers of one subject may read different header sets.
///
/// As a reply type (`Handle<In, Message<EventHeaders, Confirmation>>`), the reply's headers ride
/// the value: the runtime serializes the contract into the outgoing headers and the payload
/// through the reply codec.
///
/// # Examples
///
/// ```
/// # #[cfg(all(feature = "macros", feature = "memory", feature = "json"))]
/// # mod demo {
/// use ruststream::memory::prelude::*;
/// use serde::Deserialize;
///
/// #[derive(Deserialize, schemars::JsonSchema)]
/// struct OrderHeaders {
/// tenant: String,
/// }
///
/// #[derive(Deserialize, schemars::JsonSchema)]
/// struct Order {
/// id: u64,
/// }
///
/// struct Bill;
///
/// /// The payload and its header contract arrive decoded together.
/// impl Handle<Message<OrderHeaders, Order>> for Bill {
/// async fn handle(
/// &self,
/// msg: &Message<OrderHeaders, Order>,
/// _outs: &(),
/// _ctx: &mut Context<'_>,
/// ) -> Result<(), HandlerOutcome> {
/// tracing::info!(order = msg.body.id, tenant = msg.headers.tenant, "billed");
/// Ok(())
/// }
/// }
///
/// fn app() -> RustStream {
/// RustStream::new(AppInfo::new("billing", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
/// b.include(subscriber("orders", Bill).build());
/// })
/// }
/// # }
/// # fn main() {}
/// ```
/// A type that deserializes itself from the payload bytes: `Deserialize` means the framework's
/// codec does it, `Deserialized` means it is already done by the user's own type.
///
/// The core hands [`from_payload`](Self::from_payload) the delivery's bytes exactly as they
/// arrived - no codec runs, no decode policy of a codec applies, and nothing is copied: the
/// output borrows the broker's buffer. A failed construction is settled by the subscriber's
/// [`on_failure(decode = ..)`](crate::runtime::FailurePolicies) policy, the same rung a codec
/// decode failure lands on. This is the lane a zero-copy wire format (flatbuffers, capnp, a
/// hand-rolled frame) rides without pretending to be `serde`.
///
/// # Implementing by hand
///
/// `#[derive(Deserialized)]` (under the `macros` feature) covers a newtype or single-field
/// struct over `&'a [u8]`. Any other shape is a pair of short impls: the construction, and the
/// [`Input`] spelling that routes the type onto the self-deserializing lane. The batch spelling
/// comes for free - `&[Frame<'_>]` bodies mount off the same two impls:
///
/// ```
/// use ruststream::prelude::*;
///
/// struct Frame<'a>(&'a [u8]);
///
/// impl Deserialized for Frame<'_> {
/// type Output<'a> = Frame<'a>;
/// type Error = core::convert::Infallible;
///
/// fn from_payload(payload: &[u8]) -> Result<Frame<'_>, Self::Error> {
/// Ok(Frame(payload))
/// }
/// }
///
/// impl Input for Frame<'_> {
/// type Axis = SoloDeserialized<Frame<'static>>;
/// }
/// # fn check() -> Result<(), Box<dyn std::error::Error>> {
/// let frame = Frame::from_payload(b"bytes")?;
/// assert_eq!(frame.0, b"bytes");
/// # Ok(())
/// # }
/// # check().unwrap();
/// ```
/// What a `#[wire(decode = ..)]` function returns, with its error erased so the derive need not
/// name a type it cannot see. Machinery behind the derive.
///
/// Only the fallible shape is admitted, which every self-describing format's reader has anyway:
/// a bare `T` and `Result<T, E>` overlap the moment the decoded type is itself a result, so the
/// two cannot both be accepted.
/// A [`Handle`](super::Handle) input spelling: a decoded `T`, a [`Deserialized`] type, a
/// [`Message<H, P>`](Message) pair, a value the delivery already holds
/// ([`Carries`](crate::Carries)), or a batch (slice) of any of them.
/// The lifetime-free projection of one [`Input`] spelling. Machinery; never named in user code.
/// What one documentation state reports for one axis: the payload schema, and the headers
/// schema for a pair axis. Machinery behind documented-by-default; the `Doc` obligations
/// ([`Documentable`](super::Documentable) on the message types) live in these impls.
/// The single decoded input: `In = T`.
;
/// The single self-deserializing input: `In = F<'_>` for a [`Deserialized`] `F`.
///
/// The parameter is the family's lifetime-free representative (`Frame<'static>`), which every
/// lifetime of the input projects to.
;
/// The single pair input: `In = Message<H, P>`.
>);
/// The single carried input: `In = T` for a `T` the subscription's deliveries lend
/// ([`Carries<T>`](crate::Carries)). A broker crate's derive selects it for the type, with
/// `impl Input for Row { type Axis = SoloCarried<Row>; }`.
///
/// # Examples
///
/// A handler of one carried value and one of a batch, over a broker crate whose derive puts `SendEmail` on this lane:
///
/// ```
/// # #[cfg(all(feature = "macros", feature = "memory"))]
/// # mod demo {
/// # mod db_queue {
/// # // The broker crate's side: its broker, its descriptor, its deliveries and pages of rows.
/// # use std::num::NonZeroUsize;
/// # use futures::Stream;
/// # use ruststream::memory::{ConnectedMemoryBroker, MemoryError};
/// # use ruststream::runtime::{Input, SoloCarried};
/// # use ruststream::{AckError, AddressedCopies, BatchSubscriber, Carries, CarriesBatch};
/// # use ruststream::{HeaderMap, IncomingMessage, RedeliveryAddress, RedeliveryAddressed};
/// # use ruststream::{Subscriber, SubscriptionSource};
/// # use super::SendEmail;
/// # pub mod prelude {
/// # pub use ruststream::prelude::*;
/// # pub use super::{QueueBroker, QueueTable};
/// # }
/// # pub type QueueBroker = ruststream::memory::MemoryBroker;
/// # #[derive(Clone)]
/// # pub struct QueueTable(&'static str);
/// # impl QueueTable { pub fn new(table: &'static str) -> Self { Self(table) } }
/// # pub struct Claims;
/// # pub struct Claimed { bytes: Vec<u8>, headers: HeaderMap, row: Option<SendEmail> }
/// # pub struct Page { rows: Vec<SendEmail>, claims: Vec<Claimed> }
/// # impl SubscriptionSource<ConnectedMemoryBroker> for QueueTable {
/// # type Subscriber = Claims;
/// # type Copies = AddressedCopies;
/// # fn name(&self) -> &str { self.0 }
/// # async fn subscribe(self, _: &ConnectedMemoryBroker) -> Result<Claims, MemoryError> {
/// # Ok(Claims)
/// # }
/// # }
/// # impl RedeliveryAddressed<ConnectedMemoryBroker> for QueueTable {
/// # async fn redelivery_address(&self, _: &ConnectedMemoryBroker)
/// # -> Result<RedeliveryAddress, MemoryError> {
/// # Ok(RedeliveryAddress::new(self.0))
/// # }
/// # }
/// # impl Subscriber for Claims {
/// # type Message = Claimed;
/// # type Error = MemoryError;
/// # fn stream(&mut self) -> impl Stream<Item = Result<Claimed, MemoryError>> + Send + '_ {
/// # futures::stream::empty()
/// # }
/// # }
/// # impl BatchSubscriber for Claims {
/// # type Batch = Page;
/// # fn batches(&mut self, _: NonZeroUsize)
/// # -> impl Stream<Item = Result<Page, MemoryError>> + Send + '_ {
/// # futures::stream::empty()
/// # }
/// # }
/// # impl Carries<SendEmail> for Claimed {
/// # fn carried(&self) -> Option<&SendEmail> { self.row.as_ref() }
/// # }
/// # impl CarriesBatch<SendEmail> for Page {
/// # fn carried(&self) -> &[SendEmail] { &self.rows }
/// # }
/// # impl IntoIterator for Page {
/// # type Item = Claimed;
/// # type IntoIter = std::vec::IntoIter<Claimed>;
/// # fn into_iter(self) -> Self::IntoIter { self.claims.into_iter() }
/// # }
/// # impl IncomingMessage for Claimed {
/// # fn payload(&self) -> &[u8] { &self.bytes }
/// # fn headers(&self) -> &HeaderMap { &self.headers }
/// # async fn ack(self) -> Result<(), AckError> { Ok(()) }
/// # async fn nack(self, _: bool) -> Result<(), AckError> { Ok(()) }
/// # }
/// # // What the broker crate's derive writes.
/// # impl Input for SendEmail { type Axis = SoloCarried<Self>; }
/// # }
/// use db_queue::prelude::*;
///
/// /// One row of the queue table, as the database driver reads it.
/// // The broker crate's derive, beside `Clone`, puts the type on this lane.
/// #[derive(Clone)]
/// struct SendEmail {
/// to: String,
/// }
///
/// #[subscriber(QueueTable::new("email_jobs"))]
/// async fn send(email: &SendEmail) -> HandlerOutcome {
/// tracing::info!(to = %email.to, "sent");
/// HandlerOutcome::ack()
/// }
///
/// /// One SMTP session per page of rows.
/// #[subscriber(QueueTable::new("newsletter_jobs"))]
/// async fn send_newsletter(emails: &[SendEmail]) -> HandlerOutcome {
/// tracing::info!(count = emails.len(), "sent a page");
/// HandlerOutcome::ack()
/// }
///
/// fn app() -> RustStream {
/// RustStream::new(AppInfo::new("mailer", "0.1.0")).with_broker(QueueBroker::new(), |b| {
/// b.include(send);
/// b.include(send_newsletter.batch(nonzero!(64)));
/// })
/// }
/// # }
/// # fn main() {}
/// ```
;
/// The decoded batch input: `In = [T]`.
;
/// The self-deserializing batch input: `In = [F<'_>]` for a [`Deserialized`] `F`. See
/// [`SoloDeserialized`] for the parameter.
;
/// The pair batch input: `In = [Message<H, P>]`.
>);
/// The carried batch input: `In = [T]` for a `T` the subscription's batches lend as one slice
/// ([`CarriesBatch<T>`](crate::CarriesBatch)). See [`SoloCarried`].
;
/// The batch axis of one single-delivery axis: what `[T]` rides given what `T` rides.
///
/// The one slice `Input` impl projects through this, so every single spelling's batch comes for
/// free - a `Deserialized` type's own `Input` impl (or derive) makes `&[Frame<'_>]` bodies
/// mountable without a second impl, which the orphan rule would forbid downstream anyway
/// (`[T]` is nobody's local type). Machinery; never named in user code.
// No overlap with the decoded blanket above: that one is implicitly `Sized`, a slice is not.
// A self-deserializing payload has no serde model, so no schema is demanded or produced in any
// documentation state.
// A carried value is the service's own type, so it documents itself exactly like a decoded one.
/// A single-delivery axis: the plain, raw and pair spellings of one message at a time. The
/// bound behind the forms that make no sense for a batch (a reply's destination is one message's
/// business).
/// A batch axis: the slice spellings. The bound behind `.batch(..)`.