camel-component-http 0.13.0

HTTP client component for rust-camel
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
use camel_component_api::{CamelError, Component, Consumer, Endpoint, ProducerContext};
use tower_http::services::ServeDir;

use crate::registry::{MountMode, StaticMount};
use crate::{HttpStaticConfig, ServerRegistry};

// ---------------------------------------------------------------------------
// HttpStaticComponent
// ---------------------------------------------------------------------------

/// Component factory for the `http-static:` scheme.
///
/// Creates [`HttpStaticEndpoint`] instances from URIs like
/// `http-static:/path/to/dir?port=8080&spaFallback=true`.
pub struct HttpStaticComponent {
    config: HttpStaticConfig,
}

impl HttpStaticComponent {
    pub fn new() -> Self {
        Self {
            config: HttpStaticConfig::default(),
        }
    }

    pub fn with_config(config: HttpStaticConfig) -> Self {
        Self { config }
    }
}

impl Default for HttpStaticComponent {
    fn default() -> Self {
        Self::new()
    }
}

impl Component for HttpStaticComponent {
    fn scheme(&self) -> &str {
        "http-static"
    }

    fn create_endpoint(
        &self,
        uri: &str,
        _ctx: &dyn camel_component_api::ComponentContext,
    ) -> Result<Box<dyn Endpoint>, CamelError> {
        let config = HttpStaticConfig::from_uri_with_defaults(uri, &self.config)?;
        Ok(Box::new(HttpStaticEndpoint {
            uri: uri.to_string(),
            config,
        }))
    }
}

// ---------------------------------------------------------------------------
// HttpStaticEndpoint
// ---------------------------------------------------------------------------

/// Endpoint for a static file serving route.
///
/// Holds the resolved [`HttpStaticConfig`] and creates [`HttpStaticConsumer`]
/// instances when the route starts.
pub struct HttpStaticEndpoint {
    uri: String,
    config: HttpStaticConfig,
}

impl Endpoint for HttpStaticEndpoint {
    fn uri(&self) -> &str {
        &self.uri
    }

    fn create_consumer(&self) -> Result<Box<dyn Consumer>, CamelError> {
        Ok(Box::new(HttpStaticConsumer {
            config: self.config.clone(),
        }))
    }

    fn create_producer(
        &self,
        _ctx: &ProducerContext,
    ) -> Result<camel_component_api::BoxProcessor, CamelError> {
        Err(CamelError::Config(
            "http-static endpoint does not support producers".to_string(),
        ))
    }
}

// ---------------------------------------------------------------------------
// HttpStaticConsumer
// ---------------------------------------------------------------------------

/// Consumer that registers a static file mount into the shared
/// [`HttpRouteRegistry`] and stays idle until cancelled.
///
/// On start:
/// 1. Canonicalizes the configured `dir` (fails if not found).
/// 2. Canonicalizes each `error_pages` path (fails if any don't exist).
/// 3. Builds a `ServeDir` for the directory.
/// 4. Registers a `StaticMount` into the registry.
///
/// On stop (cancellation):
/// - Unregisters the mount from the registry.
pub struct HttpStaticConsumer {
    config: HttpStaticConfig,
}

impl HttpStaticConsumer {
    /// Create a new `HttpStaticConsumer` from the given config.
    pub fn new(config: HttpStaticConfig) -> Self {
        Self { config }
    }
}

#[async_trait::async_trait]
impl Consumer for HttpStaticConsumer {
    async fn start(&mut self, ctx: camel_component_api::ConsumerContext) -> Result<(), CamelError> {
        // 1. Canonicalize dir
        let dir = std::fs::canonicalize(&self.config.dir).map_err(|e| {
            CamelError::Config(format!(
                "http-static directory not found: {}: {}",
                self.config.dir.display(),
                e
            ))
        })?;

        // 2. Canonicalize error_pages paths (resolved relative to dir)
        let mut error_pages = std::collections::HashMap::new();
        for (code, path) in &self.config.error_pages {
            let resolved = if path.is_absolute() {
                path.clone()
            } else {
                self.config.dir.join(path)
            };
            let canonical = std::fs::canonicalize(&resolved).map_err(|e| {
                CamelError::Config(format!(
                    "http-static error page not found for status {}: {}: {}",
                    code,
                    resolved.display(),
                    e
                ))
            })?;
            error_pages.insert(*code, canonical);
        }

        // 3. Build ServeDir
        let serve_dir = ServeDir::new(&dir)
            .precompressed_gzip()
            .precompressed_br()
            .append_index_html_on_directories(true);

        // 4. Get registry
        let registry = ServerRegistry::global()
            .get_or_spawn(
                &self.config.host,
                self.config.port,
                2 * 1024 * 1024,  // max_request_body (not used for static)
                10 * 1024 * 1024, // max_response_body (not used for static)
                1024,             // max_inflight_requests
            )
            .await?;

        // 5. Register mount
        let mode = if self.config.spa_fallback {
            MountMode::Spa
        } else {
            MountMode::Static
        };
        let mount = StaticMount {
            mount_path: self.config.mount_path.clone(),
            mode,
            dir: dir.clone(),
            cache_control: self.config.cache_control.clone(),
            error_pages,
            serve_dir,
        };

        registry.register_static_mount(mount).await?;

        let mount_path_for_cleanup = self.config.mount_path.clone();
        let registry_for_cleanup = registry.clone();

        // 6. Wait on cancellation token
        ctx.cancelled().await;

        // 7. Unregister on stop (by mount_path identity)
        registry_for_cleanup
            .unregister_static_mount(&mount_path_for_cleanup)
            .await;

        Ok(())
    }

    async fn stop(&mut self) -> Result<(), CamelError> {
        Ok(())
    }

    fn concurrency_model(&self) -> camel_component_api::ConcurrencyModel {
        camel_component_api::ConcurrencyModel::Sequential
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::REGISTRY_TEST_MUTEX;
    use camel_component_api::{ConsumerContext, ExchangeEnvelope};
    use std::path::PathBuf;
    use std::sync::Arc;
    use tokio::sync::{Notify, mpsc};
    use tokio_util::sync::CancellationToken;

    /// Helper: create a test consumer context with a controllable cancellation.
    fn test_consumer_ctx(notify: Arc<Notify>) -> ConsumerContext {
        let (tx, _rx) = mpsc::channel::<ExchangeEnvelope>(16);
        let token = CancellationToken::new();
        // Spawn a task that cancels when notified
        let token_clone = token.clone();
        tokio::spawn(async move {
            notify.notified().await;
            token_clone.cancel();
        });
        ConsumerContext::new(tx, token)
    }

    #[test]
    fn test_component_scheme() {
        let component = HttpStaticComponent::new();
        assert_eq!(component.scheme(), "http-static");
    }

    #[test]
    fn test_component_with_config() {
        let config = HttpStaticConfig {
            dir: PathBuf::from("/tmp"),
            port: 9999,
            ..HttpStaticConfig::default()
        };
        let component = HttpStaticComponent::with_config(config.clone());
        assert_eq!(component.scheme(), "http-static");
    }

    #[test]
    fn test_endpoint_creates_consumer() {
        let config = HttpStaticConfig {
            dir: PathBuf::from("/tmp"),
            ..HttpStaticConfig::default()
        };
        let endpoint = HttpStaticEndpoint {
            uri: "http-static:/tmp".to_string(),
            config,
        };
        let consumer = endpoint.create_consumer();
        assert!(consumer.is_ok());
    }

    #[test]
    fn test_endpoint_producer_not_supported() {
        let config = HttpStaticConfig {
            dir: PathBuf::from("/tmp"),
            ..HttpStaticConfig::default()
        };
        let endpoint = HttpStaticEndpoint {
            uri: "http-static:/tmp".to_string(),
            config,
        };
        let ctx = camel_component_api::ProducerContext::new();
        let result = endpoint.create_producer(&ctx);
        assert!(result.is_err());
        if let Err(CamelError::Config(msg)) = result {
            assert!(msg.contains("does not support producers"));
        } else {
            panic!("Expected Config error");
        }
    }

    #[tokio::test]
    async fn test_consumer_start_nonexistent_dir_returns_error() {
        let config = HttpStaticConfig {
            dir: PathBuf::from("/nonexistent/path/that/does/not/exist"),
            port: 19900,
            ..HttpStaticConfig::default()
        };
        let mut consumer = HttpStaticConsumer::new(config);
        let notify = Arc::new(Notify::new());
        let ctx = test_consumer_ctx(notify);

        let result = consumer.start(ctx).await;
        assert!(result.is_err());
        if let Err(CamelError::Config(msg)) = result {
            assert!(msg.contains("directory not found"));
        } else {
            panic!("Expected Config error for nonexistent dir");
        }
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn test_consumer_start_registers_mount_in_registry() {
        let _guard = REGISTRY_TEST_MUTEX.lock().unwrap();
        // Reset registry for clean test
        ServerRegistry::reset();

        let dir = std::env::temp_dir();
        let canonical_dir = std::fs::canonicalize(&dir).unwrap();

        // Bind to a free port first
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        drop(listener);

        let config = HttpStaticConfig {
            dir: dir.clone(),
            port,
            host: "127.0.0.1".to_string(),
            ..HttpStaticConfig::default()
        };

        // Build ServeDir directly (same as consumer does)
        let serve_dir = ServeDir::new(&canonical_dir)
            .precompressed_gzip()
            .precompressed_br()
            .append_index_html_on_directories(true);

        // Get registry (this spawns the axum server)
        let registry = ServerRegistry::global()
            .get_or_spawn("127.0.0.1", port, 2 * 1024 * 1024, 10 * 1024 * 1024, 1024)
            .await
            .unwrap();

        // Register mount
        let mount = StaticMount {
            mount_path: "/".to_string(),
            mode: MountMode::Static,
            dir: canonical_dir.clone(),
            cache_control: config.cache_control.clone(),
            error_pages: std::collections::HashMap::new(),
            serve_dir,
        };
        registry.register_static_mount(mount).await.unwrap();

        // Verify registered
        let inner = registry.inner.read().await;
        assert_eq!(
            inner.mounts.len(),
            1,
            "Expected one static mount registered"
        );
        assert_eq!(inner.mounts[0].dir, canonical_dir);
        assert_eq!(inner.mounts[0].mount_path, "/");
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn test_consumer_stop_unregisters_mount() {
        let _guard = REGISTRY_TEST_MUTEX.lock().unwrap();
        // Reset registry for clean test
        ServerRegistry::reset();

        let dir = std::env::temp_dir();
        let canonical_dir = std::fs::canonicalize(&dir).unwrap();

        // Bind to a free port
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        drop(listener);

        // Get registry
        let registry = ServerRegistry::global()
            .get_or_spawn("127.0.0.1", port, 2 * 1024 * 1024, 10 * 1024 * 1024, 1024)
            .await
            .unwrap();

        // Register mount
        let serve_dir = ServeDir::new(&canonical_dir)
            .precompressed_gzip()
            .precompressed_br()
            .append_index_html_on_directories(true);
        let mount = StaticMount {
            mount_path: "/".to_string(),
            mode: MountMode::Static,
            dir: canonical_dir.clone(),
            cache_control: "public, max-age=0".to_string(),
            error_pages: std::collections::HashMap::new(),
            serve_dir,
        };
        registry.register_static_mount(mount).await.unwrap();

        // Verify registered
        {
            let inner = registry.inner.read().await;
            assert_eq!(inner.mounts.len(), 1);
        }

        // Unregister by mount_path
        registry.unregister_static_mount("/").await;

        // Verify unregistered
        let inner = registry.inner.read().await;
        assert_eq!(
            inner.mounts.len(),
            0,
            "Expected static mount to be unregistered"
        );
    }
}