Skip to content

Commit a786933

Browse files
committed
imp(lib): add authentication token support. close #16
1 parent bcd72c3 commit a786933

File tree

4 files changed

+110
-4
lines changed

4 files changed

+110
-4
lines changed

examples/auth.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
extern crate pyroscope;
2+
3+
use pyroscope::{PyroscopeAgent, Result};
4+
use pyroscope_pprofrs::{pprof_backend, PprofConfig};
5+
use std::hash::{Hash, Hasher};
6+
7+
fn hash_rounds(n: u64) -> u64 {
8+
let hash_str = "Some string to hash";
9+
let mut default_hasher = std::collections::hash_map::DefaultHasher::new();
10+
11+
for _ in 0..n {
12+
for _ in 0..1000 {
13+
default_hasher.write(hash_str.as_bytes());
14+
}
15+
hash_str.hash(&mut default_hasher);
16+
}
17+
18+
n
19+
}
20+
21+
fn main() -> Result<()> {
22+
// TODO: Change this token to your own.
23+
let token = String::from("<your-token>");
24+
25+
let agent = PyroscopeAgent::builder("http://localhost:4040", "example.basic")
26+
.backend(pprof_backend(PprofConfig::new().sample_rate(100)))
27+
.auth_token(token)
28+
.tags([("TagA", "ValueA"), ("TagB", "ValueB")].to_vec())
29+
.build()?;
30+
31+
// Show start time
32+
let start = std::time::SystemTime::now()
33+
.duration_since(std::time::UNIX_EPOCH)
34+
.unwrap()
35+
.as_secs();
36+
println!("Start Time: {}", start);
37+
38+
// Start Agent
39+
let agent_running = agent.start()?;
40+
41+
let _result = hash_rounds(300_000);
42+
43+
// Show stop time
44+
let stop = std::time::SystemTime::now()
45+
.duration_since(std::time::UNIX_EPOCH)
46+
.unwrap()
47+
.as_secs();
48+
println!("Stop Time: {}", stop);
49+
50+
// Stop Agent
51+
let agent_ready = agent_running.stop()?;
52+
53+
// Shutdown the Agent
54+
agent_ready.shutdown();
55+
56+
// Show program exit time
57+
let exit = std::time::SystemTime::now()
58+
.duration_since(std::time::UNIX_EPOCH)
59+
.unwrap()
60+
.as_secs();
61+
println!("Exit Time: {}", exit);
62+
63+
Ok(())
64+
}

src/pyroscope.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const LOG_TAG: &str = "Pyroscope::Agent";
2828
/// use pyroscope::pyroscope::PyroscopeConfig;
2929
/// let config = PyroscopeConfig::new("http://localhost:8080", "my-app");
3030
/// ```
31-
#[derive(Clone, Debug)]
31+
#[derive(Clone, Debug, Default)]
3232
pub struct PyroscopeConfig {
3333
/// Pyroscope Server Address
3434
pub url: String,
@@ -40,6 +40,8 @@ pub struct PyroscopeConfig {
4040
pub sample_rate: u32,
4141
/// Spy Name
4242
pub spy_name: String,
43+
/// Authentication Token
44+
pub auth_token: Option<String>,
4345
}
4446

4547
impl PyroscopeConfig {
@@ -57,6 +59,7 @@ impl PyroscopeConfig {
5759
tags: HashMap::new(), // Empty tags
5860
sample_rate: 100u32, // Default sample rate
5961
spy_name: String::from("undefined"), // Spy Name should be set by the backend
62+
auth_token: None, // No authentication token
6063
}
6164
}
6265

@@ -73,6 +76,14 @@ impl PyroscopeConfig {
7376
Self { spy_name, ..self }
7477
}
7578

79+
/// Set the Authentication Token.
80+
pub fn auth_token(self, auth_token: String) -> Self {
81+
Self {
82+
auth_token: Some(auth_token),
83+
..self
84+
}
85+
}
86+
7687
/// Set the tags.
7788
///
7889
/// # Example
@@ -143,6 +154,23 @@ impl PyroscopeAgentBuilder {
143154
Self { backend, ..self }
144155
}
145156

157+
/// Set JWT authentication token.
158+
/// This is optional. If not set, the agent will not send any authentication token.
159+
///
160+
/// #Example
161+
/// ```ignore
162+
/// let builder = PyroscopeAgentBuilder::new("http://localhost:8080", "my-app")
163+
/// .auth_token("my-token")
164+
/// .build()
165+
/// ?;
166+
/// ```
167+
pub fn auth_token(self, auth_token: impl AsRef<str>) -> Self {
168+
Self {
169+
config: self.config.auth_token(auth_token.as_ref().to_owned()),
170+
..self
171+
}
172+
}
173+
146174
/// Set tags. Default is empty.
147175
///
148176
/// # Example

src/session.rs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -168,10 +168,22 @@ impl Session {
168168
report.metadata.tags.clone().into_iter().collect(),
169169
)?;
170170

171-
// Create and send the request
172-
client
171+
// Create Reqwest builder
172+
let mut req_builder = client
173173
.post(format!("{}/ingest", url))
174-
.header("Content-Type", "binary/octet-stream")
174+
.header("Content-Type", "binary/octet-stream");
175+
176+
// Set authentication token
177+
//if self.config.auth_token.is_some() {
178+
//req_builder = req_builder.bearer_auth(self.config.auth_token.clone().unwrap());
179+
//}
180+
// rewrite with let some
181+
if let Some(auth_token) = self.config.auth_token.clone() {
182+
req_builder = req_builder.bearer_auth(auth_token);
183+
}
184+
185+
// Send the request
186+
req_builder
175187
.query(&[
176188
("name", application_name.as_str()),
177189
("from", &format!("{}", self.from)),

tests/session.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ fn test_session_new() {
2626
tags: HashMap::new(),
2727
sample_rate: 100u32,
2828
spy_name: "test-rs".to_string(),
29+
..Default::default()
2930
};
3031

3132
let report = vec![Report::new(HashMap::new())];
@@ -44,6 +45,7 @@ fn test_session_send_error() {
4445
tags: HashMap::new(),
4546
sample_rate: 100u32,
4647
spy_name: "test-rs".to_string(),
48+
..Default::default()
4749
};
4850

4951
let report = vec![Report::new(HashMap::new())];

0 commit comments

Comments
 (0)