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::endpoints::EndpointsCache;
17 : use crate::cache::project_info::ProjectInfoCacheImpl;
18 : use crate::config::{CacheOptions, EndpointCacheConfig, ProjectInfoCacheOptions};
19 : use crate::context::RequestContext;
20 : use crate::control_plane::{CachedNodeInfo, ControlPlaneApi, NodeInfoCache, errors};
21 : use crate::error::ReportableError;
22 : use crate::metrics::ApiLockMetrics;
23 : use crate::rate_limiter::{DynamicLimiter, Outcome, RateLimiterConfig, Token};
24 : use crate::types::EndpointId;
25 :
26 : #[non_exhaustive]
27 : #[derive(Clone)]
28 : pub enum ControlPlaneClient {
29 : /// Proxy V1 control plane API
30 : ProxyV1(cplane_proxy_v1::NeonControlPlaneClient),
31 : /// Local mock control plane.
32 : #[cfg(any(test, feature = "testing"))]
33 : PostgresMock(mock::MockControlPlane),
34 : /// Internal testing
35 : #[cfg(test)]
36 : #[allow(private_interfaces)]
37 : Test(Box<dyn TestControlPlaneClient>),
38 : }
39 :
40 : impl ControlPlaneApi for ControlPlaneClient {
41 0 : async fn get_role_access_control(
42 0 : &self,
43 0 : ctx: &RequestContext,
44 0 : endpoint: &EndpointId,
45 0 : role: &crate::types::RoleName,
46 0 : ) -> Result<RoleAccessControl, errors::GetAuthInfoError> {
47 0 : match self {
48 0 : Self::ProxyV1(api) => api.get_role_access_control(ctx, endpoint, role).await,
49 : #[cfg(any(test, feature = "testing"))]
50 0 : Self::PostgresMock(api) => api.get_role_access_control(ctx, endpoint, role).await,
51 : #[cfg(test)]
52 0 : Self::Test(_api) => {
53 0 : unreachable!("this function should never be called in the test backend")
54 : }
55 : }
56 0 : }
57 :
58 0 : async fn get_endpoint_access_control(
59 0 : &self,
60 0 : ctx: &RequestContext,
61 0 : endpoint: &EndpointId,
62 0 : role: &crate::types::RoleName,
63 0 : ) -> Result<EndpointAccessControl, errors::GetAuthInfoError> {
64 0 : match self {
65 0 : Self::ProxyV1(api) => api.get_endpoint_access_control(ctx, endpoint, role).await,
66 : #[cfg(any(test, feature = "testing"))]
67 0 : Self::PostgresMock(api) => api.get_endpoint_access_control(ctx, endpoint, role).await,
68 : #[cfg(test)]
69 0 : Self::Test(api) => api.get_access_control(),
70 : }
71 0 : }
72 :
73 0 : async fn get_endpoint_jwks(
74 0 : &self,
75 0 : ctx: &RequestContext,
76 0 : endpoint: &EndpointId,
77 0 : ) -> Result<Vec<AuthRule>, errors::GetEndpointJwksError> {
78 0 : match self {
79 0 : Self::ProxyV1(api) => api.get_endpoint_jwks(ctx, endpoint).await,
80 : #[cfg(any(test, feature = "testing"))]
81 0 : Self::PostgresMock(api) => api.get_endpoint_jwks(ctx, endpoint).await,
82 : #[cfg(test)]
83 0 : Self::Test(_api) => Ok(vec![]),
84 : }
85 0 : }
86 :
87 19 : async fn wake_compute(
88 19 : &self,
89 19 : ctx: &RequestContext,
90 19 : user_info: &ComputeUserInfo,
91 19 : ) -> Result<CachedNodeInfo, errors::WakeComputeError> {
92 19 : match self {
93 0 : Self::ProxyV1(api) => api.wake_compute(ctx, user_info).await,
94 : #[cfg(any(test, feature = "testing"))]
95 0 : Self::PostgresMock(api) => api.wake_compute(ctx, user_info).await,
96 : #[cfg(test)]
97 19 : Self::Test(api) => api.wake_compute(),
98 : }
99 19 : }
100 : }
101 :
102 : #[cfg(test)]
103 : pub(crate) trait TestControlPlaneClient: Send + Sync + 'static {
104 : fn wake_compute(&self) -> Result<CachedNodeInfo, errors::WakeComputeError>;
105 :
106 : fn get_access_control(&self) -> Result<EndpointAccessControl, errors::GetAuthInfoError>;
107 :
108 : fn dyn_clone(&self) -> Box<dyn TestControlPlaneClient>;
109 : }
110 :
111 : #[cfg(test)]
112 : impl Clone for Box<dyn TestControlPlaneClient> {
113 0 : fn clone(&self) -> Self {
114 0 : TestControlPlaneClient::dyn_clone(&**self)
115 0 : }
116 : }
117 :
118 : /// Various caches for [`control_plane`](super).
119 : pub struct ApiCaches {
120 : /// Cache for the `wake_compute` API method.
121 : pub(crate) node_info: NodeInfoCache,
122 : /// Cache which stores project_id -> endpoint_ids mapping.
123 : pub project_info: Arc<ProjectInfoCacheImpl>,
124 : /// List of all valid endpoints.
125 : pub endpoints_cache: Arc<EndpointsCache>,
126 : }
127 :
128 : impl ApiCaches {
129 0 : pub fn new(
130 0 : wake_compute_cache_config: CacheOptions,
131 0 : project_info_cache_config: ProjectInfoCacheOptions,
132 0 : endpoint_cache_config: EndpointCacheConfig,
133 0 : ) -> Self {
134 0 : Self {
135 0 : node_info: NodeInfoCache::new(
136 0 : "node_info_cache",
137 0 : wake_compute_cache_config.size,
138 0 : wake_compute_cache_config.ttl,
139 0 : true,
140 0 : ),
141 0 : project_info: Arc::new(ProjectInfoCacheImpl::new(project_info_cache_config)),
142 0 : endpoints_cache: Arc::new(EndpointsCache::new(endpoint_cache_config)),
143 0 : }
144 0 : }
145 : }
146 :
147 : /// Various caches for [`control_plane`](super).
148 : pub struct ApiLocks<K> {
149 : name: &'static str,
150 : node_locks: ClashMap<K, Arc<DynamicLimiter>>,
151 : config: RateLimiterConfig,
152 : timeout: Duration,
153 : epoch: std::time::Duration,
154 : metrics: &'static ApiLockMetrics,
155 : }
156 :
157 : #[derive(Debug, thiserror::Error)]
158 : pub(crate) enum ApiLockError {
159 : #[error("timeout acquiring resource permit")]
160 : TimeoutError(#[from] tokio::time::error::Elapsed),
161 : }
162 :
163 : impl ReportableError for ApiLockError {
164 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
165 0 : match self {
166 0 : ApiLockError::TimeoutError(_) => crate::error::ErrorKind::RateLimit,
167 0 : }
168 0 : }
169 : }
170 :
171 : impl<K: Hash + Eq + Clone> ApiLocks<K> {
172 0 : pub fn new(
173 0 : name: &'static str,
174 0 : config: RateLimiterConfig,
175 0 : shards: usize,
176 0 : timeout: Duration,
177 0 : epoch: std::time::Duration,
178 0 : metrics: &'static ApiLockMetrics,
179 0 : ) -> Self {
180 0 : Self {
181 0 : name,
182 0 : node_locks: ClashMap::with_shard_amount(shards),
183 0 : config,
184 0 : timeout,
185 0 : epoch,
186 0 : metrics,
187 0 : }
188 0 : }
189 :
190 0 : pub(crate) async fn get_permit(&self, key: &K) -> Result<WakeComputePermit, ApiLockError> {
191 0 : if self.config.initial_limit == 0 {
192 0 : return Ok(WakeComputePermit {
193 0 : permit: Token::disabled(),
194 0 : });
195 0 : }
196 0 : let now = Instant::now();
197 0 : let semaphore = {
198 : // get fast path
199 0 : if let Some(semaphore) = self.node_locks.get(key) {
200 0 : semaphore.clone()
201 : } else {
202 0 : self.node_locks
203 0 : .entry(key.clone())
204 0 : .or_insert_with(|| {
205 0 : self.metrics.semaphores_registered.inc();
206 0 : DynamicLimiter::new(self.config)
207 0 : })
208 0 : .clone()
209 : }
210 : };
211 0 : let permit = semaphore.acquire_timeout(self.timeout).await;
212 :
213 0 : self.metrics
214 0 : .semaphore_acquire_seconds
215 0 : .observe(now.elapsed().as_secs_f64());
216 0 : debug!("acquired permit {:?}", now.elapsed().as_secs_f64());
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 0 : }
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 : }
|