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
/*
 * Copyright 2022 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.
 */

use std::{io, sync::Arc, time::Duration};

use futures::{Stream, TryFutureExt};
use tokio_stream::StreamExt;
use tracing_futures::Instrument;

use crate::{
    discovery::{
        aggregated_discovery_service_server::{
            AggregatedDiscoveryService, AggregatedDiscoveryServiceServer,
        },
        DeltaDiscoveryRequest, DeltaDiscoveryResponse, DiscoveryRequest, DiscoveryResponse,
    },
    generated::quilkin::relay::v1alpha1::aggregated_control_plane_discovery_service_server::{
        AggregatedControlPlaneDiscoveryService, AggregatedControlPlaneDiscoveryServiceServer,
    },
    metrics,
    net::TcpListener,
};

pub struct ControlPlane<C> {
    pub config: Arc<C>,
    pub idle_request_interval: Duration,
    tx: tokio::sync::broadcast::Sender<&'static str>,
    pub is_relay: bool,
}

impl<C> Clone for ControlPlane<C> {
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            idle_request_interval: self.idle_request_interval,
            tx: self.tx.clone(),
            is_relay: self.is_relay,
        }
    }
}

impl<C: crate::config::Configuration> ControlPlane<C> {
    pub fn from_arc(config: Arc<C>, idle_request_interval: Duration) -> Self {
        let (tx, _) = tokio::sync::broadcast::channel(10);

        Self {
            config,
            idle_request_interval,
            tx,
            is_relay: false,
        }
    }

    pub fn management_server(
        mut self,
        listener: TcpListener,
    ) -> io::Result<impl std::future::Future<Output = crate::Result<()>>> {
        self.is_relay = false;
        tokio::spawn({
            let this = self.clone();
            self.config.on_changed(this)
        });

        let server = AggregatedDiscoveryServiceServer::new(self)
            .max_encoding_message_size(crate::config::max_grpc_message_size());
        let server = tonic::transport::Server::builder().add_service(server);
        tracing::info!("serving management server on port `{}`", listener.port());
        Ok(server
            .serve_with_incoming(listener.into_stream()?)
            .map_err(From::from))
    }

    pub fn relay_server(
        mut self,
        listener: TcpListener,
    ) -> io::Result<impl std::future::Future<Output = crate::Result<()>>> {
        self.is_relay = true;
        tokio::spawn({
            let this = self.clone();
            self.config.on_changed(this)
        });

        let server = AggregatedControlPlaneDiscoveryServiceServer::new(self)
            .max_encoding_message_size(crate::config::max_grpc_message_size());
        let server = tonic::transport::Server::builder().add_service(server);
        tracing::info!("serving relay server on port `{}`", listener.port());
        Ok(server
            .serve_with_incoming(listener.into_stream()?)
            .map_err(From::from))
    }

    #[inline]
    pub fn push_update(&self, resource_type: &'static str) {
        tracing::debug!(
            %resource_type,
            id = self.config.identifier(),
            is_relay = self.is_relay,
            "pushing update"
        );
        if self.tx.send(resource_type).is_err() {
            tracing::debug!("no client connections currently subscribed");
        }
    }

    pub async fn delta_aggregated_resources<S>(
        &self,
        mut streaming: S,
    ) -> Result<
        impl Stream<Item = Result<DeltaDiscoveryResponse, tonic::Status>> + Send,
        tonic::Status,
    >
    where
        S: Stream<Item = Result<DeltaDiscoveryRequest, tonic::Status>>
            + Send
            + std::marker::Unpin
            + 'static,
    {
        tracing::debug!("starting delta stream");
        let message = streaming.next().await.ok_or_else(|| {
            tracing::error!("No message found");
            tonic::Status::invalid_argument("No message found")
        })??;

        let node_id = if let Some(node) = &message.node {
            node.id.clone()
        } else {
            tracing::error!("Node identifier was not found");
            return Err(tonic::Status::invalid_argument("Node identifier required"));
        };

        let this = Self::clone(self);
        let mut rx = this.tx.subscribe();

        let id = this.config.identifier();
        tracing::debug!(
            id,
            client = node_id,
            count = this.tx.receiver_count(),
            is_relay = this.is_relay,
            "subscribed to config updates"
        );

        let control_plane_id = crate::core::ControlPlane {
            identifier: id.clone(),
        };

        use crate::config::ClientTracker;
        let mut client_tracker = ClientTracker::track_client(node_id.clone());

        let client = node_id.clone();
        let cfg = this.config.clone();
        let responder = move |req: Option<DeltaDiscoveryRequest>,
                              type_url: &str,
                              client_tracker: &mut ClientTracker|
              -> Result<Option<DeltaDiscoveryResponse>, tonic::Status> {
            let cs = if let Some(req) = req {
                metrics::delta_discovery_requests(&client, type_url).inc();

                let cs = if let Some(cs) = client_tracker.get_state(type_url) {
                    cs
                } else if cfg.allow_request_processing(type_url) {
                    client_tracker.track_state(type_url.into())
                } else {
                    return Err(tonic::Status::invalid_argument(format!(
                        "resource type '{type_url}' is not allowed by this stream"
                    )));
                };

                cs.update(req);
                tracing::debug!(kind = type_url, "sending delta update");

                cs
            } else {
                let Some(cs) = client_tracker.get_state(type_url) else {
                    return Ok(None);
                };

                tracing::debug!(kind = type_url, "sending delta for resource update");
                cs
            };

            let req = cfg
                .delta_discovery_request(cs)
                .map_err(|error| tonic::Status::internal(error.to_string()))?;

            if req.resources.is_empty() && req.removed.is_empty() {
                return Ok(None);
            }

            let removed_resources = req.removed.iter().cloned().collect();

            match client_tracker.needs_ack(crate::config::AwaitingAck {
                type_url: type_url.into(),
                removed: req.removed,
                versions: req
                    .resources
                    .iter()
                    .map(|res| (res.name.clone(), res.version.clone()))
                    .collect(),
            }) {
                Ok(nonce) => {
                    let response = DeltaDiscoveryResponse {
                        resources: req.resources,
                        nonce: nonce.to_string(),
                        control_plane: Some(control_plane_id.clone()),
                        type_url: type_url.into(),
                        removed_resources,
                        // Only used for debugging, not really useful
                        system_version_info: String::new(),
                    };

                    tracing::trace!(
                        r#type = &*response.type_url,
                        nonce = &*response.nonce,
                        "delta discovery response"
                    );

                    Ok(Some(response))
                }
                Err(error) => {
                    tracing::error!(%error, "server implementation returned invalid delta response");
                    Err(tonic::Status::internal(error.to_string()))
                }
            }
        };

        let nid = node_id.clone();

        let response = {
            if message.type_url == "ignore-me" {
                tracing::debug!(id, client = nid, "initial delta response");
                DeltaDiscoveryResponse {
                    resources: Vec::new(),
                    nonce: String::new(),
                    control_plane: None,
                    type_url: message.type_url,
                    removed_resources: Vec::new(),
                    // Only used for debugging, not really useful
                    system_version_info: String::new(),
                }
            } else {
                tracing::debug!(client = %node_id, resource_type = %message.type_url, "initial delta response");

                let type_url = message.type_url.clone();
                responder(Some(message), &type_url, &mut client_tracker)?.unwrap()
            }
        };

        let stream = async_stream::try_stream! {
            yield response;

            loop {
                tokio::select! {
                    // The resource(s) have changed, inform the connected client, but only
                    // send the changed resources that the client doesn't already have
                    res = rx.recv() => {
                        match res {
                            Ok(rt) => {
                                match responder(None, rt, &mut client_tracker) {
                                    Ok(Some(res)) => yield res,
                                    Ok(None) => {}
                                    Err(error) => {
                                        tracing::error!(%error, "responder failed to generate response");
                                        continue;
                                    },
                                }
                            }
                            Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                            Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                                let tracked_resources: Vec<_> = client_tracker.tracked_resources().collect();
                                for rt in tracked_resources {
                                    yield responder(None, &rt, &mut client_tracker)?.unwrap();
                                }
                            }
                        }
                    }
                    client_request = streaming.next() => {
                        let client_request = match client_request.transpose() {
                            Ok(Some(value)) => value,
                            Ok(None) => break,
                            Err(error) => {
                                tracing::error!(%error, "error receiving delta response");
                                continue;
                            }
                        };

                        if client_request.type_url == "ignore-me" {
                            continue;
                        }

                        let id = client_request.node.as_ref().map(|node| node.id.as_str()).unwrap_or(node_id.as_str());

                        tracing::trace!(resource_type = client_request.type_url, "new delta message");

                        if let Some(error) = &client_request.error_detail {
                            metrics::nacks(id, &client_request.type_url).inc();
                            tracing::error!(nonce = %client_request.response_nonce, ?error, "NACK");
                        } else if let Ok(nonce) = uuid::Uuid::parse_str(&client_request.response_nonce) {
                            match client_tracker.apply_ack(nonce) {
                                Ok(()) => {
                                    tracing::trace!(%nonce, "ACK");
                                }
                                Err(error) => {
                                    tracing::error!(%nonce, %error, "failed to process client ack");
                                }
                            }

                            metrics::delta_discovery_requests(id, &client_request.type_url).inc();
                            continue;
                        }

                        let type_url = client_request.type_url.clone();

                        let Some(response) = responder(Some(client_request), &type_url, &mut client_tracker).unwrap() else { continue; };
                        yield response;
                    }
                }
            }

            tracing::info!("terminating stream");
        };

        Ok(Box::pin(stream.instrument(tracing::info_span!(
            "xds_server_stream",
            id,
            client = nid
        ))))
    }
}

#[tonic::async_trait]
impl<C: crate::config::Configuration> AggregatedDiscoveryService for ControlPlane<C> {
    type StreamAggregatedResourcesStream =
        std::pin::Pin<Box<dyn Stream<Item = Result<DiscoveryResponse, tonic::Status>> + Send>>;
    type DeltaAggregatedResourcesStream =
        std::pin::Pin<Box<dyn Stream<Item = Result<DeltaDiscoveryResponse, tonic::Status>> + Send>>;

    #[tracing::instrument(skip_all)]
    async fn stream_aggregated_resources(
        &self,
        _request: tonic::Request<tonic::Streaming<DiscoveryRequest>>,
    ) -> Result<tonic::Response<Self::StreamAggregatedResourcesStream>, tonic::Status> {
        Err(tonic::Status::unimplemented(
            "only delta streams are supported",
        ))
    }

    #[tracing::instrument(skip_all)]
    async fn delta_aggregated_resources(
        &self,
        request: tonic::Request<tonic::Streaming<DeltaDiscoveryRequest>>,
    ) -> Result<tonic::Response<Self::DeltaAggregatedResourcesStream>, tonic::Status> {
        Ok(tonic::Response::new(Box::pin(
            self.delta_aggregated_resources(request.into_inner())
                .in_current_span()
                .await?,
        )))
    }
}

#[tonic::async_trait]
impl<C: crate::config::Configuration> AggregatedControlPlaneDiscoveryService for ControlPlane<C> {
    type StreamAggregatedResourcesStream =
        std::pin::Pin<Box<dyn Stream<Item = Result<DiscoveryRequest, tonic::Status>> + Send>>;
    type DeltaAggregatedResourcesStream =
        std::pin::Pin<Box<dyn Stream<Item = Result<DeltaDiscoveryRequest, tonic::Status>> + Send>>;

    #[tracing::instrument(skip_all)]
    async fn stream_aggregated_resources(
        &self,
        _responses: tonic::Request<tonic::Streaming<DiscoveryResponse>>,
    ) -> Result<tonic::Response<Self::StreamAggregatedResourcesStream>, tonic::Status> {
        Err(tonic::Status::unimplemented(
            "only delta streams are supported",
        ))
    }

    #[tracing::instrument(skip_all)]
    async fn delta_aggregated_resources(
        &self,
        responses: tonic::Request<tonic::Streaming<DeltaDiscoveryResponse>>,
    ) -> Result<tonic::Response<Self::DeltaAggregatedResourcesStream>, tonic::Status> {
        let remote_addr = responses
            .remote_addr()
            .ok_or_else(|| tonic::Status::invalid_argument("no remote address available"))?;

        tracing::info!("control plane discovery delta stream attempt");
        let mut responses = responses.into_inner();
        let Some(identifier) = responses
            .next()
            .await
            .ok_or_else(|| tonic::Status::cancelled("received empty first response"))??
            .control_plane
            .map(|cp| cp.identifier)
        else {
            return Err(tonic::Status::invalid_argument(
                "DeltaDiscoveryResponse.control_plane.identifier is required in the first message",
            ));
        };

        tracing::info!(identifier, "new control plane delta discovery stream");
        let config = self.config.clone();
        let idle_request_interval = self.idle_request_interval;

        let (ds, mut request_stream) = super::client::DeltaClientStream::new();

        let _handle: tokio::task::JoinHandle<crate::Result<()>> = tokio::task::spawn(
            async move {
                tracing::info!(identifier, "sending initial delta discovery request");

                let local = Arc::new(crate::config::LocalVersions::new(
                    config.interested_resources().map(|(n, _)| n),
                ));

                ds.refresh(&identifier, config.interested_resources().collect(), &local)
                    .await
                    .map_err(|error| tonic::Status::internal(error.to_string()))?;

                let mut response_stream = crate::config::handle_delta_discovery_responses(
                    identifier.clone(),
                    responses,
                    config.clone(),
                    local.clone(),
                    Some(remote_addr),
                    None,
                );

                loop {
                    let next_response =
                        tokio::time::timeout(idle_request_interval, response_stream.next());

                    if let Ok(Some(ack)) = next_response.await {
                        tracing::trace!("sending ack request");
                        ds.send_response(ack?)
                            .await
                            .map_err(|_| tonic::Status::internal("this should not be reachable"))?;
                    } else {
                        tracing::trace!("exceeded idle interval, sending request");
                        ds.refresh(&identifier, config.interested_resources().collect(), &local)
                            .await
                            .map_err(|error| tonic::Status::internal(error.to_string()))?;
                    }
                }
            }
            .instrument(tracing::trace_span!("handle_delta_discovery_response")),
        );

        Ok(tonic::Response::new(Box::pin(async_stream::stream! {
            loop {
                let Some(req) = request_stream.recv().await else { break; };
                yield Ok(req);
            }
        })))
    }
}