tonic/transport/channel/service/discover.rs
1/*
2 *
3 * Copyright 2025 gRPC authors.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to
7 * deal in the Software without restriction, including without limitation the
8 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 * sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 */
24
25use super::super::{Connection, Endpoint};
26
27use std::{
28 hash::Hash,
29 pin::Pin,
30 task::{Context, Poll},
31};
32use tokio::sync::mpsc::Receiver;
33use tokio_stream::Stream;
34use tower::discover::Change as TowerChange;
35
36/// A change in the service set.
37#[derive(Debug, Clone)]
38pub enum Change<K, V> {
39 /// A new service identified by key `K` was identified.
40 Insert(K, V),
41 /// The service identified by key `K` disappeared.
42 Remove(K),
43}
44
45pub(crate) struct DynamicServiceStream<K: Hash + Eq + Clone> {
46 changes: Receiver<Change<K, Endpoint>>,
47}
48
49impl<K: Hash + Eq + Clone> DynamicServiceStream<K> {
50 pub(crate) fn new(changes: Receiver<Change<K, Endpoint>>) -> Self {
51 Self { changes }
52 }
53}
54
55impl<K: Hash + Eq + Clone> Stream for DynamicServiceStream<K> {
56 type Item = Result<TowerChange<K, Connection>, crate::BoxError>;
57
58 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
59 match Pin::new(&mut self.changes).poll_recv(cx) {
60 Poll::Pending | Poll::Ready(None) => Poll::Pending,
61 Poll::Ready(Some(change)) => match change {
62 Change::Insert(k, endpoint) => {
63 let connection = Connection::lazy(endpoint.http_connector(), endpoint);
64 Poll::Ready(Some(Ok(TowerChange::Insert(k, connection))))
65 }
66 Change::Remove(k) => Poll::Ready(Some(Ok(TowerChange::Remove(k)))),
67 },
68 }
69 }
70}
71
72impl<K: Hash + Eq + Clone> Unpin for DynamicServiceStream<K> {}