rama-net 0.4.0

rama network types and utilities
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
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
use std::{
    fmt,
    sync::{Arc, OnceLock},
};

use crate::address::ProxyAddress;
use rama_core::{
    Layer, Service, error::BoxError, error_sink::ErrorSink, extensions::ExtensionsRef,
    telemetry::tracing,
};

use super::{
    ProxyRoute, ProxyRoutes,
    env::proxy_address_from_env,
    load::{CachedLoadError, LoadErrorPolicy},
};

#[derive(Debug, Clone, Default)]
/// Apply one fixed proxy address to any service input with extensions.
///
/// This layer reads application environment variables only when constructed
/// with [`try_from_env`][Self::try_from_env]. It does not inspect operating
/// system proxy settings; use [`SystemProxyLayer`] for those. When the layers
/// are chained, existing route decisions are preserved by default. Opt into
/// overwriting only when this address is authoritative. Use
/// [`LazyProxyAddressLayer`] when environment lookup should happen only if
/// no higher-priority route has already been selected.
///
/// See [`ProxyAddressService`] for more information.
///
/// [`Extensions`]: rama_core::extensions::Extensions
/// [`SystemProxyLayer`]: crate::client::SystemProxyLayer
pub struct ProxyAddressLayer {
    address: Option<ProxyAddress>,
    overwrite: bool,
}

impl ProxyAddressLayer {
    /// Create a new [`ProxyAddressLayer`] that will create
    /// a service to set the given [`ProxyAddress`] as a proxied [`ProxyRoute`].
    #[must_use]
    pub fn new(address: ProxyAddress) -> Self {
        Self::maybe(Some(address))
    }

    /// Create a new [`ProxyAddressLayer`] which will create
    /// a service that will set the given [`ProxyAddress`] as a proxied [`ProxyRoute`] if it is not
    /// `None`.
    #[must_use]
    pub fn maybe(address: Option<ProxyAddress>) -> Self {
        Self {
            address,
            ..Default::default()
        }
    }

    /// Return the configured proxy address, when this layer has one.
    #[must_use]
    pub const fn proxy_address(&self) -> Option<&ProxyAddress> {
        self.address.as_ref()
    }

    /// Try to create a new [`ProxyAddressLayer`] which will establish
    /// a proxy connection over the environment variable `http_proxy`.
    ///
    /// Uppercase `HTTP_PROXY` is deliberately not accepted by default because
    /// CGI derives it from an incoming `Proxy` header. Use
    /// [`ProxyEnvLayer`] for curl-compatible HTTP, HTTPS, and all-protocol
    /// environment selection.
    ///
    /// [`ProxyEnvLayer`]: crate::client::ProxyEnvLayer
    pub fn try_from_env_default() -> Result<Self, BoxError> {
        Self::try_from_env("http_proxy")
    }

    /// Try to create a new [`ProxyAddressLayer`] which will establish
    /// a proxy connection over the given environment variable.
    pub fn try_from_env(key: impl AsRef<str>) -> Result<Self, BoxError> {
        proxy_address_from_env(key.as_ref()).map(Self::maybe)
    }

    rama_utils::macros::generate_set_and_with! {
        /// Replace an existing [`ProxyRoute`] or [`ProxyRoutes`] decision.
        /// Existing routes are preserved by default.
        pub fn overwrite(mut self, overwrite: bool) -> Self {
            self.overwrite = overwrite;
            self
        }
    }
}

impl<S> Layer<S> for ProxyAddressLayer {
    type Service = ProxyAddressService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        ProxyAddressService::maybe(inner, self.address.clone()).with_overwrite(self.overwrite)
    }

    fn into_layer(self, inner: S) -> Self::Service {
        ProxyAddressService::maybe(inner, self.address).with_overwrite(self.overwrite)
    }
}

/// Service produced by [`ProxyAddressLayer`].
///
/// [`Extensions`]: rama_core::extensions::Extensions
#[derive(Debug, Clone)]
pub struct ProxyAddressService<S> {
    inner: S,
    proxy_info: Option<ProxyAddress>,
    overwrite: bool,
}

impl<S> ProxyAddressService<S> {
    /// Create a new [`ProxyAddressService`] that will create
    /// a service to set the given [`ProxyAddress`] as a proxied [`ProxyRoute`].
    pub const fn new(inner: S, address: ProxyAddress) -> Self {
        Self::maybe(inner, Some(address))
    }

    /// Create a new [`ProxyAddressService`] which will create
    /// a service that will set the given [`ProxyAddress`] as a proxied [`ProxyRoute`] if it is not
    /// `None`.
    pub const fn maybe(inner: S, address: Option<ProxyAddress>) -> Self {
        Self {
            inner,
            proxy_info: address,
            overwrite: false,
        }
    }

    /// Try to create a new [`ProxyAddressService`] which will establish
    /// a proxy connection over the environment variable `http_proxy`.
    ///
    /// Uppercase `HTTP_PROXY` is deliberately not accepted by default because
    /// CGI derives it from an incoming `Proxy` header. Use
    /// [`ProxyEnvLayer`] for curl-compatible HTTP, HTTPS, and all-protocol
    /// environment selection.
    ///
    /// [`ProxyEnvLayer`]: crate::client::ProxyEnvLayer
    pub fn try_from_env_default(inner: S) -> Result<Self, BoxError> {
        Self::try_from_env(inner, "http_proxy")
    }

    /// Try to create a new [`ProxyAddressService`] which will establish
    /// a proxy connection over the given environment variable.
    pub fn try_from_env(inner: S, key: impl AsRef<str>) -> Result<Self, BoxError> {
        proxy_address_from_env(key.as_ref()).map(|address| Self::maybe(inner, address))
    }

    rama_utils::macros::generate_set_and_with! {
        /// Replace an existing [`ProxyRoute`] or [`ProxyRoutes`] decision.
        /// Existing routes are preserved by default.
        pub fn overwrite(mut self, overwrite: bool) -> Self {
            self.overwrite = overwrite;
            self
        }
    }
}

type ProxyAddressLoader =
    dyn Fn() -> Result<Option<ProxyAddress>, BoxError> + Send + Sync + 'static;

type CachedProxyAddress = Result<Option<ProxyAddress>, CachedLoadError>;

/// Lazily resolve and apply a proxy address to any input with extensions.
///
/// Existing routes are preserved by default, in which case the loader is not
/// consulted if a [`ProxyRoute`] or [`ProxyRoutes`] decision exists. Otherwise,
/// its result is cached and shared by every clone of the layer and service.
/// This is useful for environment configuration that may never be needed.
#[derive(Clone)]
pub struct LazyProxyAddressLayer {
    loader: Arc<ProxyAddressLoader>,
    cached: Arc<OnceLock<CachedProxyAddress>>,
    load_error_policy: LoadErrorPolicy,
    overwrite: bool,
}

impl fmt::Debug for LazyProxyAddressLayer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LazyProxyAddressLayer")
            .field("cached", &self.cached.get())
            .field("load_error_policy", &self.load_error_policy)
            .field("overwrite", &self.overwrite)
            .finish_non_exhaustive()
    }
}

impl LazyProxyAddressLayer {
    /// Create a lazy layer backed by a synchronous, non-blocking loader.
    ///
    /// The loader runs at most once, on the first request that does not already
    /// have a preserved route decision. Both success and failure are cached.
    #[must_use]
    pub fn new<F>(loader: F) -> Self
    where
        F: Fn() -> Result<Option<ProxyAddress>, BoxError> + Send + Sync + 'static,
    {
        Self {
            loader: Arc::new(loader),
            cached: Arc::new(OnceLock::new()),
            load_error_policy: LoadErrorPolicy::Reject,
            overwrite: false,
        }
    }

    /// Lazily read and parse the `http_proxy` environment variable on the
    /// first request without a preserved route.
    ///
    /// Uppercase `HTTP_PROXY` is deliberately not accepted by default because
    /// CGI derives it from an incoming `Proxy` header. Use
    /// [`ProxyEnvLayer`] for curl-compatible HTTP, HTTPS, and all-protocol
    /// environment selection.
    ///
    /// [`ProxyEnvLayer`]: crate::client::ProxyEnvLayer
    #[must_use]
    pub fn from_env_default() -> Self {
        Self::from_env("http_proxy")
    }

    /// Lazily read and parse a proxy address from the named environment
    /// variable on the first request without a preserved route.
    #[must_use]
    pub fn from_env(key: impl Into<String>) -> Self {
        let key = key.into();
        Self::new(move || proxy_address_from_env(&key))
    }

    rama_utils::macros::generate_set_and_with! {
        /// Handle a loader error through an [`ErrorSink`] and continue without
        /// selecting a proxy. By default loader errors reject the request.
        ///
        /// The sink is invoked at most once because the handled result is
        /// cached and shared by every clone of this layer and its service.
        pub fn load_error_sink(
            mut self,
            sink: impl ErrorSink,
        ) -> Self {
            self.load_error_policy = LoadErrorPolicy::Handle(Arc::new(sink));
            self.cached = Arc::new(OnceLock::new());
            self
        }
    }

    rama_utils::macros::generate_set_and_with! {
        /// Replace an existing [`ProxyRoute`] or [`ProxyRoutes`] decision.
        /// Existing routes are preserved by default.
        pub fn overwrite(mut self, overwrite: bool) -> Self {
            self.overwrite = overwrite;
            self
        }
    }
}

impl<S> Layer<S> for LazyProxyAddressLayer {
    type Service = LazyProxyAddressService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        LazyProxyAddressService {
            inner,
            loader: self.loader.clone(),
            cached: self.cached.clone(),
            load_error_policy: self.load_error_policy.clone(),
            overwrite: self.overwrite,
        }
    }

    fn into_layer(self, inner: S) -> Self::Service {
        LazyProxyAddressService {
            inner,
            loader: self.loader,
            cached: self.cached,
            load_error_policy: self.load_error_policy,
            overwrite: self.overwrite,
        }
    }
}

/// Service produced by [`LazyProxyAddressLayer`].
#[derive(Clone)]
pub struct LazyProxyAddressService<S> {
    inner: S,
    loader: Arc<ProxyAddressLoader>,
    cached: Arc<OnceLock<CachedProxyAddress>>,
    load_error_policy: LoadErrorPolicy,
    overwrite: bool,
}

impl<S: fmt::Debug> fmt::Debug for LazyProxyAddressService<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LazyProxyAddressService")
            .field("inner", &self.inner)
            .field("cached", &self.cached.get())
            .field("load_error_policy", &self.load_error_policy)
            .field("overwrite", &self.overwrite)
            .finish_non_exhaustive()
    }
}

impl<S, Input> Service<Input> for LazyProxyAddressService<S>
where
    S: Service<Input, Error: Into<BoxError>>,
    Input: ExtensionsRef + Send + 'static,
{
    type Output = S::Output;
    type Error = BoxError;

    async fn serve(&self, input: Input) -> Result<Self::Output, Self::Error> {
        if !self.overwrite
            && (input.extensions().contains::<ProxyRoute>()
                || input.extensions().contains::<ProxyRoutes>())
        {
            return self.inner.serve(input).await.map_err(Into::into);
        }

        let proxy_info = self.cached.get_or_init(|| match (self.loader)() {
            Ok(proxy_info) => Ok(proxy_info),
            Err(error) => self.load_error_policy.handle_cached(error, None),
        });
        let proxy_info = match proxy_info {
            Ok(proxy_info) => proxy_info,
            Err(error) => return Err(Box::new(error.clone())),
        };

        if let Some(proxy_info) = proxy_info {
            tracing::trace!(
                server.address = %proxy_info.address.host,
                server.port = proxy_info.address.port,
                "setting lazily resolved proxy address",
            );
            input
                .extensions()
                .insert(ProxyRoute::Proxy(proxy_info.clone()));
        }

        self.inner.serve(input).await.map_err(Into::into)
    }
}

impl<S, Input> Service<Input> for ProxyAddressService<S>
where
    S: Service<Input>,
    Input: ExtensionsRef + Send + 'static,
{
    type Output = S::Output;
    type Error = S::Error;

    fn serve(
        &self,
        input: Input,
    ) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send + '_ {
        if let Some(ref proxy_info) = self.proxy_info
            && (self.overwrite
                || (!input.extensions().contains::<ProxyRoute>()
                    && !input.extensions().contains::<ProxyRoutes>()))
        {
            tracing::trace!(
                server.address = %proxy_info.address.host,
                server.port = proxy_info.address.port,
                "setting proxy address",
            );
            input
                .extensions()
                .insert(ProxyRoute::Proxy(proxy_info.clone()));
        }
        self.inner.serve(input)
    }
}

#[cfg(test)]
mod tests {
    use std::{
        convert::Infallible,
        sync::{
            Arc,
            atomic::{AtomicUsize, Ordering},
        },
    };

    use parking_lot::Mutex;
    use rama_core::{Layer as _, Service as _, extensions::Extensions, service::service_fn};

    use super::*;

    #[derive(Debug, Clone)]
    struct TestInput {
        extensions: Extensions,
    }

    impl TestInput {
        fn new() -> Self {
            Self {
                extensions: Extensions::new(),
            }
        }
    }

    impl ExtensionsRef for TestInput {
        fn extensions(&self) -> &Extensions {
            &self.extensions
        }
    }

    #[tokio::test]
    async fn preserve_respects_singular_and_collected_route_decisions() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let inner = service_fn({
            let seen = seen.clone();
            move |request: TestInput| {
                seen.lock().push((
                    request.extensions().contains::<ProxyRoute>(),
                    request.extensions().contains::<ProxyRoutes>(),
                ));
                async { Ok::<_, Infallible>(()) }
            }
        });
        let layer = ProxyAddressLayer::new("http://proxy.example:8080".parse().unwrap())
            .with_overwrite(false);
        let service = layer.into_layer(inner);

        let singular = TestInput::new();
        singular.extensions().insert(ProxyRoute::Direct);
        service.serve(singular).await.unwrap();

        let collected = TestInput::new();
        collected
            .extensions()
            .insert(ProxyRoutes::from(ProxyRoute::Direct));
        service.serve(collected).await.unwrap();

        let undecided = TestInput::new();
        service.serve(undecided).await.unwrap();

        assert_eq!(
            seen.lock().as_slice(),
            [(true, false), (false, true), (true, false)]
        );
    }

    #[tokio::test]
    async fn overwrite_replaces_an_authoritative_plural_plan() {
        let proxy: ProxyAddress = "http://new.proxy:8080".parse().unwrap();
        let service = ProxyAddressLayer::new(proxy.clone())
            .with_overwrite(true)
            .into_layer(
                crate::client::ProxyRoutesLayer::new().into_layer(service_fn(
                    |request: TestInput| async move {
                        let route = request.extensions().get_ref::<ProxyRoute>().cloned();
                        Ok::<_, Infallible>(route)
                    },
                )),
            );
        let request = TestInput::new();
        request
            .extensions()
            .insert(ProxyRoutes::new([ProxyRoute::Direct, ProxyRoute::Direct]));

        assert_eq!(
            service.serve(request).await.unwrap(),
            Some(ProxyRoute::Proxy(proxy))
        );
    }

    #[tokio::test]
    async fn lazy_loader_skips_preserved_routes_and_shares_cached_result() {
        let calls = Arc::new(AtomicUsize::new(0));
        let proxy: ProxyAddress = "http://proxy.example:8080".parse().unwrap();
        let layer = LazyProxyAddressLayer::new({
            let calls = calls.clone();
            let proxy = proxy.clone();
            move || {
                calls.fetch_add(1, Ordering::AcqRel);
                Ok(Some(proxy.clone()))
            }
        })
        .with_overwrite(false);

        let seen = Arc::new(Mutex::new(Vec::new()));
        let service = layer.into_layer(service_fn({
            let seen = seen.clone();
            move |request: TestInput| {
                seen.lock().push((
                    request.extensions().get_ref::<ProxyRoute>().cloned(),
                    request.extensions().contains::<ProxyRoutes>(),
                ));
                async { Ok::<_, Infallible>(()) }
            }
        }));
        let cloned_service = service.clone();

        let singular = TestInput::new();
        singular.extensions().insert(ProxyRoute::Direct);
        service.serve(singular).await.unwrap();

        let collected = TestInput::new();
        collected
            .extensions()
            .insert(ProxyRoutes::from(ProxyRoute::Direct));
        service.serve(collected).await.unwrap();
        assert_eq!(calls.load(Ordering::Acquire), 0);

        service.serve(TestInput::new()).await.unwrap();
        cloned_service.serve(TestInput::new()).await.unwrap();

        assert_eq!(calls.load(Ordering::Acquire), 1);
        assert_eq!(
            seen.lock().as_slice(),
            [
                (Some(ProxyRoute::Direct), false),
                (None, true),
                (Some(ProxyRoute::Proxy(proxy.clone())), false),
                (Some(ProxyRoute::Proxy(proxy)), false),
            ]
        );
    }

    #[tokio::test]
    async fn lazy_loader_caches_absence_and_failure() {
        let absent_calls = Arc::new(AtomicUsize::new(0));
        let absent_service = LazyProxyAddressLayer::new({
            let absent_calls = absent_calls.clone();
            move || {
                absent_calls.fetch_add(1, Ordering::AcqRel);
                Ok(None)
            }
        })
        .into_layer(service_fn(|request: TestInput| async move {
            Ok::<_, Infallible>(request.extensions().contains::<ProxyRoute>())
        }));

        assert!(!absent_service.serve(TestInput::new()).await.unwrap());
        assert!(!absent_service.serve(TestInput::new()).await.unwrap());
        assert_eq!(absent_calls.load(Ordering::Acquire), 1);

        let error_calls = Arc::new(AtomicUsize::new(0));
        let error_service = LazyProxyAddressLayer::new({
            let error_calls = error_calls.clone();
            move || {
                error_calls.fetch_add(1, Ordering::AcqRel);
                Err(std::io::Error::other("invalid proxy environment").into())
            }
        })
        .into_layer(service_fn(|_request: TestInput| async move {
            Ok::<_, Infallible>(())
        }));

        for _ in 0..2 {
            let error = error_service.serve(TestInput::new()).await.unwrap_err();
            assert_eq!(error.to_string(), "invalid proxy environment");
        }
        assert_eq!(error_calls.load(Ordering::Acquire), 1);
    }

    #[tokio::test]
    async fn handled_lazy_loader_error_is_sunk_once_and_treated_as_absent() {
        let loader_calls = Arc::new(AtomicUsize::new(0));
        let sink_calls = Arc::new(AtomicUsize::new(0));
        let service = LazyProxyAddressLayer::new({
            let loader_calls = loader_calls.clone();
            move || {
                loader_calls.fetch_add(1, Ordering::AcqRel);
                Err(std::io::Error::other("invalid proxy environment").into())
            }
        })
        .with_load_error_sink({
            let sink_calls = sink_calls.clone();
            move |error: BoxError| {
                assert_eq!(error.to_string(), "invalid proxy environment");
                sink_calls.fetch_add(1, Ordering::AcqRel);
            }
        })
        .into_layer(service_fn(|request: TestInput| async move {
            Ok::<_, Infallible>(request.extensions().contains::<ProxyRoute>())
        }));

        for _ in 0..2 {
            assert!(!service.serve(TestInput::new()).await.unwrap());
        }
        assert_eq!(loader_calls.load(Ordering::Acquire), 1);
        assert_eq!(sink_calls.load(Ordering::Acquire), 1);
    }
}