Skip to main content

hopr_transport/protocol/pipeline/
builder.rs

1//! Builder for constructing the HOPR packet pipeline.
2
3use bytes::Bytes;
4use hopr_api::{
5    PeerId,
6    node::TicketEvent,
7    types::{crypto::prelude::*, internal::prelude::*},
8};
9use hopr_crypto_packet::{HoprPixSpec, HoprShareResolution, HoprSurb};
10use hopr_protocol_app::prelude::*;
11use hopr_protocol_hopr::prelude::*;
12use hopr_protocol_pix::ExitAcknowledgementShareProcessor;
13use hopr_utils::runtime::AbortableList;
14
15use super::{
16    NodeType, NoopTicketProcessor, NopExitAcknowledgementShareProcessor, PacketPipelineProcesses,
17    config::PacketPipelineConfig, run_packet_pipeline_inner,
18};
19use crate::{PeerProtocolCounterRegistry, trace_context::WithContext};
20
21/// Placeholder type used by [`PacketPipelineBuilder`] for generic parameters that have
22/// not yet been provided via the corresponding builder method.
23pub struct Unset;
24
25/// Builder for constructing the HOPR packet pipeline for a specific node type.
26///
27/// The builder is constructed from a packet key via [`PacketPipelineBuilder::new`]; the
28/// transport, codec and application API must then be provided via the
29/// [`PacketPipelineBuilder::transport`], [`PacketPipelineBuilder::codec`] and
30/// [`PacketPipelineBuilder::api`] builder methods.
31///
32/// Terminal methods for each node type are then exposed:
33/// - [`PacketPipelineBuilder::build_for_relay`] — full pipeline, requires ticket processing via
34///   [`PacketPipelineBuilder::with_ticket_processing`].
35/// - [`PacketPipelineBuilder::build_for_entry`] — Entry nodes; the incoming acknowledgement pipeline is not started at
36///   all.
37/// - [`PacketPipelineBuilder::build_for_exit`] — Exit nodes; the incoming acknowledgement pipeline is started and
38///   processes exit-acknowledgement shares.
39///
40/// The exit-acknowledgement share processor and the recovered-SSA events sink can be configured via
41/// [`PacketPipelineBuilder::with_exit_ack_share_processing`]. They default to a no-op processor and
42/// a draining sink respectively when not provided.
43///
44/// The pipeline does not handle mixing itself; it needs to be injected as a separate process
45/// overlay on top of the `wire_msg` Stream or Sink.
46pub struct PacketPipelineBuilder<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut, AppIn> {
47    packet_key: OffchainKeypair,
48    wire_msg: (WOut, WIn),
49    codec: (C, D),
50    cfg: PacketPipelineConfig,
51    api: (AppOut, AppIn),
52    counters: PeerProtocolCounterRegistry,
53    ticket_proc: Option<T>,
54    ticket_events: Option<TEvt>,
55    exit_ack_proc: A,
56    ssa_events: SEvt,
57}
58
59impl
60    PacketPipelineBuilder<
61        Unset,
62        Unset,
63        Unset,
64        Unset,
65        NoopTicketProcessor,
66        futures::sink::Drain<TicketEvent>,
67        NopExitAcknowledgementShareProcessor,
68        futures::sink::Drain<HoprShareResolution>,
69        Unset,
70        Unset,
71    >
72{
73    /// Creates a new builder with the common parameters shared by all node types.
74    ///
75    /// The transport, codec and application API must be supplied via
76    /// [`PacketPipelineBuilder::transport`], [`PacketPipelineBuilder::codec`] and
77    /// [`PacketPipelineBuilder::api`] before any of the terminal `build_for_*` methods can
78    /// be called.
79    ///
80    /// The pipeline configuration defaults to [`PacketPipelineConfig::default`]; use
81    /// [`PacketPipelineBuilder::with_config`] to override it. The per-peer counter registry
82    /// defaults to an empty one; use [`PacketPipelineBuilder::with_counters`] to override it.
83    ///
84    /// Use [`PacketPipelineBuilder::with_ticket_processing`] to attach ticket processing
85    /// before calling [`PacketPipelineBuilder::build_for_relay`].
86    ///
87    /// Use [`PacketPipelineBuilder::with_exit_ack_share_processing`] to override the default
88    /// no-op exit-acknowledgement share processor and the default draining recovered-SSA events
89    /// sink before calling [`PacketPipelineBuilder::build_for_relay`] or
90    /// [`PacketPipelineBuilder::build_for_exit`].
91    pub fn new(packet_key: OffchainKeypair) -> Self {
92        Self {
93            packet_key,
94            wire_msg: (Unset, Unset),
95            codec: (Unset, Unset),
96            cfg: PacketPipelineConfig::default(),
97            api: (Unset, Unset),
98            counters: PeerProtocolCounterRegistry::default(),
99            ticket_proc: None,
100            ticket_events: None,
101            exit_ack_proc: NopExitAcknowledgementShareProcessor,
102            ssa_events: futures::sink::drain(),
103        }
104    }
105}
106
107impl<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut, AppIn>
108    PacketPipelineBuilder<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut, AppIn>
109{
110    /// Overrides the default [`PacketPipelineConfig`].
111    #[must_use]
112    pub fn with_config(mut self, cfg: PacketPipelineConfig) -> Self {
113        self.cfg = cfg;
114        self
115    }
116
117    /// Overrides the default (empty) per-peer protocol counter registry.
118    #[must_use]
119    pub fn with_counters(mut self, counters: PeerProtocolCounterRegistry) -> Self {
120        self.counters = counters;
121        self
122    }
123
124    /// Sets the underlying wire-message transport (outgoing sink, incoming stream).
125    #[must_use]
126    pub fn transport<WIn2, WOut2>(
127        self,
128        wire_msg: (WOut2, WIn2),
129    ) -> PacketPipelineBuilder<WIn2, WOut2, C, D, T, TEvt, A, SEvt, AppOut, AppIn> {
130        PacketPipelineBuilder {
131            packet_key: self.packet_key,
132            wire_msg,
133            codec: self.codec,
134            cfg: self.cfg,
135            api: self.api,
136            counters: self.counters,
137            ticket_proc: self.ticket_proc,
138            ticket_events: self.ticket_events,
139            exit_ack_proc: self.exit_ack_proc,
140            ssa_events: self.ssa_events,
141        }
142    }
143
144    /// Sets the packet codec (encoder, decoder).
145    #[must_use]
146    pub fn codec<C2, D2>(
147        self,
148        codec: (C2, D2),
149    ) -> PacketPipelineBuilder<WIn, WOut, C2, D2, T, TEvt, A, SEvt, AppOut, AppIn> {
150        PacketPipelineBuilder {
151            packet_key: self.packet_key,
152            wire_msg: self.wire_msg,
153            codec,
154            cfg: self.cfg,
155            api: self.api,
156            counters: self.counters,
157            ticket_proc: self.ticket_proc,
158            ticket_events: self.ticket_events,
159            exit_ack_proc: self.exit_ack_proc,
160            ssa_events: self.ssa_events,
161        }
162    }
163
164    /// Sets the application API (outgoing sink for received data, incoming stream for data to send).
165    #[must_use]
166    pub fn api<AppOut2, AppIn2>(
167        self,
168        api: (AppOut2, AppIn2),
169    ) -> PacketPipelineBuilder<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut2, AppIn2> {
170        PacketPipelineBuilder {
171            packet_key: self.packet_key,
172            wire_msg: self.wire_msg,
173            codec: self.codec,
174            cfg: self.cfg,
175            api,
176            counters: self.counters,
177            ticket_proc: self.ticket_proc,
178            ticket_events: self.ticket_events,
179            exit_ack_proc: self.exit_ack_proc,
180            ssa_events: self.ssa_events,
181        }
182    }
183
184    /// Attaches a ticket processor and a ticket-events sink to the builder.
185    ///
186    /// Required before calling [`PacketPipelineBuilder::build_for_relay`]. Has no effect on
187    /// Entry/Exit builds, which never process tickets.
188    #[must_use]
189    pub fn with_ticket_processing<T2, TEvt2>(
190        self,
191        ticket_proc: T2,
192        ticket_events: TEvt2,
193    ) -> PacketPipelineBuilder<WIn, WOut, C, D, T2, TEvt2, A, SEvt, AppOut, AppIn>
194    where
195        T2: UnacknowledgedTicketProcessor + Sync + Send + 'static,
196        TEvt2: futures::Sink<TicketEvent> + Clone + Unpin + Send + 'static,
197        TEvt2::Error: std::error::Error,
198    {
199        PacketPipelineBuilder {
200            packet_key: self.packet_key,
201            wire_msg: self.wire_msg,
202            codec: self.codec,
203            cfg: self.cfg,
204            api: self.api,
205            counters: self.counters,
206            ticket_proc: Some(ticket_proc),
207            ticket_events: Some(ticket_events),
208            exit_ack_proc: self.exit_ack_proc,
209            ssa_events: self.ssa_events,
210        }
211    }
212
213    /// Attaches an exit-acknowledgement share processor and a recovered-SSA events sink to the builder.
214    ///
215    /// Optional: when not called, the builder defaults to [`NopExitAcknowledgementShareProcessor`]
216    /// and a draining sink ([`futures::sink::drain`]). Has no effect on Entry builds, which never
217    /// process exit-acknowledgement shares.
218    #[must_use]
219    pub fn with_exit_ack_share_processing<A2, SEvt2>(
220        self,
221        exit_ack_proc: A2,
222        ssa_events: SEvt2,
223    ) -> PacketPipelineBuilder<WIn, WOut, C, D, T, TEvt, A2, SEvt2, AppOut, AppIn>
224    where
225        A2: ExitAcknowledgementShareProcessor<HoprPixSpec> + Send + Sync + 'static,
226        SEvt2: futures::Sink<HoprShareResolution> + Clone + Unpin + Send + 'static,
227        SEvt2::Error: std::error::Error,
228    {
229        PacketPipelineBuilder {
230            packet_key: self.packet_key,
231            wire_msg: self.wire_msg,
232            codec: self.codec,
233            cfg: self.cfg,
234            api: self.api,
235            counters: self.counters,
236            ticket_proc: self.ticket_proc,
237            ticket_events: self.ticket_events,
238            exit_ack_proc,
239            ssa_events,
240        }
241    }
242}
243
244impl<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut, AppIn>
245    PacketPipelineBuilder<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut, AppIn>
246where
247    WOut: futures::Sink<(PeerId, Bytes)> + Clone + Unpin + Send + 'static,
248    WOut::Error: std::error::Error,
249    WIn: futures::Stream<Item = (PeerId, Bytes)> + Send + 'static,
250    C: PacketEncoder + Sync + Send + 'static,
251    D: PacketDecoder + Sync + Send + 'static,
252    T: UnacknowledgedTicketProcessor + Sync + Send + 'static,
253    TEvt: futures::Sink<TicketEvent> + Clone + Unpin + Send + 'static,
254    TEvt::Error: std::error::Error,
255    A: ExitAcknowledgementShareProcessor<HoprPixSpec> + Send + Sync + 'static,
256    SEvt: futures::Sink<HoprShareResolution> + Clone + Unpin + Send + 'static,
257    SEvt::Error: std::error::Error,
258    AppOut: futures::Sink<(HoprPseudonym, ApplicationDataIn)> + Send + 'static,
259    AppOut::Error: std::error::Error,
260    AppIn: futures::Stream + Send + 'static,
261    AppIn::Item: Into<WithContext<(ResolvedTransportRouting<HoprSurb>, ApplicationDataOut)>> + Send,
262{
263    /// Builds and starts the full packet pipeline for a HOPR **Relay** node.
264    ///
265    /// Relay nodes run the full pipeline: outgoing/incoming messages, outgoing acknowledgements,
266    /// and incoming acknowledgements (with ticket processing).
267    ///
268    /// # Panics
269    ///
270    /// Panics if [`PacketPipelineBuilder::with_ticket_processing`] was not called before this method.
271    #[must_use]
272    pub fn build_for_relay(self) -> AbortableList<PacketPipelineProcesses> {
273        let ticket_proc = self
274            .ticket_proc
275            .expect("Relay node requires ticket processing; call with_ticket_processing() first");
276        let ticket_events = self
277            .ticket_events
278            .expect("Relay node requires ticket processing; call with_ticket_processing() first");
279        run_packet_pipeline_inner(
280            NodeType::Relay,
281            self.packet_key,
282            self.wire_msg,
283            self.codec,
284            ticket_proc,
285            self.exit_ack_proc,
286            ticket_events,
287            self.ssa_events,
288            self.cfg,
289            self.api,
290            self.counters,
291        )
292    }
293}
294
295impl<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut, AppIn>
296    PacketPipelineBuilder<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut, AppIn>
297where
298    WOut: futures::Sink<(PeerId, Bytes)> + Clone + Unpin + Send + 'static,
299    WOut::Error: std::error::Error,
300    WIn: futures::Stream<Item = (PeerId, Bytes)> + Send + 'static,
301    C: PacketEncoder + Sync + Send + 'static,
302    D: PacketDecoder + Sync + Send + 'static,
303    AppOut: futures::Sink<(HoprPseudonym, ApplicationDataIn)> + Send + 'static,
304    AppOut::Error: std::error::Error,
305    AppIn: futures::Stream + Send + 'static,
306    AppIn::Item: Into<WithContext<(ResolvedTransportRouting<HoprSurb>, ApplicationDataOut)>> + Send,
307{
308    /// Builds and starts the packet pipeline for a HOPR **Entry** node.
309    ///
310    /// Entry nodes never relay packets and therefore do not process tickets. As a consequence,
311    /// the incoming acknowledgement pipeline is **not** started.
312    /// Any ticket processor, ticket events sink, exit-acknowledgement share processor or
313    /// recovered-SSA events sink previously set via
314    /// [`PacketPipelineBuilder::with_ticket_processing`] or
315    /// [`PacketPipelineBuilder::with_exit_ack_share_processing`] is ignored.
316    #[must_use]
317    pub fn build_for_entry(self) -> AbortableList<PacketPipelineProcesses> {
318        run_packet_pipeline_inner(
319            NodeType::Entry,
320            self.packet_key,
321            self.wire_msg,
322            self.codec,
323            NoopTicketProcessor,
324            NopExitAcknowledgementShareProcessor,
325            futures::sink::drain(),
326            futures::sink::drain(),
327            self.cfg,
328            self.api,
329            self.counters,
330        )
331    }
332}
333
334impl<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut, AppIn>
335    PacketPipelineBuilder<WIn, WOut, C, D, T, TEvt, A, SEvt, AppOut, AppIn>
336where
337    WOut: futures::Sink<(PeerId, Bytes)> + Clone + Unpin + Send + 'static,
338    WOut::Error: std::error::Error,
339    WIn: futures::Stream<Item = (PeerId, Bytes)> + Send + 'static,
340    C: PacketEncoder + Sync + Send + 'static,
341    D: PacketDecoder + Sync + Send + 'static,
342    A: ExitAcknowledgementShareProcessor<HoprPixSpec> + Send + Sync + 'static,
343    SEvt: futures::Sink<HoprShareResolution> + Clone + Unpin + Send + 'static,
344    SEvt::Error: std::error::Error,
345    AppOut: futures::Sink<(HoprPseudonym, ApplicationDataIn)> + Send + 'static,
346    AppOut::Error: std::error::Error,
347    AppIn: futures::Stream + Send + 'static,
348    AppIn::Item: Into<WithContext<(ResolvedTransportRouting<HoprSurb>, ApplicationDataOut)>> + Send,
349{
350    /// Builds and starts the packet pipeline for a HOPR **Exit** node.
351    ///
352    /// Exit nodes do not process tickets. However, in contrast to
353    /// [`PacketPipelineBuilder::build_for_entry`], the incoming acknowledgement pipeline is kept
354    /// running and processes the recovered SSA shares using the exit-acknowledgement share
355    /// processor configured via [`PacketPipelineBuilder::with_exit_ack_share_processing`] (or the
356    /// default no-op processor if not configured).
357    /// Any ticket processor or ticket events sink previously set via
358    /// [`PacketPipelineBuilder::with_ticket_processing`] is ignored.
359    #[must_use]
360    pub fn build_for_exit(self) -> AbortableList<PacketPipelineProcesses> {
361        run_packet_pipeline_inner(
362            NodeType::Exit,
363            self.packet_key,
364            self.wire_msg,
365            self.codec,
366            NoopTicketProcessor,
367            self.exit_ack_proc,
368            futures::sink::drain(),
369            self.ssa_events,
370            self.cfg,
371            self.api,
372            self.counters,
373        )
374    }
375}