-
Notifications
You must be signed in to change notification settings - Fork 7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Cache client state #198
Merged
Merged
Cache client state #198
Changes from 2 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
56f788b
Cache client state
sfackler 9739c5b
Add generated changelog entries
svc-changelog 680b66a
Explicitly partition cachable and uncachable config
sfackler e4871e4
avoid unnecessary clones
sfackler 168bfe1
parameterize the cache
sfackler f434c93
rename to weak cache and test
sfackler 705cc64
newline
sfackler fc267fb
check that entries are cleaned on drop
sfackler File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
type: feature | ||
feature: | ||
description: Client state is now cached and shared between clients. | ||
links: | ||
- https://github.com/palantir/conjure-rust-runtime/pull/198 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
// Copyright 2024 Palantir Technologies, Inc. | ||
// | ||
// 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::{ | ||
sync::{Arc, Weak}, | ||
time::Duration, | ||
}; | ||
|
||
use conjure_error::Error; | ||
use conjure_runtime_config::{ProxyConfig, SecurityConfig}; | ||
use linked_hash_map::LinkedHashMap; | ||
use parking_lot::Mutex; | ||
use url::Url; | ||
|
||
use crate::{ | ||
raw::DefaultRawClient, Builder, ClientQos, ClientState, Idempotency, NodeSelectionStrategy, | ||
ServerQos, ServiceError, UserAgent, | ||
}; | ||
|
||
const MAX_CACHED_CHANNELS: usize = 1_000; | ||
|
||
struct CachedState { | ||
state: Weak<ClientState<DefaultRawClient>>, | ||
id: usize, | ||
} | ||
|
||
struct Inner { | ||
cache: LinkedHashMap<Arc<CacheKey>, CachedState>, | ||
next_id: usize, | ||
} | ||
|
||
#[derive(Clone)] | ||
pub struct ClientCache { | ||
inner: Arc<Mutex<Inner>>, | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What is the purpose of having this inner field on the public struct? Does it hide your Inner cache implementation? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yep! |
||
|
||
impl ClientCache { | ||
pub fn new() -> Self { | ||
ClientCache { | ||
inner: Arc::new(Mutex::new(Inner { | ||
cache: LinkedHashMap::new(), | ||
next_id: 0, | ||
})), | ||
} | ||
} | ||
|
||
pub fn get(&self, builder: &Builder) -> Result<Arc<ClientState<DefaultRawClient>>, Error> { | ||
let key = Arc::new(CacheKey { | ||
service: builder.get_service().to_string(), | ||
user_agent: builder.get_user_agent().clone(), | ||
uris: builder.get_uris().to_vec(), | ||
security: builder.get_security().clone(), | ||
proxy: builder.get_proxy().clone(), | ||
connect_timeout: builder.get_connect_timeout(), | ||
read_timeout: builder.get_read_timeout(), | ||
write_timeout: builder.get_write_timeout(), | ||
backoff_slot_size: builder.get_backoff_slot_size(), | ||
max_num_retries: builder.get_max_num_retries(), | ||
client_qos: builder.get_client_qos(), | ||
server_qos: builder.get_server_qos(), | ||
service_error: builder.get_service_error(), | ||
idempotency: builder.get_idempotency(), | ||
node_selection_strategy: builder.get_node_selection_strategy(), | ||
rng_seed: builder.get_rng_seed(), | ||
}); | ||
|
||
let mut inner = self.inner.lock(); | ||
if let Some(state) = inner | ||
.cache | ||
.get_refresh(&key) | ||
.and_then(|w| w.state.upgrade()) | ||
{ | ||
return Ok(state.clone()); | ||
} | ||
|
||
let mut state = ClientState::new(builder)?; | ||
let id = inner.next_id; | ||
inner.next_id += 1; | ||
state.evictor = Some(CacheEvictor { | ||
inner: Arc::downgrade(&self.inner), | ||
key: key.clone(), | ||
id, | ||
}); | ||
let state = Arc::new(state); | ||
let cached_state = CachedState { | ||
state: Arc::downgrade(&state), | ||
id, | ||
}; | ||
inner.cache.insert(key, cached_state); | ||
|
||
while inner.cache.len() > MAX_CACHED_CHANNELS { | ||
inner.cache.pop_front(); | ||
} | ||
|
||
Ok(state) | ||
} | ||
} | ||
|
||
#[derive(Clone, PartialEq, Eq, Hash)] | ||
struct CacheKey { | ||
service: String, | ||
user_agent: UserAgent, | ||
uris: Vec<Url>, | ||
security: SecurityConfig, | ||
proxy: ProxyConfig, | ||
connect_timeout: Duration, | ||
read_timeout: Duration, | ||
write_timeout: Duration, | ||
backoff_slot_size: Duration, | ||
max_num_retries: u32, | ||
client_qos: ClientQos, | ||
server_qos: ServerQos, | ||
service_error: ServiceError, | ||
idempotency: Idempotency, | ||
node_selection_strategy: NodeSelectionStrategy, | ||
rng_seed: Option<u64>, | ||
} | ||
|
||
pub struct CacheEvictor { | ||
inner: Weak<Mutex<Inner>>, | ||
key: Arc<CacheKey>, | ||
id: usize, | ||
} | ||
|
||
impl Drop for CacheEvictor { | ||
fn drop(&mut self) { | ||
let Some(inner) = self.inner.upgrade() else { | ||
return; | ||
}; | ||
let mut inner = inner.lock(); | ||
|
||
if let Some(cached_state) = inner.cache.get(&self.key) { | ||
if cached_state.id == self.id { | ||
inner.cache.remove(&self.key); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's probably worth adding some tests for the ClientCache logic, especially since the evictor logic is a bit tricky
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah. I think the best route is probably to make the cache generic so I can use a different type than DefaultRawClient for testing?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, that sounds right. If you make the cache key generic it might also make it easier to move that closer to the builder logic, where the builder comes with a method to generate the cache key.