easyhttpmock-vetis-compio 0.1.0

EasyHttpMock adapter for Vetis HTTP server using compio runtime.
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
use caramelo::expect;
use easyhttpmock::{
    errors::{EasyHttpMockError, MockError, ServerError},
    mock::{Mock, Request},
    server::{generate_randon_port, PortGenerator, ServerAdapter},
    HttpMockResult,
};
use http_body_util::BodyExt;
use std::sync::Arc;
use vetis_compio::{
    handler_fn,
    http::Response,
    virtual_host::{path::HandlerPath, VirtualHostImpl},
    Protocol, ServerConfig, Vetis, VetisServer,
};

/// Builder for VetisAdapterConfig
pub struct VetisAdapterConfigBuilder {
    hostname: String,
    interface: String,
    protocol: Protocol,
    port: u16,
    cert: Option<Vec<u8>>,
    key: Option<Vec<u8>>,
    ca: Option<Vec<u8>>,
}

impl VetisAdapterConfigBuilder {
    /// Sets the hostname for the server.
    ///
    /// # Arguments
    /// * `hostname` - The hostname to set.
    ///
    /// # Returns
    /// A new `VetisAdapterConfigBuilder` instance with the hostname set.
    pub fn hostname(mut self, hostname: &str) -> Self {
        self.hostname = hostname.to_string();
        self
    }

    /// Sets the interface for the server.
    ///
    /// # Arguments
    /// * `interface` - The interface to set.
    ///
    /// # Returns
    /// A new `VetisAdapterConfigBuilder` instance with the interface set.
    pub fn interface(mut self, interface: &str) -> Self {
        self.interface = interface.to_string();
        self
    }

    /// Sets the protocol for the server.
    ///
    /// # Arguments
    /// * `protocol` - The protocol to set.
    ///
    /// # Returns
    /// A new `VetisAdapterConfigBuilder` instance with the protocol set.
    pub fn protocol(mut self, protocol: Protocol) -> Self {
        self.protocol = protocol;
        self
    }

    /// Sets the port for the server.
    ///
    /// # Arguments
    /// * `port` - The port to set.
    ///
    /// # Returns
    /// A new `VetisAdapterConfigBuilder` instance with the port set.
    pub fn port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Sets the certificate for the server.
    ///
    /// # Arguments
    /// * `cert` - The certificate to set.
    ///
    /// # Returns
    /// A new `VetisAdapterConfigBuilder` instance with the certificate set.
    pub fn cert(mut self, cert: Vec<u8>) -> Self {
        self.cert = Some(cert);
        self
    }

    /// Sets the key for the server.
    ///
    /// # Arguments
    /// * `key` - The key to set.
    ///
    /// # Returns
    /// A new `VetisAdapterConfigBuilder` instance with the key set.
    pub fn key(mut self, key: Vec<u8>) -> Self {
        self.key = Some(key);
        self
    }

    /// Sets the CA certificate for the server.
    ///
    /// # Arguments
    /// * `ca` - The CA certificate to set.
    ///
    /// # Returns
    /// A new `VetisAdapterConfigBuilder` instance with the CA certificate set.
    pub fn ca(mut self, ca: Vec<u8>) -> Self {
        self.ca = Some(ca);
        self
    }

    /// Builds the VetisAdapterConfig from the builder.
    ///
    /// # Returns
    /// A new `VetisAdapterConfig` instance.
    pub fn build(self) -> VetisAdapterConfig {
        VetisAdapterConfig {
            hostname: self.hostname,
            interface: self.interface,
            protocol: self.protocol,
            port: self.port,
            cert: self.cert,
            key: self.key,
            ca: self.ca,
        }
    }
}

/// Configuration for the Vetis adapter.
#[derive(Clone, PartialEq)]
pub struct VetisAdapterConfig {
    hostname: String,
    interface: String,
    protocol: Protocol,
    port: u16,
    cert: Option<Vec<u8>>,
    key: Option<Vec<u8>>,
    ca: Option<Vec<u8>>,
}

impl Default for VetisAdapterConfig {
    /// Creates a default configuration for the Vetis adapter.
    ///
    /// This function sets up a basic server configuration with:
    /// - Hostname: "localhost"
    /// - Interface: "0.0.0.0"
    /// - Port: random port between 9000 and 65535
    /// - No TLS certificates (HTTP only)
    ///
    /// # Returns
    /// A default `VetisAdapterConfig` instance.
    fn default() -> Self {
        Self {
            hostname: "localhost".into(),
            interface: "0.0.0.0".into(),
            protocol: Protocol::Http1,
            port: generate_randon_port(),
            cert: None,
            key: None,
            ca: None,
        }
    }
}

impl VetisAdapterConfig {
    /// Creates a new builder for the Vetis adapter configuration.
    ///
    /// This function sets up a basic server configuration with:
    /// - Hostname: "localhost"
    /// - Interface: "0.0.0.0"
    /// - Port: random port between 9000 and 65535
    /// - No TLS certificates (HTTP only)
    ///
    /// # Returns
    /// A new `VetisAdapterConfigBuilder` instance.
    pub fn builder() -> VetisAdapterConfigBuilder {
        VetisAdapterConfigBuilder {
            hostname: "localhost".into(),
            interface: "0.0.0.0".into(),
            protocol: Protocol::Http1,
            port: rand::random_range(9000..65535),
            cert: None,
            key: None,
            ca: None,
        }
    }

    /// Returns the hostname of the server.
    ///
    /// # Returns
    /// The hostname of the server.
    pub fn hostname(&self) -> &String {
        &self.hostname
    }

    /// Returns the interface of the server.
    ///
    /// # Returns
    /// The interface of the server.
    pub fn interface(&self) -> &str {
        &self.interface
    }

    /// Returns the port of the server.
    ///
    /// # Returns
    /// The port of the server.
    pub fn port(&self) -> u16 {
        self.port
    }

    /// Returns the certificate of the server.
    ///
    /// # Returns
    /// The certificate of the server.
    pub fn cert(&self) -> &Option<Vec<u8>> {
        &self.cert
    }

    /// Returns the key of the server.
    ///
    /// # Returns
    /// The key of the server.
    pub fn key(&self) -> &Option<Vec<u8>> {
        &self.key
    }

    /// Returns the CA certificate of the server.
    ///
    /// # Returns
    /// The CA certificate of the server.
    pub fn ca(&self) -> &Option<Vec<u8>> {
        &self.ca
    }
}

impl From<VetisAdapterConfig> for ServerConfig {
    fn from(config: VetisAdapterConfig) -> Self {
        let listener_config = vetis_compio::ListenerConfig::builder()
            .interface(&config.interface)
            .protocol(config.protocol)
            .port(config.port)
            .build()
            .expect("Failed to build listener config");
        ServerConfig::builder()
            .add_listener(listener_config)
            .build()
            .expect("Failed to build server config")
    }
}

#[derive(Default)]
/// Vetis adapter implementation
pub struct VetisAdapter {
    server: Vetis,
    config: VetisAdapterConfig,
    mock: Option<Arc<Mock>>,
}

impl PortGenerator<VetisAdapter> for VetisAdapterConfigBuilder {
    fn with_random_port(self) -> Self {
        let port = generate_randon_port();
        self.port(port)
    }
}

impl ServerAdapter for VetisAdapter {
    /// The configuration type for the adapter.
    type Config = VetisAdapterConfig;

    /// Creates a new VetisAdapter instance.
    ///
    /// # Arguments
    /// * `config` - The configuration for the adapter.
    ///
    /// # Returns
    /// A new `VetisAdapter` instance.
    fn new(config: Self::Config) -> Result<Self, EasyHttpMockError> {
        let vetis_config = config
            .clone()
            .into();

        let server = Vetis::new(vetis_config);

        Ok(Self { server, config, mock: None })
    }

    /// Returns the hostname of the server.
    ///
    /// # Returns
    /// The hostname of the server.
    fn hostname(&self) -> String {
        self.config
            .hostname()
            .clone()
    }

    /// Returns the base URL of the server.
    ///
    /// # Returns
    /// The base URL of the server.
    fn base_url(&self) -> String {
        let hostname = self.hostname();

        if self
            .config
            .cert
            .is_some()
        {
            format!("https://{}:{}", hostname, self.config.port())
        } else {
            format!("http://{}:{}", hostname, self.config.port())
        }
    }

    /// Returns the configuration of the server.
    ///
    /// # Returns
    /// The configuration of the server.
    fn config(&self) -> &Self::Config {
        &self.config
    }

    /// Returns the configuration of the server.
    ///
    /// # Returns
    /// The configuration of the server.
    fn config_mut(&mut self) -> &mut Self::Config {
        &mut self.config
    }

    /// Sets the mock to handle incoming requests.
    ///
    /// # Arguments
    ///
    /// * `mock` - The mock to handle incoming requests.
    ///
    /// # Returns
    ///
    /// * `Result<(), EasyHttpMockError>` - The result of the operation.
    ///
    fn register_mock(&mut self, mock: Arc<Mock>) {
        self.mock = Some(mock);
    }

    /// Starts the server with the given handler.
    ///
    /// # Arguments
    ///
    /// * `handler` - The handler to use for the server.
    ///
    /// # Returns
    ///
    /// A result indicating whether the server started successfully or a `EasyHttpMockError` if it failed.
    ///
    async fn start(&mut self) -> HttpMockResult<()> {
        let mock = match self.mock.as_ref() {
            Some(mocker) => mocker,
            None => return Err(MockError::Notfound.into()),
        };

        let mock_clone = mock.clone();
        let path = HandlerPath::builder()
            .uri("/")
            .handler(handler_fn(move |request| {
                // Since handler function is defined here, we need to clone the mocker
                // to move it into the async block
                let mock = mock_clone.clone();
                async move {
                    let (parts, body) = request.into_parts();

                    let mut data = Vec::<u8>::new();
                    let Ok(body_data) = body.collect().await else {
                        return Err(vetis_compio::errors::VetisError::Handler(
                            "Failed to collect body".to_string(),
                        ));
                    };

                    data.extend_from_slice(&body_data.to_bytes());

                    expect(Request::from_parts(parts)).to_match(
                        mock.request()
                            .matcher()
                            .clone(),
                    );

                    let respond = mock
                        .request()
                        .respond();

                    if let Some(respond) = respond {
                        Ok(Response::builder()
                            .status(respond.status_code())
                            .bytes(&respond.body()))
                    } else {
                        Err(vetis_compio::errors::VetisError::Handler(
                            "Missing respond mock".to_string(),
                        ))
                    }
                }
            }))
            .build();

        let hostname = self.hostname();

        let host_config = vetis_compio::VirtualHostConfig::builder()
            .hostname(&hostname)
            .root_directory(".")
            .port(self.config.port());

        let host_config = if let Some(((cert, key), ca)) = self
            .config
            .cert
            .as_ref()
            .zip(
                self.config
                    .key
                    .as_ref(),
            )
            .zip(
                self.config
                    .ca
                    .as_ref(),
            ) {
            host_config.security(
                vetis_compio::SecurityConfig::builder()
                    .cert_from_bytes(cert.clone())
                    .key_from_bytes(key.clone())
                    .ca_cert_from_bytes(ca.clone())
                    .build()
                    .map_err(|e| EasyHttpMockError::Server(ServerError::Config(e.to_string())))?,
            )
        } else {
            host_config
        };

        let host_config = host_config
            .build()
            .map_err(|e| EasyHttpMockError::Server(ServerError::Creation(e.to_string())))?;

        let mut host = VirtualHostImpl::new(host_config);
        if let Err(e) = path {
            return Err(EasyHttpMockError::Server(ServerError::Creation(e.to_string())));
        }

        host.add_path(path.unwrap());

        self.server
            .add_virtual_host(host)
            .await;

        self.server
            .start()
            .await
            .map_err(|e| EasyHttpMockError::Server(ServerError::Start(e.to_string())))
    }

    /// Stops the server.
    ///
    /// # Returns
    /// A result indicating whether the server stopped successfully.
    async fn stop(&mut self) -> HttpMockResult<()> {
        self.server
            .stop()
            .await
            .map_err(|e| EasyHttpMockError::Server(ServerError::Stop(e.to_string())))
    }
}