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
//! Per-delivery publish context and the transform stacks layered over a publisher.
use fmt;
use PhantomData;
use Outgoing;
use crateHeaderMap;
use crateDeliveryHeaders;
/// A read-only view of the originating delivery, handed to a [`PublishTransform`].
///
/// A reply is published from inside a handler, so the static publish transform can read the
/// delivery that produced it: its channel [`name`](Self::name), the incoming
/// [`headers`](Self::headers) (a W3C `traceparent`, a correlation id), and the broker's typed
/// per-delivery [`context`](Self::context) by [`Field`](crate::Field) key. This is how a trace / correlation id
/// propagates from the incoming message onto the reply (the static, zero-cost path; the app-wide
/// [`PublishLayer`](crate::runtime::PublishLayer) stays context-agnostic). `C` is the
/// handler's context type (`()` when it names none).
///
/// A batch's replies are the exception, because a batch spans many deliveries and has no single
/// one to read: a [`BatchPublishTransform`] sees one view for the whole batch, whose
/// [`name`](Self::name) is the subscription, whose [`headers`](Self::headers) are empty, and
/// whose [`context`](Self::context) is the broker's batch context.
/// What one publish position hands its transforms.
///
/// A reply is published by the runtime, which still holds the delivery being answered, so a
/// transform there can read it. A message leaving an [`Out`](crate::runtime::Out) slot is
/// published by the handler body, which has already read whatever it wanted from its own
/// [`Context`](crate::runtime::Context), so there is no delivery left to hand on. The difference
/// between the two positions is exactly this view, not two interfaces: [`PublishTransform`] takes
/// the kind as a parameter and every position picks its own at compile time.
///
/// The set is closed - [`ForReply`] and [`ForSlot`] - and nothing below the mount site asks which
/// one it got.
/// The kind of a reply position: the transform reads the delivery it answers, as a
/// [`PublishContext`] over the handler's own context type `C`.
>);
/// The kind of an [`Out`](crate::runtime::Out) slot position: the transform reads a
/// [`SlotContext`], which names the slot and nothing else.
;
/// What a transform on an [`Out`](crate::runtime::Out) slot gets to read: the slot's own name.
///
/// A slot publish is issued by the handler body, so the delivery that prompted it is the body's to
/// read and to put on the message; by the time a transform runs there is no delivery left. What
/// remains is which slot the message is leaving through, which is worth having when one transform
/// value is named on several slots. `#[non_exhaustive]`, because a position that later carries
/// more can carry it here without a new interface.
/// What a transform does to the message's destination: the second half of what it declares,
/// beside the view it reads.
///
/// A position offers one of these as the most a transform mounted there may do, and a transform
/// projects one as what it needs. They meet at the mount site: [`Names`] on a transform requires
/// [`Names`] on the position, and [`Reads`] fits anywhere.
///
/// [`NamesDestination`] is a supertrait so the same answer reaches the runtime as a value: every
/// projected destination use carries `NAMES`, and a mount reads it without a bound of its own.
/// The transform reads the destination and leaves it alone. What almost every transform declares,
/// and what every position offers.
;
/// The transform names the destination. A position offers this only where the destination is not
/// already declared, so a declaration and the wire cannot disagree.
;
/// Whether what a transform declares fits the position it is being mounted on. Implemented on the
/// transform's own [`PublishTransform::Destination`], so what fails is a bound naming the reason
/// rather than a mismatch on the projection that produced it.
///
/// [`Reads`] fits any position at any time. [`Names`] fits a position that offers the right
/// ([`NamingOffered`]) and has not given it away ([`NamingUntaken`]), and those are two bounds so
/// a refusal says which of the two it was. `By` is what declares the position's offer - the reply
/// type, or the slot's marker - carried so the error names it.
// A reading transform asks for nothing, so it fits every offer whatever came before.
// A naming one asks for both halves, as bounds rather than as parameter matches.
/// A position that offers a transform the right to name the destination, as declared by `By`.
/// A position whose naming right no transform has taken yet.
/// Whether a destination use names the destination, as a value the runtime can read.
///
/// The type-level answer is what the mount site is checked against; this is the same answer
/// carried to startup, where a position that names per delivery needs no destination of its own.
/// Whether one transform may still name the destination, given what the transforms before it on
/// the same position did.
///
/// The half of [`FitsOffer`] that does not need the position's offer, for a stack checked in one
/// piece at the mount rather than element by element as it is composed.
/// Whether a registration says where its copies go, read off what the position offers and what
/// the transforms on it declared.
///
/// A position that offers nothing has the destination declared already, so any stack settles it;
/// one that offers the naming right has nothing else to fall back on, so a stack that only reads
/// leaves the destination unsaid. Machinery; never named directly.
/// The destination use of a whole transform stack: [`Names`] as soon as one element names.
/// Machinery behind the `.transform(..)` step's own check.
/// A static, compile-time publish transform: mutates an [`Outgoing`] before it is sent, with read
/// access to whatever its position hands it.
///
/// The publish-side counterpart to the consume-side [`Layer`](crate::runtime::Layer): zero-cost composition,
/// no `dyn` dispatch. Composed onto a position by the `.transform(..)` step of a mount site's
/// chain. Use for
/// per-destination transforms that belong to the publisher itself - a Confluent / Avro envelope, a
/// fixed content-type header, or stamping the delivery's trace / correlation id onto the reply
/// (read it from `cx`). For cross-cutting
/// *observation* across every publish (metrics), use the app-wide [`PublishLayer`](crate::runtime::PublishLayer) via
/// [`RustStream::publish_layer`](crate::runtime::RustStream::publish_layer) instead; the per-publisher
/// transforms run first (closest to the value), then the app-wide publish pipeline, then the send.
///
/// # Which positions a transform mounts on
///
/// `K` is the position's [`ContextKind`], and writing the impl is how a transform says where it
/// belongs. A transform that reads nothing is generic over the kind and over the options, and
/// mounts anywhere:
///
/// ```
/// use ruststream::runtime::{ContextKind, Outgoing, PublishTransform, Reads};
///
/// struct Envelope;
///
/// impl<K: ContextKind, Options> PublishTransform<K, Options> for Envelope {
/// type Destination = Reads;
///
/// fn apply(
/// &self,
/// out: &mut Outgoing<'_>,
/// _options: &mut Option<Options>,
/// _cx: &K::View<'_>,
/// ) {
/// out.headers_mut().insert("x-envelope", b"1".to_vec());
/// }
/// }
/// ```
///
/// One that reads the delivery names [`ForReply`], and naming it on a slot is then a compile error
/// at the mount site:
///
/// ```
/// use ruststream::runtime::{ForReply, Outgoing, PublishContext, PublishTransform, Reads};
///
/// struct StampSource;
///
/// impl<C, Options> PublishTransform<ForReply<C>, Options> for StampSource {
/// type Destination = Reads;
///
/// fn apply(
/// &self,
/// out: &mut Outgoing<'_>,
/// _options: &mut Option<Options>,
/// cx: &PublishContext<'_, C>,
/// ) {
/// out.headers_mut().insert("x-source", cx.name().as_bytes().to_vec());
/// }
/// }
/// ```
///
/// # What a transform writes
///
/// `Options` is the broker's per-message settings type ([`Publisher::Options`](crate::Publisher::Options)),
/// and the position is `None` until something fills it: the publish policy's own settings are
/// what apply. A transform that sets one writes the broker's type into its impl, so it mounts
/// over that broker's publisher and nowhere else:
///
/// ```
/// use ruststream::runtime::{ForSlot, Outgoing, PublishTransform, Reads, SlotContext};
///
/// /// What one broker lets a single message differ in.
/// #[derive(Clone, Default)]
/// struct Priority {
/// level: Option<u8>,
/// }
///
/// struct Urgent;
///
/// impl PublishTransform<ForSlot, Priority> for Urgent {
/// type Destination = Reads;
///
/// fn apply(
/// &self,
/// _out: &mut Outgoing<'_>,
/// options: &mut Option<Priority>,
/// _cx: &SlotContext<'_>,
/// ) {
/// options.get_or_insert_with(Priority::default).level = Some(9);
/// }
/// }
/// ```
///
/// On a slot the position starts as a copy of what the call site's own builder steps set, so a
/// transform completes the call rather than replacing it: it reads a field the call left alone
/// and overrides one it filled. A reply has no call site, so there the position starts at `None`.
///
/// # What a transform may do to the destination
///
/// [`Destination`](Self::Destination) is the third half of the declaration, beside the view and
/// the options: a
/// transform that leaves the destination alone declares [`Reads`], one that names it declares
/// [`Names`]. Stable Rust has no default for an associated type, so every impl writes the line -
/// including the three above, which declare `Reads`.
///
/// A position offers the right to name only where nothing has declared the destination already:
/// a reply type that leaves it open, a slot whose whole `#[publishes(..)]` dictionary leaves it
/// open. Where it is not on offer, mounting a naming transform is a compile error at the mount
/// site, which is what keeps a declaration and the wire in step. [`Outgoing::set_name`] stays a
/// plain method; what is checked is the declaration, not the call.
///
/// A destination the delivery already carries travels as the delivery's own buffer:
/// [`HeaderMap::get_shared`](crate::HeaderMap::get_shared) hands the header value over as a
/// counted handle, <code>[Str](crate::Str)::try_from</code> checks it is UTF-8, and `set_name`
/// takes the result. Answering where the request asked therefore costs a reference count, not a copy of the
/// address.
///
/// ```
/// use ruststream::Str;
/// use ruststream::runtime::{ForReply, Names, Outgoing, PublishContext, PublishTransform};
///
/// /// Answers where the request asked to be answered.
/// struct ReplyTo;
///
/// impl<C, Options> PublishTransform<ForReply<C>, Options> for ReplyTo {
/// type Destination = Names;
///
/// fn apply(
/// &self,
/// out: &mut Outgoing<'_>,
/// _options: &mut Option<Options>,
/// cx: &PublishContext<'_, C>,
/// ) {
/// if let Some(to) = cx.headers().get_shared("reply-to")
/// && let Ok(to) = Str::try_from(to)
/// {
/// out.set_name(to);
/// }
/// }
/// }
/// ```
/// The no-op [`PublishTransform`]: the default for a reply wiring with no static transforms.
;
/// Composes two [`PublishTransform`]s: `inner` runs first, then `outer`. Built by a chain's
/// `.transform(..)` step; you rarely name it directly.
/// A static publish transform that runs only on a batch publishing (`&[T]` + `reply(..)`)
/// handler's replies, not on single-message replies.
///
/// The batch counterpart of [`PublishTransform`], kept a distinct trait so a transform that belongs to
/// the batch path only (a header marking a reply as batched, a per-batch sampling decision) cannot
/// be added with a chain's `.transform(..)` step by mistake; it is added with
/// `.batch_transform(..)`, which the single-message mounts reject at compile time. The
/// per-message [`PublishTransform`] stack does not run for batched replies and this one does not run for
/// single-message replies - the two paths are independent. To use the same transform on both, add
/// it to each, reusing it on the batch side with [`for_batch`] (no second implementation).
///
/// Each reply in the batch runs through it individually, but they all see one
/// [`PublishContext`], and it is the batch's rather than a delivery's: a batch spans many
/// deliveries, so it has no single one to read. [`name`](PublishContext::name) is the
/// subscription, [`headers`](PublishContext::headers) is empty, and
/// [`context`](PublishContext::context) reads the broker's batch context (built from the batch's
/// first delivery). A transform that has to read the message it answers for belongs on the
/// per-message path, where the reply and its delivery are one.
/// The no-op [`BatchPublishTransform`]: the default for a reply wiring with no batch transforms.
;
/// Composes two [`BatchPublishTransform`]s: `inner` runs first, then `outer`. Built by a chain's
/// `.batch_transform(..)` step; you rarely name it directly.
/// Adapts a per-message [`PublishTransform`] into a [`BatchPublishTransform`], applying it to each reply of
/// a batch. Built by [`for_batch`].
;
/// Lifts a per-message [`PublishTransform`] onto the batch path.
///
/// The same transform then goes on a reply chain's `.batch_transform(..)` step, with no second
/// implementation to write.
///
/// ```
/// # #[cfg(all(feature = "memory", feature = "macros", feature = "json"))]
/// # mod demo {
/// use ruststream::memory::prelude::*;
/// use ruststream::runtime::{for_batch, ContextKind, Outgoing, PublishTransform, Reads};
/// # use ruststream::subscriber;
/// # #[derive(serde::Deserialize, schemars::JsonSchema)]
/// # struct Order { id: u64 }
/// # #[derive(serde::Serialize, schemars::JsonSchema, ruststream::Outgoing)]
/// # struct Confirmation { id: u64 }
/// # #[subscriber("orders", reply("confirmations"))]
/// # async fn confirm(orders: &[Order]) -> Vec<Confirmation> {
/// # orders.iter().map(|o| Confirmation { id: o.id }).collect()
/// # }
///
/// struct Stamp;
/// impl<K: ContextKind, Options> PublishTransform<K, Options> for Stamp {
/// type Destination = Reads;
///
/// fn apply(
/// &self,
/// out: &mut Outgoing<'_>,
/// _options: &mut Option<Options>,
/// _cx: &K::View<'_>,
/// ) {
/// out.headers_mut().insert("x-stamp", b"1".to_vec());
/// }
/// }
///
/// fn app() -> RustStream {
/// RustStream::new(AppInfo::new("orders", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
/// // `Stamp` on the batch path, without a second implementation.
/// b.include(confirm.batch(nonzero!(8)))
/// .out(Reply, Publish)
/// .batch_transform(for_batch(Stamp));
/// })
/// }
/// # }
/// ```