wingfoil 6.0.5

graph based stream processing 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
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
//! Type-safe builders for Aeron channel URIs.
//!
//! Constructing Aeron channel URIs by hand is error-prone — typos in the
//! `aeron:udp?endpoint=...` syntax are silently accepted by the media driver
//! and surface only as a non-connecting publication. The [`ChannelUri`]
//! helpers below produce the canonical strings for the most common channel
//! shapes used by `wingfoil`-based applications.

use std::net::Ipv6Addr;
use std::str::FromStr;

use super::TransportError;

/// ASCII punctuation accepted in URI parameter values.
///
/// Covers IPv4 host/port (`.`, `:`), bracketed IPv6 (`[`, `]`), DNS hostnames
/// (`.`, `-`), and identifier characters (`_`). The validator is an
/// **allowlist** — any character outside this set (including non-ASCII letters,
/// Unicode invisibles, whitespace, and Aeron URI separators `|?=#,;`) is
/// rejected.
const URI_ALLOWED_PUNCT: &[char] = &[':', '[', ']', '.', '-', '_'];

fn is_uri_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || URI_ALLOWED_PUNCT.contains(&c)
}

/// Validates an Aeron URI parameter value: non-empty and ASCII allowlist.
fn validate_param(label: &str, value: &str) -> Result<(), TransportError> {
    if value.is_empty() {
        return Err(TransportError::Invalid(format!(
            "{label} must not be empty"
        )));
    }
    if let Some(ch) = value.chars().find(|c| !is_uri_char(*c)) {
        return Err(TransportError::Invalid(format!(
            "{label} contains invalid character '{ch}' (U+{:04X}); only ASCII alphanumerics and ':[].-_' are permitted",
            ch as u32
        )));
    }
    Ok(())
}

/// Validates that `value` is shaped like `host:port` or `[ipv6]:port`.
///
/// `port` must parse as a `u16`. Bare IPv6 (multiple colons, no brackets) is
/// rejected because it is ambiguous: `::1` could mean host `::1` with no port
/// or host `:` port `:1`.
fn validate_host_port(label: &str, value: &str) -> Result<(), TransportError> {
    validate_param(label, value)?;

    let (host, port) = if let Some(rest) = value.strip_prefix('[') {
        let close = rest.find(']').ok_or_else(|| {
            TransportError::Invalid(format!(
                "{label} bracketed IPv6 address missing closing ']' in '{value}'"
            ))
        })?;
        let host = &rest[..close];
        let after = &rest[close + 1..];
        let port = after.strip_prefix(':').ok_or_else(|| {
            TransportError::Invalid(format!(
                "{label} bracketed IPv6 address must be followed by ':port' in '{value}'"
            ))
        })?;
        Ipv6Addr::from_str(host).map_err(|_| {
            TransportError::Invalid(format!(
                "{label} bracketed IPv6 '{host}' is not a valid IPv6 address in '{value}'"
            ))
        })?;
        (host, port)
    } else {
        let colons = value.matches(':').count();
        if colons == 0 {
            return Err(TransportError::Invalid(format!(
                "{label} expected 'host:port' in '{value}'"
            )));
        }
        if colons > 1 {
            return Err(TransportError::Invalid(format!(
                "{label} bare IPv6 must be bracketed like '[::1]:port' (got '{value}')"
            )));
        }
        // Exactly one ':' validated above, so the split is infallible.
        let (host, port) = value
            .split_once(':')
            .expect("invariant: exactly one ':' validated above");
        if host.contains('[') || host.contains(']') {
            return Err(TransportError::Invalid(format!(
                "{label} brackets are only allowed as the bracketed-IPv6 prefix '[ipv6]:port' (got '{value}')"
            )));
        }
        (host, port)
    };

    if host.is_empty() {
        return Err(TransportError::Invalid(format!(
            "{label} host part must not be empty"
        )));
    }
    port.parse::<u16>().map_err(|_| {
        TransportError::Invalid(format!(
            "{label} port '{port}' must be a valid u16 (0-65535)"
        ))
    })?;
    Ok(())
}

/// Builders for Aeron channel URI strings.
///
/// Parameterised constructors return `Result<String, TransportError>`. They
/// reject inputs that are empty, contain non-ASCII or non-allowlist characters
/// (Unicode invisibles, whitespace, control chars, Aeron URI separators
/// `|?=#,;`), or do not match the expected `host:port` shape (with bracketed
/// IPv6 supported as `[::1]:port`). These checks run at startup, not on the
/// hot path.
#[derive(Debug)]
pub struct ChannelUri;

impl ChannelUri {
    /// Returns the IPC channel URI: `aeron:ipc`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use wingfoil::adapters::aeron::ChannelUri;
    /// assert_eq!(ChannelUri::ipc(), "aeron:ipc");
    /// ```
    pub fn ipc() -> String {
        "aeron:ipc".to_string()
    }

    /// Returns a UDP unicast channel URI: `aeron:udp?endpoint={endpoint}`.
    ///
    /// `endpoint` must be `host:port` (or `[ipv6]:port`).
    ///
    /// # Errors
    ///
    /// Returns [`TransportError::Invalid`] if `endpoint` is empty, contains
    /// disallowed characters, or does not match the `host:port` shape.
    ///
    /// # Examples
    ///
    /// ```
    /// # use wingfoil::adapters::aeron::ChannelUri;
    /// assert_eq!(
    ///     ChannelUri::udp("127.0.0.1:40123").unwrap(),
    ///     "aeron:udp?endpoint=127.0.0.1:40123"
    /// );
    /// ```
    pub fn udp(endpoint: &str) -> Result<String, TransportError> {
        validate_host_port("endpoint", endpoint)?;
        Ok(format!("aeron:udp?endpoint={endpoint}"))
    }

    /// Returns an MDC publication channel URI:
    /// `aeron:udp?control={control}|control-mode=dynamic`.
    ///
    /// Use this for the publisher side of a Multi-Destination-Cast stream.
    /// `control` must be `host:port` (or `[ipv6]:port`).
    ///
    /// # Errors
    ///
    /// Returns [`TransportError::Invalid`] if `control` is empty, contains
    /// disallowed characters, or does not match the `host:port` shape.
    ///
    /// # Examples
    ///
    /// ```
    /// # use wingfoil::adapters::aeron::ChannelUri;
    /// assert_eq!(
    ///     ChannelUri::mdc_publication("127.0.0.1:40456").unwrap(),
    ///     "aeron:udp?control=127.0.0.1:40456|control-mode=dynamic"
    /// );
    /// ```
    pub fn mdc_publication(control: &str) -> Result<String, TransportError> {
        validate_host_port("control", control)?;
        Ok(format!("aeron:udp?control={control}|control-mode=dynamic"))
    }

    /// Returns an MDC subscription channel URI:
    /// `aeron:udp?endpoint={endpoint}|control={control}|control-mode=dynamic`.
    ///
    /// Use this for the subscriber side of a Multi-Destination-Cast stream.
    /// Both `endpoint` and `control` must be `host:port` (or `[ipv6]:port`).
    ///
    /// # Errors
    ///
    /// Returns [`TransportError::Invalid`] if either parameter is empty,
    /// contains disallowed characters, or does not match the `host:port` shape.
    ///
    /// # Examples
    ///
    /// ```
    /// # use wingfoil::adapters::aeron::ChannelUri;
    /// assert_eq!(
    ///     ChannelUri::mdc_subscription("127.0.0.1:40789", "127.0.0.1:40456").unwrap(),
    ///     "aeron:udp?endpoint=127.0.0.1:40789|control=127.0.0.1:40456|control-mode=dynamic"
    /// );
    /// ```
    pub fn mdc_subscription(endpoint: &str, control: &str) -> Result<String, TransportError> {
        validate_host_port("endpoint", endpoint)?;
        validate_host_port("control", control)?;
        Ok(format!(
            "aeron:udp?endpoint={endpoint}|control={control}|control-mode=dynamic"
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn given_channel_uri_when_ipc_then_returns_aeron_ipc() {
        assert_eq!(ChannelUri::ipc(), "aeron:ipc");
    }

    #[test]
    fn given_channel_uri_when_udp_then_formats_endpoint() {
        assert_eq!(
            ChannelUri::udp("127.0.0.1:40123").unwrap(),
            "aeron:udp?endpoint=127.0.0.1:40123"
        );
    }

    #[test]
    fn given_channel_uri_when_udp_with_bracketed_ipv6_then_formats_endpoint() {
        assert_eq!(
            ChannelUri::udp("[::1]:40123").unwrap(),
            "aeron:udp?endpoint=[::1]:40123"
        );
    }

    #[test]
    fn given_channel_uri_when_udp_with_hostname_then_formats_endpoint() {
        assert_eq!(
            ChannelUri::udp("aeron-host.example.com:40123").unwrap(),
            "aeron:udp?endpoint=aeron-host.example.com:40123"
        );
    }

    #[test]
    fn given_channel_uri_when_mdc_publication_then_formats_control_dynamic() {
        assert_eq!(
            ChannelUri::mdc_publication("127.0.0.1:40456").unwrap(),
            "aeron:udp?control=127.0.0.1:40456|control-mode=dynamic"
        );
    }

    #[test]
    fn given_channel_uri_when_mdc_subscription_then_formats_endpoint_and_control() {
        assert_eq!(
            ChannelUri::mdc_subscription("127.0.0.1:40789", "127.0.0.1:40456").unwrap(),
            "aeron:udp?endpoint=127.0.0.1:40789|control=127.0.0.1:40456|control-mode=dynamic"
        );
    }

    #[test]
    fn given_channel_uri_when_udp_empty_endpoint_then_returns_error() {
        let err = ChannelUri::udp("").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_pipe_in_endpoint_then_returns_error() {
        let err = ChannelUri::udp("host|control-mode=dynamic").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_question_mark_in_endpoint_then_returns_error() {
        let err = ChannelUri::udp("host?evil=1").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_mdc_publication_empty_control_then_returns_error() {
        let err = ChannelUri::mdc_publication("").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_mdc_subscription_empty_endpoint_then_returns_error() {
        let err = ChannelUri::mdc_subscription("", "127.0.0.1:40456").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_mdc_subscription_empty_control_then_returns_error() {
        let err = ChannelUri::mdc_subscription("127.0.0.1:40789", "").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_equals_in_endpoint_then_returns_error() {
        let err = ChannelUri::udp("host:1234=evil").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_hash_in_endpoint_then_returns_error() {
        let err = ChannelUri::udp("host:1234#frag").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_space_in_endpoint_then_returns_error() {
        let err = ChannelUri::udp("host 1234").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_comma_in_endpoint_then_returns_error() {
        let err = ChannelUri::udp("host1:1,host2:2").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_semicolon_in_endpoint_then_returns_error() {
        let err = ChannelUri::udp("host:1234;evil").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_non_ascii_in_endpoint_then_returns_error() {
        // Cyrillic 'а' (U+0430) is visually identical to Latin 'a' (U+0061).
        let err = ChannelUri::udp("\u{0430}.example.com:1234").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_zero_width_space_in_endpoint_then_returns_error() {
        // U+200B (ZWSP) is not matched by char::is_whitespace.
        let err = ChannelUri::udp("127.0.0.1:40123\u{200B}").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_no_colon_then_returns_error() {
        let err = ChannelUri::udp("hostonly").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_bare_ipv6_then_returns_error() {
        let err = ChannelUri::udp("::1").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_port_too_large_then_returns_error() {
        let err = ChannelUri::udp("127.0.0.1:65536").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_non_numeric_port_then_returns_error() {
        let err = ChannelUri::udp("127.0.0.1:abc").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_empty_host_then_returns_error() {
        let err = ChannelUri::udp(":1234").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_unclosed_bracket_then_returns_error() {
        let err = ChannelUri::udp("[::1:1234").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_udp_bracket_without_port_then_returns_error() {
        let err = ChannelUri::udp("[::1]").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_mdc_publication_no_colon_then_returns_error() {
        let err = ChannelUri::mdc_publication("hostonly").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_channel_uri_when_mdc_subscription_endpoint_no_colon_then_returns_error() {
        let err = ChannelUri::mdc_subscription("hostonly", "127.0.0.1:40456").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_validate_host_port_when_brackets_outside_prefix_then_returns_error() {
        let err = ChannelUri::udp("host[evil]:1234").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_validate_host_port_when_bracketed_hostname_non_hex_then_returns_error() {
        let err = ChannelUri::udp("[hello-world]:80").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_validate_host_port_when_bracketed_colon_only_then_returns_error() {
        let err = ChannelUri::udp("[:]:80").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_validate_host_port_when_bracketed_ipv4_then_returns_error() {
        let err = ChannelUri::udp("[127.0.0.1]:80").unwrap_err();
        assert!(matches!(err, TransportError::Invalid(_)));
    }

    #[test]
    fn given_validate_host_port_when_zero_colons_then_error_mentions_host_port() {
        let err = ChannelUri::udp("hostonly").unwrap_err();
        match err {
            TransportError::Invalid(msg) => {
                assert!(
                    msg.contains("host:port"),
                    "expected error to mention 'host:port' for zero-colon input, got: {msg}"
                );
            }
            other => panic!("unexpected error variant: {other:?}"),
        }
    }

    #[test]
    fn given_validate_host_port_when_multiple_colons_then_error_mentions_bracketed_ipv6() {
        let err = ChannelUri::udp("::1").unwrap_err();
        match err {
            TransportError::Invalid(msg) => {
                assert!(
                    msg.contains("bracketed"),
                    "expected error to mention bracketed-IPv6 form for bare IPv6 input, got: {msg}"
                );
            }
            other => panic!("unexpected error variant: {other:?}"),
        }
    }
}