Skip to content

Commit 5dbeb1c

Browse files
rust: Add Svix::with_token to allow changing api token
Constructing a new `Svix` client performs TLS initialization, which can be expensive (openssl needs to read certs from disk). The new `with_token` method allows changing the api token while re-using the Hyper client, which avoids performing disk io.
1 parent fa1851a commit 5dbeb1c

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

rust/src/api.rs

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,36 @@ impl Default for SvixOptions {
4141
/// Svix API client.
4242
pub struct Svix {
4343
cfg: Configuration,
44+
server_url: Option<String>,
4445
}
4546

4647
impl Svix {
4748
pub fn new(token: String, options: Option<SvixOptions>) -> Self {
4849
let options = options.unwrap_or_default();
4950

50-
let base_path = options.server_url.unwrap_or_else(|| {
51+
let cfg = Configuration {
52+
user_agent: Some(format!("svix-libs/{CRATE_VERSION}/rust")),
53+
client: HyperClient::builder(TokioExecutor::new()).build(crate::default_connector()),
54+
timeout: options.timeout,
55+
// These fields will be set by `with_token` below
56+
base_path: String::new(),
57+
bearer_access_token: None,
58+
};
59+
let svix = Self {
60+
cfg,
61+
server_url: options.server_url,
62+
};
63+
svix.with_token(token)
64+
}
65+
66+
/// Creates a new `Svix` API client with a different token,
67+
/// re-using all of the settings and the Hyper client from
68+
/// an existing `Svix` instance.
69+
///
70+
/// This can be used to change the token without incurring
71+
/// the cost of TLS initialization.
72+
pub fn with_token(&self, token: String) -> Self {
73+
let base_path = self.server_url.clone().unwrap_or_else(|| {
5174
match token.split('.').last() {
5275
Some("us") => "https://api.us.svix.com",
5376
Some("eu") => "https://api.eu.svix.com",
@@ -58,13 +81,16 @@ impl Svix {
5881
});
5982
let cfg = Configuration {
6083
base_path,
61-
user_agent: Some(format!("svix-libs/{CRATE_VERSION}/rust")),
84+
user_agent: self.cfg.user_agent.clone(),
6285
bearer_access_token: Some(token),
63-
client: HyperClient::builder(TokioExecutor::new()).build(crate::default_connector()),
64-
timeout: options.timeout,
86+
client: self.cfg.client.clone(),
87+
timeout: self.cfg.timeout,
6588
};
6689

67-
Self { cfg }
90+
Self {
91+
cfg,
92+
server_url: self.server_url.clone(),
93+
}
6894
}
6995

7096
pub fn authentication(&self) -> Authentication<'_> {

0 commit comments

Comments
 (0)