Skip to content

Commit 3e9c4c2

Browse files
authored
Replace constants with settings
* Replace constants with settings * Refactored to use constants * Changes to use settings * Changed to use settings
1 parent 4a9652b commit 3e9c4c2

File tree

6 files changed

+124
-70
lines changed

6 files changed

+124
-70
lines changed

potsi.toml

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
[ad_server]
2+
ad_partner_url = "equativ_ad_api_2"
3+
sync_url = "https://adapi-srv-eu.smartadserver.com/ac?pgid=2040327&fmtid=137675&synthetic_id={{synthetic_id}}"
4+
5+
[prebid]
6+
server_url = "http://68.183.113.79:8000/openrtb2/auction"
7+
18
[synthetic]
29
counter_store = "jevans_synth_id_counter"
3-
opid_store = "jevans_synth_id_opid"
10+
opid_store = "jevans_synth_id_opid"
11+
secret_key = "potsi"

src/constants.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,2 @@
1-
pub const BACKEND2: &str = "equativ_ad_api_2";
2-
pub const SECRET_KEY: &[u8] = b"stackpop";
3-
pub const SYNTH_ID_COUNTER_STORE: &str = "jevans_synth_id_counter";
4-
pub const SYNTH_ID_OPID_STORE: &str = "jevans_synth_id_opid";
1+
pub const SYNTH_HEADER_FRESH: &str = "X-Synthetic-Fresh";
2+
pub const SYNTH_HEADER_POTSI: &str = "X-Synthetic-Potsi";

src/main.rs

Lines changed: 38 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::env;
77

88
mod constants;
99
mod cookies;
10-
use constants::*;
10+
use constants::{SYNTH_HEADER_FRESH, SYNTH_HEADER_POTSI};
1111
mod models;
1212
use models::AdResponse;
1313
mod prebid;
@@ -21,44 +21,46 @@ use templates::HTML_TEMPLATE;
2121

2222
#[fastly::main]
2323
fn main(req: Request) -> Result<Response, Error> {
24-
let _settings = Settings::new();
24+
let settings = Settings::new().unwrap();
25+
println!("Settings {settings:?}");
26+
2527
futures::executor::block_on(async {
2628
println!(
2729
"FASTLY_SERVICE_VERSION: {}",
2830
std::env::var("FASTLY_SERVICE_VERSION").unwrap_or_else(|_| String::new())
2931
);
3032

3133
match (req.get_method(), req.get_path()) {
32-
(&Method::GET, "/") => handle_main_page(req),
33-
(&Method::GET, "/ad-creative") => handle_ad_request(req),
34-
(&Method::GET, "/prebid-test") => handle_prebid_test(req).await,
34+
(&Method::GET, "/") => handle_main_page(&settings, req),
35+
(&Method::GET, "/ad-creative") => handle_ad_request(&settings, req),
36+
(&Method::GET, "/prebid-test") => handle_prebid_test(&settings, req).await,
3537
_ => Ok(Response::from_status(StatusCode::NOT_FOUND)
3638
.with_body("Not Found")
3739
.with_header(header::CONTENT_TYPE, "text/plain")),
3840
}
3941
})
4042
}
4143

42-
fn handle_main_page(req: Request) -> Result<Response, Error> {
44+
fn handle_main_page(settings: &Settings, req: Request) -> Result<Response, Error> {
4345
println!(
44-
"Testing constants - BACKEND2: {}, SYNTH_ID_COUNTER_STORE: {}",
45-
BACKEND2, SYNTH_ID_COUNTER_STORE
46+
"Using ad_partner_url: {}, counter_store: {}",
47+
settings.ad_server.ad_partner_url, settings.synthetic.counter_store,
4648
);
4749

4850
log_fastly::init_simple("mylogs", Info);
4951

5052
// Calculate fresh ID first using the synthetic module
51-
let fresh_id = synthetic::generate_synthetic_id(&req);
53+
let fresh_id = synthetic::generate_synthetic_id(settings, &req);
5254

5355
// Check for existing POTSI ID in this specific order:
5456
// 1. X-Synthetic-Potsi header
5557
// 2. Cookie
5658
// 3. Fall back to fresh ID
57-
let synthetic_id = synthetic::get_or_generate_synthetic_id(&req);
59+
let synthetic_id = synthetic::get_or_generate_synthetic_id(settings, &req);
5860

5961
println!(
6062
"Existing POTSI header: {:?}",
61-
req.get_header("X-Synthetic-Potsi")
63+
req.get_header(SYNTH_HEADER_POTSI)
6264
);
6365
println!("Generated Fresh ID: {}", fresh_id);
6466
println!("Using POTSI ID: {}", synthetic_id);
@@ -67,8 +69,8 @@ fn handle_main_page(req: Request) -> Result<Response, Error> {
6769
let mut response = Response::from_status(StatusCode::OK)
6870
.with_body(HTML_TEMPLATE)
6971
.with_header(header::CONTENT_TYPE, "text/html")
70-
.with_header("X-Synthetic-Fresh", &fresh_id) // Fresh ID always changes
71-
.with_header("X-Synthetic-Potsi", &synthetic_id); // POTSI ID remains stable
72+
.with_header(SYNTH_HEADER_FRESH, &fresh_id) // Fresh ID always changes
73+
.with_header(SYNTH_HEADER_POTSI, &synthetic_id); // POTSI ID remains stable
7274

7375
// Always set the cookie with the synthetic ID
7476
response.set_header(
@@ -94,7 +96,7 @@ fn handle_main_page(req: Request) -> Result<Response, Error> {
9496
Ok(response)
9597
}
9698

97-
fn handle_ad_request(req: Request) -> Result<Response, Error> {
99+
fn handle_ad_request(settings: &Settings, req: Request) -> Result<Response, Error> {
98100
// Log headers for debugging
99101
let client_ip = req
100102
.get_client_ip_addr()
@@ -108,11 +110,11 @@ fn handle_ad_request(req: Request) -> Result<Response, Error> {
108110
println!("X-Forwarded-For: {}", x_forwarded_for.unwrap_or("None"));
109111

110112
// Generate synthetic ID
111-
let synthetic_id = generate_synthetic_id(&req);
113+
let synthetic_id = generate_synthetic_id(settings, &req);
112114

113115
// Increment visit counter in KV store
114-
println!("Opening KV store: {}", SYNTH_ID_COUNTER_STORE);
115-
let store = match KVStore::open(SYNTH_ID_COUNTER_STORE) {
116+
println!("Opening KV store: {}", settings.synthetic.counter_store);
117+
let store = match KVStore::open(settings.synthetic.counter_store.as_str()) {
116118
Ok(Some(store)) => store,
117119
Ok(None) => {
118120
println!("KV store not found");
@@ -161,10 +163,7 @@ fn handle_ad_request(req: Request) -> Result<Response, Error> {
161163
println!("Synthetic ID {} visit count: {}", synthetic_id, new_count);
162164

163165
// Construct URL with synthetic ID
164-
let ad_server_url = format!(
165-
"https://adapi-srv-eu.smartadserver.com/ac?pgid=2040327&fmtid=137675&synthetic_id={}",
166-
synthetic_id
167-
);
166+
let ad_server_url = settings.ad_server.sync_url.replace("{{synthetic_id}}", &synthetic_id);
168167

169168
println!("Sending request to backend: {}", ad_server_url);
170169

@@ -175,7 +174,7 @@ fn handle_ad_request(req: Request) -> Result<Response, Error> {
175174
println!(" {}: {:?}", name, value);
176175
}
177176

178-
match req.send(BACKEND2) {
177+
match req.send(settings.ad_server.ad_partner_url.as_str()) {
179178
Ok(mut res) => {
180179
println!(
181180
"Received response from backend with status: {}",
@@ -236,8 +235,11 @@ fn handle_ad_request(req: Request) -> Result<Response, Error> {
236235
println!("Found opid: {}", opid);
237236

238237
// Store in opid KV store
239-
println!("Attempting to open KV store: {}", SYNTH_ID_OPID_STORE);
240-
match KVStore::open(SYNTH_ID_OPID_STORE) {
238+
println!(
239+
"Attempting to open KV store: {}",
240+
settings.synthetic.opid_store
241+
);
242+
match KVStore::open(settings.synthetic.opid_store.as_str()) {
241243
Ok(Some(store)) => {
242244
println!("Successfully opened KV store");
243245
match store.insert(&synthetic_id, opid.as_bytes()) {
@@ -251,12 +253,15 @@ fn handle_ad_request(req: Request) -> Result<Response, Error> {
251253
}
252254
}
253255
Ok(None) => {
254-
println!("KV store returned None: {}", SYNTH_ID_OPID_STORE);
256+
println!(
257+
"KV store returned None: {}",
258+
settings.synthetic.opid_store
259+
);
255260
}
256261
Err(e) => {
257262
println!(
258263
"Error opening KV store '{}': {:?}",
259-
SYNTH_ID_OPID_STORE, e
264+
settings.synthetic.opid_store, e
260265
);
261266
}
262267
};
@@ -293,29 +298,29 @@ fn handle_ad_request(req: Request) -> Result<Response, Error> {
293298
}
294299

295300
/// Handles the prebid test route with detailed error logging
296-
async fn handle_prebid_test(mut req: Request) -> Result<Response, Error> {
301+
async fn handle_prebid_test(settings: &Settings, mut req: Request) -> Result<Response, Error> {
297302
println!("Starting prebid test request handling");
298303

299304
// Calculate fresh ID
300-
let fresh_id = synthetic::generate_synthetic_id(&req);
305+
let fresh_id = synthetic::generate_synthetic_id(settings, &req);
301306

302307
// Check for existing POTSI ID in same order as handle_main_page
303-
let synthetic_id = synthetic::get_or_generate_synthetic_id(&req);
308+
let synthetic_id = synthetic::get_or_generate_synthetic_id(settings, &req);
304309

305310
println!(
306311
"Existing POTSI header: {:?}",
307-
req.get_header("X-Synthetic-Potsi")
312+
req.get_header(SYNTH_HEADER_POTSI)
308313
);
309314
println!("Generated Fresh ID: {}", fresh_id);
310315
println!("Using POTSI ID: {}", synthetic_id);
311316

312317
// Set both IDs as headers
313-
req.set_header("X-Synthetic-Fresh", &fresh_id);
314-
req.set_header("X-Synthetic-Potsi", &synthetic_id);
318+
req.set_header(SYNTH_HEADER_FRESH, &fresh_id);
319+
req.set_header(SYNTH_HEADER_POTSI, &synthetic_id);
315320

316321
println!("Using POTSI ID: {}, Fresh ID: {}", synthetic_id, fresh_id);
317322

318-
let prebid_req = match PrebidRequest::new(&req) {
323+
let prebid_req = match PrebidRequest::new(settings, &req) {
319324
Ok(req) => {
320325
println!(
321326
"Successfully created PrebidRequest with synthetic ID: {}",

src/prebid.rs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1-
use crate::synthetic::generate_synthetic_id;
2-
use fastly::http::Method;
1+
use fastly::http::{header, Method};
32
use fastly::{Error, Request, Response};
43
use serde_json::json;
54
use url;
65

6+
use crate::constants::{SYNTH_HEADER_FRESH, SYNTH_HEADER_POTSI};
7+
use crate::settings::Settings;
8+
use crate::synthetic::generate_synthetic_id;
9+
710
/// Represents a request to the Prebid Server with all necessary parameters
811
pub struct PrebidRequest {
912
/// Synthetic ID used for user identification across requests
@@ -26,13 +29,13 @@ impl PrebidRequest {
2629
///
2730
/// # Returns
2831
/// * `Result<Self, Error>` - New PrebidRequest or error
29-
pub fn new(req: &Request) -> Result<Self, Error> {
32+
pub fn new(settings: &Settings, req: &Request) -> Result<Self, Error> {
3033
// Get the POTSI ID from header (which we just set in handle_prebid_test)
3134
let synthetic_id = req
32-
.get_header("X-Synthetic-Potsi")
35+
.get_header(SYNTH_HEADER_POTSI)
3336
.and_then(|h| h.to_str().ok())
3437
.map(|s| s.to_string())
35-
.unwrap_or_else(|| generate_synthetic_id(req));
38+
.unwrap_or_else(|| generate_synthetic_id(settings, req));
3639

3740
// Get the original client IP from Fastly headers
3841
let client_ip = req
@@ -50,12 +53,12 @@ impl PrebidRequest {
5053

5154
// Try to get domain from Referer or Origin headers, fallback to default
5255
let domain = req
53-
.get_header("Referer")
56+
.get_header(header::REFERER)
5457
.and_then(|h| h.to_str().ok())
5558
.and_then(|r| url::Url::parse(r).ok())
5659
.and_then(|u| u.host_str().map(|h| h.to_string()))
5760
.or_else(|| {
58-
req.get_header("Origin")
61+
req.get_header(header::ORIGIN)
5962
.and_then(|h| h.to_str().ok())
6063
.and_then(|o| url::Url::parse(o).ok())
6164
.and_then(|u| u.host_str().map(|h| h.to_string()))
@@ -66,7 +69,7 @@ impl PrebidRequest {
6669

6770
// Create origin with owned String
6871
let origin = req
69-
.get_header("Origin")
72+
.get_header(header::ORIGIN)
7073
.and_then(|h| h.to_str().ok())
7174
.map(|s| s.to_string())
7275
.unwrap_or_else(|| format!("https://{}", domain));
@@ -92,7 +95,7 @@ impl PrebidRequest {
9295

9396
// Get and store the POTSI ID value from the incoming request
9497
let potsi_id = incoming_req
95-
.get_header("X-Synthetic-Potsi")
98+
.get_header(SYNTH_HEADER_POTSI)
9699
.and_then(|h| h.to_str().ok())
97100
.map(|s| s.to_string())
98101
.unwrap_or_else(|| self.synthetic_id.clone());
@@ -160,11 +163,11 @@ impl PrebidRequest {
160163
"at": 1
161164
});
162165

163-
req.set_header("Content-Type", "application/json");
166+
req.set_header(header::CONTENT_TYPE, "application/json");
164167
req.set_header("X-Forwarded-For", &self.client_ip);
165-
req.set_header("Origin", &self.origin);
166-
req.set_header("X-Synthetic-Fresh", &self.synthetic_id);
167-
req.set_header("X-Synthetic-Potsi", &potsi_id);
168+
req.set_header(header::ORIGIN, &self.origin);
169+
req.set_header(SYNTH_HEADER_FRESH, &self.synthetic_id);
170+
req.set_header(SYNTH_HEADER_POTSI, &potsi_id);
168171

169172
println!(
170173
"Sending prebid request with Fresh ID: {} and POTSI ID: {}",

src/settings.rs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,37 @@ use std::str;
44

55
#[derive(Debug, Deserialize)]
66
#[allow(unused)]
7-
struct Synthetic {
8-
counter_store: String,
9-
opid_store: String,
7+
pub struct AdServer {
8+
pub ad_partner_url: String,
9+
pub sync_url: String,
10+
}
11+
12+
#[derive(Debug, Deserialize)]
13+
#[allow(unused)]
14+
pub struct Prebid {
15+
pub server_url: String,
16+
}
17+
18+
#[derive(Debug, Deserialize)]
19+
#[allow(unused)]
20+
pub struct Synthetic {
21+
pub counter_store: String,
22+
pub opid_store: String,
23+
pub secret_key: String,
1024
}
1125

1226
#[derive(Debug, Deserialize)]
1327
#[allow(unused)]
1428
pub(crate) struct Settings {
15-
synthetic: Synthetic,
29+
pub ad_server: AdServer,
30+
pub prebid: Prebid,
31+
pub synthetic: Synthetic,
1632
}
1733

1834
impl Settings {
1935
pub(crate) fn new() -> Result<Self, ConfigError> {
20-
let tom_bytes = include_bytes!("../potsi.toml");
21-
let toml_str = str::from_utf8(tom_bytes).unwrap();
36+
let toml_bytes = include_bytes!("../potsi.toml");
37+
let toml_str = str::from_utf8(toml_bytes).unwrap();
2238

2339
let s = Config::builder()
2440
.add_source(File::from_str(toml_str, FileFormat::Toml))

0 commit comments

Comments
 (0)