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
/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// We don't control the codegen, so disable any code warnings in the
// proto modules.
#[allow(warnings)]
mod xds {
    pub mod core {
        pub mod v3 {
            #![doc(hidden)]
            tonic::include_proto!("xds.core.v3");
        }
    }

    pub mod r#type {
        pub mod matcher {
            pub mod v3 {
                pub use super::super::super::config::common::matcher::v3::*;
                tonic::include_proto!("envoy.r#type.matcher.v3");
            }
        }
        pub mod metadata {
            pub mod v3 {
                tonic::include_proto!("envoy.r#type.metadata.v3");
            }
        }
        pub mod tracing {
            pub mod v3 {
                tonic::include_proto!("envoy.r#type.tracing.v3");
            }
        }
        pub mod v3 {
            tonic::include_proto!("envoy.r#type.v3");
        }
    }
    pub mod config {
        pub mod accesslog {
            pub mod v3 {
                tonic::include_proto!("envoy.config.accesslog.v3");
            }
        }
        pub mod cluster {
            pub mod v3 {
                tonic::include_proto!("envoy.config.cluster.v3");
            }
        }
        pub mod common {
            pub mod matcher {
                pub mod v3 {
                    tonic::include_proto!("envoy.config.common.matcher.v3");
                }
            }
        }
        pub mod core {
            pub mod v3 {
                tonic::include_proto!("envoy.config.core.v3");
            }
        }
        pub mod endpoint {
            pub mod v3 {
                tonic::include_proto!("envoy.config.endpoint.v3");
            }
        }
        pub mod listener {
            pub mod v3 {
                tonic::include_proto!("envoy.config.listener.v3");
            }
        }
        pub mod route {
            pub mod v3 {
                tonic::include_proto!("envoy.config.route.v3");
            }
        }
    }
    pub mod service {
        pub mod discovery {
            pub mod v3 {
                tonic::include_proto!("envoy.service.discovery.v3");

                impl TryFrom<DiscoveryResponse> for DiscoveryRequest {
                    type Error = eyre::Error;

                    fn try_from(response: DiscoveryResponse) -> Result<Self, Self::Error> {
                        Ok(Self {
                            version_info: response.version_info,
                            resource_names: response
                                .resources
                                .into_iter()
                                .map(crate::xds::Resource::try_from)
                                .map(|result| result.map(|resource| resource.name().to_owned()))
                                .collect::<Result<Vec<_>, _>>()?,
                            type_url: response.type_url,
                            response_nonce: response.nonce,
                            ..<_>::default()
                        })
                    }
                }
            }
        }
        pub mod cluster {
            pub mod v3 {
                tonic::include_proto!("envoy.service.cluster.v3");
            }
        }
    }
}

#[allow(warnings)]
mod google {
    pub mod rpc {
        tonic::include_proto!("google.rpc");
    }
}

pub(crate) mod client;
mod metrics;
mod resource;
pub(crate) mod server;

pub use client::Client;
pub use resource::{Resource, ResourceType};
pub use server::ControlPlane;
pub use service::discovery::v3::aggregated_discovery_service_client::AggregatedDiscoveryServiceClient;
pub use xds::*;

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

    use std::sync::Arc;

    use crate::{config::Config, endpoint::Endpoint, filters::*};

    #[tokio::test]
    async fn token_routing() {
        let mut helper = crate::test_utils::TestHelper::default();
        let token = uuid::Uuid::new_v4().into_bytes();
        let address = {
            let mut addr = Endpoint::new(helper.run_echo_server().await);
            addr.metadata.known.tokens.insert(token.into());
            addr
        };
        let localities = crate::endpoint::LocalityEndpoints::from(address.clone());

        let xds_port = crate::test_utils::available_addr().await.port();
        let xds_config: Arc<Config> = serde_json::from_value(serde_json::json!({
            "admin": null,
            "version": "v1alpha1",
            "id": "test-proxy",
            "port": xds_port,
            "clusters": {
                "default": {
                    "localities": [localities]
                }
            },
        }))
        .map(Arc::new)
        .unwrap();

        let client_addr = crate::test_utils::available_addr().await;
        let client_config: Config = serde_json::from_value(serde_json::json!({
            "version": "v1alpha1",
            "admin": null,
            "id": "test-proxy",
            "port": client_addr.port(),
            "management_servers": [{
                "address": format!("http://0.0.0.0:{}", xds_port),
            }]
        }))
        .unwrap();

        // Test that the client can handle the manager dropping out.
        let handle = tokio::spawn(server::spawn(xds_config.clone()));

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        let (_shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(());
        tokio::spawn(server::spawn(xds_config.clone()));
        tokio::spawn(
            crate::Proxy::try_from(client_config)
                .unwrap()
                .run(shutdown_rx),
        );
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        handle.abort();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        tokio::spawn(server::spawn(xds_config.clone()));
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        const VERSION_KEY: &str = "quilkin.dev/load_balancer/version";
        const TOKEN_KEY: &str = "quilkin.dev/load_balancer/token";

        xds_config.filters.store(Arc::new(
            [
                Capture::as_filter_config(capture::Config {
                    metadata_key: VERSION_KEY.into(),
                    strategy: capture::Suffix {
                        size: 1,
                        remove: true,
                    }
                    .into(),
                })
                .unwrap(),
                Match::as_filter_config(r#match::Config {
                    on_write: None,
                    on_read: Some(r#match::DirectionalConfig {
                        metadata_key: VERSION_KEY.into(),
                        branches: vec![r#match::Branch {
                            value: 1.into(),
                            filter: Capture::as_filter_config(capture::Config {
                                metadata_key: TOKEN_KEY.into(),
                                strategy: capture::Suffix {
                                    size: 16,
                                    remove: true,
                                }
                                .into(),
                            })
                            .unwrap(),
                        }],
                        fallthrough: <_>::default(),
                    }),
                })
                .unwrap(),
                Match::as_filter_config(r#match::Config {
                    on_write: None,
                    on_read: Some(r#match::DirectionalConfig {
                        metadata_key: VERSION_KEY.into(),
                        branches: vec![r#match::Branch {
                            value: 1.into(),
                            filter: TokenRouter::as_filter_config(token_router::Config {
                                metadata_key: TOKEN_KEY.into(),
                            })
                            .unwrap(),
                        }],
                        fallthrough: <_>::default(),
                    }),
                })
                .unwrap(),
            ]
            .try_into()
            .unwrap(),
        ));

        let client = tokio::net::UdpSocket::bind((std::net::Ipv4Addr::UNSPECIFIED, 0))
            .await
            .unwrap();

        let data = "Hello World!".as_bytes();
        let mut packet = data.to_vec();
        packet.extend(token);
        packet.push(1);

        client
            .send_to(
                &packet,
                (std::net::Ipv4Addr::UNSPECIFIED, client_addr.port()),
            )
            .await
            .unwrap();
        let mut buf = vec![0; 12];
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            client.recv_from(&mut buf),
        )
        .await
        .unwrap()
        .unwrap();

        assert_eq!(data, buf);
    }

    #[tokio::test]
    async fn basic() {
        let config: Arc<Config> = serde_json::from_value(serde_json::json!({
            "version": "v1alpha1",
            "admin": null,
            "id": "test-proxy",
            "port": 23456u16,
            "management_servers": [{
                "address": "http://127.0.0.1:23456",
            }]
        }))
        .map(Arc::new)
        .unwrap();

        tokio::spawn(server::spawn(config.clone()));
        let client = Client::connect(config.clone()).await.unwrap();
        let mut stream = client.stream().await.unwrap();

        // Each time, we create a new upstream endpoint and send a cluster update for it.
        let concat_bytes = vec![("b", "c,"), ("d", "e")];
        for (b1, b2) in concat_bytes.into_iter() {
            let socket = std::net::UdpSocket::bind((std::net::Ipv4Addr::UNSPECIFIED, 0)).unwrap();
            let local_addr: crate::endpoint::EndpointAddress = socket.local_addr().unwrap().into();

            config.clusters.modify(|clusters| {
                let cluster = clusters.default_cluster_mut();
                cluster.localities.clear();
                cluster.insert(Endpoint::new(local_addr.clone()))
            });

            let filters = crate::filters::FilterChain::try_from(vec![
                ConcatenateBytes::as_filter_config(concatenate_bytes::Config {
                    on_read: concatenate_bytes::Strategy::Append,
                    on_write: <_>::default(),
                    bytes: b1.as_bytes().to_vec(),
                })
                .unwrap(),
                ConcatenateBytes::as_filter_config(concatenate_bytes::Config {
                    on_read: concatenate_bytes::Strategy::Append,
                    on_write: <_>::default(),
                    bytes: b2.as_bytes().to_vec(),
                })
                .unwrap(),
            ])
            .unwrap();

            config.filters.modify(|chain| *chain = filters.clone());

            stream.send(ResourceType::Cluster, &[]).await.unwrap();
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            assert_eq!(
                local_addr,
                config
                    .clusters
                    .load()
                    .get_default()
                    .unwrap()
                    .endpoints()
                    .next()
                    .unwrap()
                    .address
            );

            stream.send(ResourceType::Listener, &[]).await.unwrap();
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            let changed_filters = config.filters.load();

            assert_eq!(changed_filters.len(), 2);

            let mut iter = changed_filters.iter();
            assert_eq!(iter.next().unwrap(), filters[0].clone().into());
            assert_eq!(iter.next().unwrap(), filters[1].clone().into());
        }
    }
}