endhost_api_client/client.rs
1// Copyright 2025 Anapaya Systems
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//! # Endhost API client
15//!
16//! An [EndhostApiClient] provides the application with the information
17//! necessary to send and receive SCION-packets in the routing domain that is
18//! associated with the endhost API.
19//!
20//! The implementation [CrpcEndhostApiClient] is a concrete implementation
21//! following the current specification of the endhost-API.
22//!
23//! ## Example Usage
24//!
25//! ```no_run
26//! use std::{net::SocketAddr, str::FromStr};
27//!
28//! use endhost_api_client::client::{CrpcEndhostApiClient, EndhostApiClient};
29//! use sciparse::identifier::isd_asn::IsdAsn;
30//!
31//! pub async fn get_all_udp_sockaddrs() -> anyhow::Result<Vec<SocketAddr>> {
32//! let crpc_client =
33//! CrpcEndhostApiClient::new(&url::Url::parse("http://10.0.0.1:48080/").unwrap())?;
34//!
35//! let res = crpc_client
36//! .list_underlays(IsdAsn::from_str("1-ff00:0:110").unwrap())
37//! .await?
38//! .udp_underlay
39//! .iter()
40//! .map(|router| router.internal_interface)
41//! .collect();
42//!
43//! Ok(res)
44//! }
45//! ```
46use std::{ops::Deref, sync::Arc};
47
48use endhost_api::routes::{
49 ENDHOST_API_V1, LIST_SEGMENTS, LIST_UNDERLAYS, SEGMENTS_SERVICE, UNDERLAY_SERVICE,
50};
51use endhost_api_models::underlays::Underlays;
52use endhost_api_protobuf::v1::{
53 ListSegmentsRequest, ListSegmentsResponse, ListUnderlaysRequest, ListUnderlaysResponse,
54};
55use reqwest_connect_rpc::{
56 client::{CrpcClient, CrpcClientError},
57 token_source::TokenSource,
58};
59use sciparse::{identifier::isd_asn::IsdAsn, rpc::FromRpcError, segment::SegmentsPage};
60
61/// Endhost API client trait.
62///
63/// This allows for a client mock implementation in tests.
64#[async_trait::async_trait]
65pub trait EndhostApiClient: Send + Sync {
66 /// List the available underlays for a given ISD-AS.
67 ///
68 /// # Arguments
69 /// * `isd_as` - The ISD-AS to list the underlays for. For a wildcard ISD AS
70 /// (`IsdAsn::WILDCARD`), all existing underlays will be returned.
71 ///
72 /// # Returns
73 /// A future that resolves to the list of underlays.
74 async fn list_underlays(&self, isd_as: IsdAsn) -> Result<Underlays, CrpcClientError>;
75 /// List the available segments between a source and destination ISD-AS.
76 ///
77 /// # Arguments
78 /// * `src` - The source ISD-AS.
79 /// * `dst` - The destination ISD-AS.
80 /// * `page_size` - The maximum number of segments to return.
81 /// * `page_token` - The token to use for pagination.
82 async fn list_segments(
83 &self,
84 src: IsdAsn,
85 dst: IsdAsn,
86 page_size: i32,
87 page_token: String,
88 ) -> Result<SegmentsPage, CrpcClientError>;
89}
90
91/// Connect RPC endhost API client.
92pub struct CrpcEndhostApiClient {
93 client: CrpcClient,
94}
95
96impl Deref for CrpcEndhostApiClient {
97 type Target = CrpcClient;
98
99 fn deref(&self) -> &Self::Target {
100 &self.client
101 }
102}
103
104impl CrpcEndhostApiClient {
105 /// Creates a new endhost API client from the given base URL.
106 pub fn new(base_url: &url::Url) -> anyhow::Result<Self> {
107 Ok(CrpcEndhostApiClient {
108 client: CrpcClient::new(base_url)?,
109 })
110 }
111
112 /// Creates a new endhost API client from the given base URL and [`reqwest::Client`].
113 pub fn new_with_client(base_url: &url::Url, client: reqwest::Client) -> anyhow::Result<Self> {
114 Ok(CrpcEndhostApiClient {
115 client: CrpcClient::new_with_client(base_url, client)?,
116 })
117 }
118
119 /// Uses the provided token source for authentication.
120 pub fn use_token_source(&mut self, token_source: Arc<dyn TokenSource>) -> &mut Self {
121 self.client.use_token_source(token_source);
122 self
123 }
124}
125
126#[async_trait::async_trait]
127impl EndhostApiClient for CrpcEndhostApiClient {
128 async fn list_underlays(&self, isd_as: IsdAsn) -> Result<Underlays, CrpcClientError> {
129 self.client
130 .unary_request::<ListUnderlaysRequest, ListUnderlaysResponse>(
131 &format!("{ENDHOST_API_V1}.{UNDERLAY_SERVICE}{LIST_UNDERLAYS}"),
132 &ListUnderlaysRequest {
133 isd_as: Some(isd_as.into()),
134 },
135 )
136 .await?
137 .try_into()
138 .map_err(|e: url::ParseError| {
139 CrpcClientError::DecodeError {
140 context: "parsing underlay address as URL".into(),
141 source: Some(e.into()),
142 body: None,
143 }
144 })
145 .inspect(|resp| {
146 tracing::debug!(%resp, "Listed underlays");
147 })
148 }
149
150 async fn list_segments(
151 &self,
152 src: IsdAsn,
153 dst: IsdAsn,
154 page_size: i32,
155 page_token: String,
156 ) -> Result<SegmentsPage, CrpcClientError> {
157 self.client
158 .unary_request::<ListSegmentsRequest, ListSegmentsResponse>(
159 &format!("{ENDHOST_API_V1}.{SEGMENTS_SERVICE}{LIST_SEGMENTS}"),
160 &ListSegmentsRequest {
161 src_isd_as: src.0,
162 dst_isd_as: dst.0,
163 page_size,
164 page_token,
165 },
166 )
167 .await?
168 .try_into()
169 .map_err(|e: FromRpcError| {
170 CrpcClientError::DecodeError {
171 context: "failed decoding segments".into(),
172 source: Some(e.into()),
173 body: None,
174 }
175 })
176 .inspect(|resp: &SegmentsPage| {
177 tracing::debug!(
178 core=?resp.segments.core_segments.len(),
179 down=?resp.segments.down_segments.len(),
180 up=?resp.segments.up_segments.len(),
181 "Listed segments"
182 );
183 })
184 }
185}