Line data Source code
1 : pub mod cplane_proxy_v1;
2 : #[cfg(any(test, feature = "testing"))]
3 : pub mod mock;
4 :
5 : use std::hash::Hash;
6 : use std::sync::Arc;
7 : use std::time::Duration;
8 :
9 : use clashmap::ClashMap;
10 : use tokio::time::Instant;
11 : use tracing::{debug, info};
12 :
13 : use super::{EndpointAccessControl, RoleAccessControl};
14 : use crate::auth::backend::ComputeUserInfo;
15 : use crate::auth::backend::jwt::{AuthRule, FetchAuthRules, FetchAuthRulesError};
16 : use crate::cache::project_info::ProjectInfoCacheImpl;
17 : use crate::config::{CacheOptions, ProjectInfoCacheOptions};
18 : use crate::context::RequestContext;
19 : use crate::control_plane::{CachedNodeInfo, ControlPlaneApi, NodeInfoCache, errors};
20 : use crate::error::ReportableError;
21 : use crate::metrics::ApiLockMetrics;
22 : use crate::rate_limiter::{DynamicLimiter, Outcome, RateLimiterConfig, Token};
23 : use crate::types::EndpointId;
24 :
25 : #[non_exhaustive]
26 : #[derive(Clone)]
27 : pub enum ControlPlaneClient {
28 : /// Proxy V1 control plane API
29 : ProxyV1(cplane_proxy_v1::NeonControlPlaneClient),
30 : /// Local mock control plane.
31 : #[cfg(any(test, feature = "testing"))]
32 : PostgresMock(mock::MockControlPlane),
33 : /// Internal testing
34 : #[cfg(test)]
35 : #[allow(private_interfaces)]
36 : Test(Box<dyn TestControlPlaneClient>),
37 : }
38 :
39 : impl ControlPlaneApi for ControlPlaneClient {
40 0 : async fn get_role_access_control(
41 0 : &self,
42 0 : ctx: &RequestContext,
43 0 : endpoint: &EndpointId,
44 0 : role: &crate::types::RoleName,
45 0 : ) -> Result<RoleAccessControl, errors::GetAuthInfoError> {
46 0 : match self {
47 0 : Self::ProxyV1(api) => api.get_role_access_control(ctx, endpoint, role).await,
48 : #[cfg(any(test, feature = "testing"))]
49 0 : Self::PostgresMock(api) => api.get_role_access_control(ctx, endpoint, role).await,
50 : #[cfg(test)]
51 0 : Self::Test(_api) => {
52 0 : unreachable!("this function should never be called in the test backend")
53 : }
54 : }
55 0 : }
56 :
57 0 : async fn get_endpoint_access_control(
58 0 : &self,
59 0 : ctx: &RequestContext,
60 0 : endpoint: &EndpointId,
61 0 : role: &crate::types::RoleName,
62 0 : ) -> Result<EndpointAccessControl, errors::GetAuthInfoError> {
63 0 : match self {
64 0 : Self::ProxyV1(api) => api.get_endpoint_access_control(ctx, endpoint, role).await,
65 : #[cfg(any(test, feature = "testing"))]
66 0 : Self::PostgresMock(api) => api.get_endpoint_access_control(ctx, endpoint, role).await,
67 : #[cfg(test)]
68 0 : Self::Test(api) => api.get_access_control(),
69 : }
70 0 : }
71 :
72 0 : async fn get_endpoint_jwks(
73 0 : &self,
74 0 : ctx: &RequestContext,
75 0 : endpoint: &EndpointId,
76 0 : ) -> Result<Vec<AuthRule>, errors::GetEndpointJwksError> {
77 0 : match self {
78 0 : Self::ProxyV1(api) => api.get_endpoint_jwks(ctx, endpoint).await,
79 : #[cfg(any(test, feature = "testing"))]
80 0 : Self::PostgresMock(api) => api.get_endpoint_jwks(ctx, endpoint).await,
81 : #[cfg(test)]
82 0 : Self::Test(_api) => Ok(vec![]),
83 : }
84 0 : }
85 :
86 21 : async fn wake_compute(
87 21 : &self,
88 21 : ctx: &RequestContext,
89 21 : user_info: &ComputeUserInfo,
90 21 : ) -> Result<CachedNodeInfo, errors::WakeComputeError> {
91 21 : match self {
92 0 : Self::ProxyV1(api) => api.wake_compute(ctx, user_info).await,
93 : #[cfg(any(test, feature = "testing"))]
94 0 : Self::PostgresMock(api) => api.wake_compute(ctx, user_info).await,
95 : #[cfg(test)]
96 21 : Self::Test(api) => api.wake_compute(),
97 : }
98 21 : }
99 : }
100 :
101 : #[cfg(test)]
102 : pub(crate) trait TestControlPlaneClient: Send + Sync + 'static {
103 : fn wake_compute(&self) -> Result<CachedNodeInfo, errors::WakeComputeError>;
104 :
105 : fn get_access_control(&self) -> Result<EndpointAccessControl, errors::GetAuthInfoError>;
106 :
107 : fn dyn_clone(&self) -> Box<dyn TestControlPlaneClient>;
108 : }
109 :
110 : #[cfg(test)]
111 : impl Clone for Box<dyn TestControlPlaneClient> {
112 0 : fn clone(&self) -> Self {
113 0 : TestControlPlaneClient::dyn_clone(&**self)
114 0 : }
115 : }
116 :
117 : /// Various caches for [`control_plane`](super).
118 : pub struct ApiCaches {
119 : /// Cache for the `wake_compute` API method.
120 : pub(crate) node_info: NodeInfoCache,
121 : /// Cache which stores project_id -> endpoint_ids mapping.
122 : pub project_info: Arc<ProjectInfoCacheImpl>,
123 : }
124 :
125 : impl ApiCaches {
126 0 : pub fn new(
127 0 : wake_compute_cache_config: CacheOptions,
128 0 : project_info_cache_config: ProjectInfoCacheOptions,
129 0 : ) -> Self {
130 0 : Self {
131 0 : node_info: NodeInfoCache::new(
132 0 : "node_info_cache",
133 0 : wake_compute_cache_config.size,
134 0 : wake_compute_cache_config.ttl,
135 0 : true,
136 0 : ),
137 0 : project_info: Arc::new(ProjectInfoCacheImpl::new(project_info_cache_config)),
138 0 : }
139 0 : }
140 : }
141 :
142 : /// Various caches for [`control_plane`](super).
143 : pub struct ApiLocks<K> {
144 : name: &'static str,
145 : node_locks: ClashMap<K, Arc<DynamicLimiter>>,
146 : config: RateLimiterConfig,
147 : timeout: Duration,
148 : epoch: std::time::Duration,
149 : metrics: &'static ApiLockMetrics,
150 : }
151 :
152 : #[derive(Debug, thiserror::Error)]
153 : pub(crate) enum ApiLockError {
154 : #[error("timeout acquiring resource permit")]
155 : TimeoutError(#[from] tokio::time::error::Elapsed),
156 : }
157 :
158 : impl ReportableError for ApiLockError {
159 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
160 0 : match self {
161 0 : ApiLockError::TimeoutError(_) => crate::error::ErrorKind::RateLimit,
162 : }
163 0 : }
164 : }
165 :
166 : impl<K: Hash + Eq + Clone> ApiLocks<K> {
167 0 : pub fn new(
168 0 : name: &'static str,
169 0 : config: RateLimiterConfig,
170 0 : shards: usize,
171 0 : timeout: Duration,
172 0 : epoch: std::time::Duration,
173 0 : metrics: &'static ApiLockMetrics,
174 0 : ) -> Self {
175 0 : Self {
176 0 : name,
177 0 : node_locks: ClashMap::with_shard_amount(shards),
178 0 : config,
179 0 : timeout,
180 0 : epoch,
181 0 : metrics,
182 0 : }
183 0 : }
184 :
185 0 : pub(crate) async fn get_permit(&self, key: &K) -> Result<WakeComputePermit, ApiLockError> {
186 0 : if self.config.initial_limit == 0 {
187 0 : return Ok(WakeComputePermit {
188 0 : permit: Token::disabled(),
189 0 : });
190 0 : }
191 0 : let now = Instant::now();
192 0 : let semaphore = {
193 : // get fast path
194 0 : if let Some(semaphore) = self.node_locks.get(key) {
195 0 : semaphore.clone()
196 : } else {
197 0 : self.node_locks
198 0 : .entry(key.clone())
199 0 : .or_insert_with(|| {
200 0 : self.metrics.semaphores_registered.inc();
201 0 : DynamicLimiter::new(self.config)
202 0 : })
203 0 : .clone()
204 : }
205 : };
206 0 : let permit = semaphore.acquire_timeout(self.timeout).await;
207 :
208 0 : self.metrics
209 0 : .semaphore_acquire_seconds
210 0 : .observe(now.elapsed().as_secs_f64());
211 :
212 0 : if permit.is_ok() {
213 0 : debug!(elapsed = ?now.elapsed(), "acquired permit");
214 : } else {
215 0 : debug!(elapsed = ?now.elapsed(), "timed out acquiring permit");
216 : }
217 0 : Ok(WakeComputePermit { permit: permit? })
218 0 : }
219 :
220 0 : pub async fn garbage_collect_worker(&self) {
221 0 : if self.config.initial_limit == 0 {
222 0 : return;
223 0 : }
224 0 : let mut interval =
225 0 : tokio::time::interval(self.epoch / (self.node_locks.shards().len()) as u32);
226 : loop {
227 0 : for (i, shard) in self.node_locks.shards().iter().enumerate() {
228 0 : interval.tick().await;
229 : // temporary lock a single shard and then clear any semaphores that aren't currently checked out
230 : // race conditions: if strong_count == 1, there's no way that it can increase while the shard is locked
231 : // therefore releasing it is safe from race conditions
232 0 : info!(
233 : name = self.name,
234 : shard = i,
235 0 : "performing epoch reclamation on api lock"
236 : );
237 0 : let mut lock = shard.write();
238 0 : let timer = self.metrics.reclamation_lag_seconds.start_timer();
239 0 : let count = lock
240 0 : .extract_if(|(_, semaphore)| Arc::strong_count(semaphore) == 1)
241 0 : .count();
242 0 : drop(lock);
243 0 : self.metrics.semaphores_unregistered.inc_by(count as u64);
244 0 : timer.observe();
245 : }
246 : }
247 0 : }
248 : }
249 :
250 : pub(crate) struct WakeComputePermit {
251 : permit: Token,
252 : }
253 :
254 : impl WakeComputePermit {
255 0 : pub(crate) fn should_check_cache(&self) -> bool {
256 0 : !self.permit.is_disabled()
257 0 : }
258 0 : pub(crate) fn release(self, outcome: Outcome) {
259 0 : self.permit.release(outcome);
260 0 : }
261 0 : pub(crate) fn release_result<T, E>(self, res: Result<T, E>) -> Result<T, E> {
262 0 : match res {
263 0 : Ok(_) => self.release(Outcome::Success),
264 0 : Err(_) => self.release(Outcome::Overload),
265 : }
266 0 : res
267 0 : }
268 : }
269 :
270 : impl FetchAuthRules for ControlPlaneClient {
271 0 : async fn fetch_auth_rules(
272 0 : &self,
273 0 : ctx: &RequestContext,
274 0 : endpoint: EndpointId,
275 0 : ) -> Result<Vec<AuthRule>, FetchAuthRulesError> {
276 0 : self.get_endpoint_jwks(ctx, &endpoint)
277 0 : .await
278 0 : .map_err(FetchAuthRulesError::GetEndpointJwks)
279 0 : }
280 : }
|