-
Notifications
You must be signed in to change notification settings - Fork 281
feat: Adds secondary sqlite db to ads-client #7567
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
Open
thesuzerain
wants to merge
18
commits into
main
Choose a base branch
from
ads-client-adds-secondary-sqlite-db
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+865
−34
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
86ef587
feat: Initial commit
thesuzerain c17bbed
fix: rename rawad
thesuzerain 640873f
fix: storablead
thesuzerain 66ffa6f
fix: adds msising telemetry
thesuzerain d44acb5
fix: remove ttl
thesuzerain 276602a
fix: clippy
thesuzerain 9d4be84
fix: some cleanup
thesuzerain af1f25d
fix: size
thesuzerain 1254bc5
fix: extracted bytesize and clock
thesuzerain 998c211
fix: extracts bytesize and clock
thesuzerain 1aea442
fix: clippy
thesuzerain 388155e
fix: some review fixes
thesuzerain 26710f3
fix: More revisions
thesuzerain 6cb33a1
fix: ads changelog
thesuzerain 0c523fe
Merge branch 'main' of https://github.com/mozilla/application-service…
thesuzerain 5b7cc8a
feat: adds shutdown to adsstore
thesuzerain 8b1afdf
nit: alphabetical
thesuzerain 3613845
feat: Refactor
thesuzerain 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 hidden or 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 hidden or 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 hidden or 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,142 @@ | ||
| pub mod builder; | ||
| pub mod connection_initializer; | ||
| pub mod store; | ||
|
|
||
| use serde::{Deserialize, Serialize}; | ||
|
|
||
| use crate::{ | ||
| ads_store::{builder::AdsStoreBuilder, store::AdsStoreHolder}, | ||
| database::bytesize::ByteSize, | ||
| mars::ad_response::{AdImage, AdSpoc, AdTile}, | ||
| }; | ||
| use std::path::Path; | ||
|
|
||
| /// Identification of placement sent and returned from MARS (eg: `mock_spoc_1`) | ||
| #[derive(Debug, Hash, PartialEq, Eq, Clone)] | ||
| pub struct PlacementId(String); | ||
|
|
||
| impl PlacementId { | ||
| pub fn new(s: &str) -> PlacementId { | ||
| PlacementId(s.to_string()) | ||
| } | ||
| pub fn into_inner(self) -> String { | ||
| self.0 | ||
| } | ||
| } | ||
|
|
||
| impl AsRef<str> for PlacementId { | ||
| fn as_ref(&self) -> &str { | ||
| &self.0 | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] | ||
| pub enum StorableAd { | ||
| Image(AdImage), | ||
| Spoc(AdSpoc), | ||
| Tile(AdTile), | ||
| } | ||
|
|
||
| pub struct AdsStore { | ||
| holder: AdsStoreHolder, | ||
| #[allow(dead_code)] | ||
| max_size: ByteSize, | ||
| } | ||
|
|
||
| impl AdsStore { | ||
| pub fn builder<P: AsRef<Path>>(db_path: P) -> AdsStoreBuilder { | ||
| AdsStoreBuilder::new(db_path.as_ref()) | ||
| } | ||
|
|
||
| pub fn clear(&self) -> Result<(), rusqlite::Error> { | ||
| self.holder.clear_all()?; | ||
| Ok(()) | ||
| } | ||
|
|
||
| pub fn shutdown_db(self) -> Result<(), rusqlite::Error> { | ||
| self.holder.close() | ||
| } | ||
|
|
||
| pub fn invalidate_by_id(&self, placement_id: &PlacementId) -> Result<(), rusqlite::Error> { | ||
| self.holder.invalidate_ad_by_id(placement_id)?; | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use crate::mars::ad_response::{AdCallbacks, AdImage}; | ||
| use url::Url; | ||
|
|
||
| #[test] | ||
| fn test_ads_store_creation() { | ||
| // Test that AdsStore can be created successfully with test config | ||
| let store: Result<AdsStore, _> = AdsStore::builder("test_store.db").build(); | ||
| assert!(store.is_ok()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_clear_store() { | ||
| let store: AdsStore = AdsStore::builder("test_clear.db").build().unwrap(); | ||
|
|
||
| let base_url = mockito::server_url(); | ||
| let ad = StorableAd::Image(AdImage { | ||
| url: "https://ads.fakeexample.org/example_ad_1".to_string(), | ||
| image_url: "https://ads.fakeexample.org/example_image_1".to_string(), | ||
| format: "billboard".to_string(), | ||
| block_key: "abc123".into(), | ||
| alt_text: Some("An ad for a puppy".to_string()), | ||
| callbacks: AdCallbacks { | ||
| click: Url::parse(&format!("{}/click/example_ad_1", base_url)).unwrap(), | ||
| impression: Url::parse(&format!("{}/impression/example_ad_1", base_url)).unwrap(), | ||
| report: Some(Url::parse(&format!("{}/report/example_ad_1", base_url)).unwrap()), | ||
| }, | ||
| }); | ||
| let placement_id = PlacementId::new("mock_billboard_1"); | ||
| store.holder.store_ad(&placement_id, ad.clone()).unwrap(); | ||
|
|
||
| // Verify it's cached | ||
| let retrieved = store.holder.lookup(&placement_id).unwrap(); | ||
| assert!(retrieved.is_some()); | ||
|
|
||
| // Clear the cache | ||
| store.clear().unwrap(); | ||
|
|
||
| // Verify it's cleared | ||
| let retrieved_after_clear = store.holder.lookup(&placement_id).unwrap(); | ||
| assert!(retrieved_after_clear.is_none()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_invalidate_by_id() { | ||
| let store: AdsStore = AdsStore::builder("test_invalidate.db").build().unwrap(); | ||
|
|
||
| let base_url = mockito::server_url(); | ||
| let ad = StorableAd::Image(AdImage { | ||
| url: "https://ads.fakeexample.org/example_ad_1".to_string(), | ||
| image_url: "https://ads.fakeexample.org/example_image_1".to_string(), | ||
| format: "billboard".to_string(), | ||
| block_key: "abc123".into(), | ||
| alt_text: Some("An ad for a puppy".to_string()), | ||
| callbacks: AdCallbacks { | ||
| click: Url::parse(&format!("{}/click/example_ad_1", base_url)).unwrap(), | ||
| impression: Url::parse(&format!("{}/impression/example_ad_1", base_url)).unwrap(), | ||
| report: Some(Url::parse(&format!("{}/report/example_ad_1", base_url)).unwrap()), | ||
| }, | ||
| }); | ||
|
|
||
| let placement_1 = PlacementId::new("mock_billboard_1"); | ||
| let placement_2 = PlacementId::new("mock_billboard_2"); | ||
| store.holder.store_ad(&placement_1, ad.clone()).unwrap(); | ||
| store.holder.store_ad(&placement_2, ad.clone()).unwrap(); | ||
|
|
||
| assert!(store.holder.lookup(&placement_1).unwrap().is_some()); | ||
| assert!(store.holder.lookup(&placement_2).unwrap().is_some()); | ||
|
|
||
| store.invalidate_by_id(&placement_1).unwrap(); | ||
|
|
||
| assert!(store.holder.lookup(&placement_1).unwrap().is_none()); | ||
| assert!(store.holder.lookup(&placement_2).unwrap().is_some()); | ||
| } | ||
| } |
This file contains hidden or 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,158 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| use super::connection_initializer::AdsStoreConnectionInitializer; | ||
| use crate::ads_store::store::AdsStoreHolder; | ||
| use crate::ads_store::AdsStore; | ||
| use crate::database::bytesize::ByteSize; | ||
| use rusqlite::Connection; | ||
| use sql_support::open_database; | ||
| use std::path::PathBuf; | ||
|
|
||
| const DEFAULT_MAX_SIZE: ByteSize = ByteSize::mib(10); | ||
| const MIN_STORE_SIZE: ByteSize = ByteSize::kib(1); | ||
| const MAX_STORE_SIZE: ByteSize = ByteSize::mib(100); | ||
|
|
||
| #[derive(Debug, thiserror::Error)] | ||
| pub enum AdsStoreBuilderError { | ||
| #[error("Database error: {0}")] | ||
| Database(#[from] open_database::Error), | ||
| #[error("Database path cannot be empty")] | ||
| EmptyDbPath, | ||
| #[error( | ||
| "Maximum store size must be between {min_size} and {max_size}, got {size_bytes} bytes" | ||
| )] | ||
| InvalidMaxSize { | ||
| max_size: String, | ||
| min_size: String, | ||
| size_bytes: u64, | ||
| }, | ||
| } | ||
|
|
||
| pub struct AdsStoreBuilder { | ||
| db_path: PathBuf, | ||
| max_size: Option<ByteSize>, | ||
| } | ||
|
|
||
| impl AdsStoreBuilder { | ||
| pub fn new(db_path: impl Into<PathBuf>) -> Self { | ||
| Self { | ||
| db_path: db_path.into(), | ||
| max_size: None, | ||
| } | ||
| } | ||
|
|
||
| pub fn max_size(mut self, max_size: ByteSize) -> Self { | ||
| self.max_size = Some(max_size); | ||
| self | ||
| } | ||
|
|
||
| fn open_connection(&self) -> Result<Connection, AdsStoreBuilderError> { | ||
| let initializer = AdsStoreConnectionInitializer {}; | ||
| let conn = if cfg!(test) { | ||
| open_database::open_memory_database(&initializer)? | ||
| } else { | ||
| open_database::open_database(&self.db_path, &initializer)? | ||
| }; | ||
| Ok(conn) | ||
| } | ||
|
|
||
| fn validate(&self) -> Result<(), AdsStoreBuilderError> { | ||
| if self.db_path.to_string_lossy().trim().is_empty() { | ||
| return Err(AdsStoreBuilderError::EmptyDbPath); | ||
| } | ||
|
|
||
| if let Some(max_size) = self.max_size { | ||
| if max_size < MIN_STORE_SIZE || max_size > MAX_STORE_SIZE { | ||
| return Err(AdsStoreBuilderError::InvalidMaxSize { | ||
| size_bytes: max_size.as_u64(), | ||
| min_size: MIN_STORE_SIZE.to_string(), | ||
| max_size: MAX_STORE_SIZE.to_string(), | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| pub fn build(&self) -> Result<AdsStore, AdsStoreBuilderError> { | ||
| self.validate()?; | ||
|
|
||
| let conn = self.open_connection()?; | ||
| let holder = AdsStoreHolder::new(conn); | ||
| let max_size = self.max_size.unwrap_or(DEFAULT_MAX_SIZE); | ||
| Ok(AdsStore { max_size, holder }) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| fn make_test_builder(path: &str) -> AdsStoreBuilder { | ||
| AdsStoreBuilder::new(path) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_store_builder_with_defaults() { | ||
| let builder = make_test_builder("test.db"); | ||
| assert_eq!(builder.db_path, PathBuf::from("test.db")); | ||
| assert_eq!(builder.max_size, None); | ||
| assert!(builder.build().is_ok()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_cache_builder_valid_custom() { | ||
| let builder = make_test_builder("custom.db").max_size(ByteSize::b(1024)); | ||
|
|
||
| assert_eq!(builder.db_path, PathBuf::from("custom.db")); | ||
| assert_eq!(builder.max_size, Some(ByteSize::b(1024))); | ||
| assert!(builder.build().is_ok()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_validation_empty_db_path() { | ||
| let result = make_test_builder(" ").build(); | ||
| assert!(matches!(result, Err(AdsStoreBuilderError::EmptyDbPath))); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_validation_max_size_too_small() { | ||
| let result = make_test_builder("test.db") | ||
| .max_size(ByteSize::b(512)) | ||
| .build(); | ||
| assert!(matches!( | ||
| result, | ||
| Err(AdsStoreBuilderError::InvalidMaxSize { | ||
| size_bytes: 512, | ||
| min_size: _, | ||
| max_size: _, | ||
| }) | ||
| )); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_validation_max_size_too_large() { | ||
| let result = make_test_builder("test.db") | ||
| .max_size(ByteSize::b(2 * 1024 * 1024 * 1024)) | ||
| .build(); | ||
| assert!(matches!( | ||
| result, | ||
| Err(AdsStoreBuilderError::InvalidMaxSize { | ||
| size_bytes: 2147483648, | ||
| min_size: _, | ||
| max_size: _, | ||
| }) | ||
| )); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_validation_max_size_boundaries() { | ||
| let builder_min = make_test_builder("test.db").max_size(MIN_STORE_SIZE); | ||
| assert!(builder_min.build().is_ok()); | ||
|
|
||
| let builder_max = make_test_builder("test.db").max_size(MAX_STORE_SIZE); | ||
| assert!(builder_max.build().is_ok()); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
We keep
max_sizein the builder but it's not publically exposed ATM, as discussed. Options like this will be accessible by surfaces as needed.