Skip to content
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

Initial AdView manager for serve-ing and testing generated code for ads #476

Merged
merged 4 commits into from
Mar 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
478 changes: 473 additions & 5 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ members = [
"primitives",
"adapter",
"adview-manager",
# Server for testing adview manager generated code
"adview-manager/serve",
"validator_worker",
"sentry",
"test_harness",
Expand Down
1 change: 1 addition & 0 deletions adapter/src/ethereum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ mod error;
pub mod ewt;

#[cfg(any(test, feature = "test-util"))]
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
pub mod test_util;

pub static OUTPACE_ABI: Lazy<&'static [u8]> =
Expand Down
2 changes: 1 addition & 1 deletion adview-manager/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ serde_json = "^1.0"
reqwest = { version = "0.11", features = ["json"] }
url = { version = "^2.1", features = ["serde"] }
# Logging
slog = { version = "^2.5.2", features = ["max_level_trace"] }
log = "0.4"
# Async
async-std = "^1.8"
# Other
Expand Down
23 changes: 23 additions & 0 deletions adview-manager/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# AdView Manager

Gives you the ability to generate the code for showing ads on a publisher website.

### Testing

There is a local server that you can run for testing purposes
This server gives you access to routes for showing ads and in terms to view,
the generated by this crate HTML/JavaScript code which is used on
a publisher websites.

Running the local server:

`RUST_LOG=debug cargo run -p serve`

This will start a server at `127.0.0.1:3030`

You can use `RUST_LOG` environment variable to set the logging level
for the server.

Routes:

- `GET /ad` - visualizes a single ad
34 changes: 34 additions & 0 deletions adview-manager/serve/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[package]
authors = ["Ambire <[email protected]>", "Lachezar Lechev <[email protected]>"]
edition = "2021"
name = "serve"
version = "0.1.0"
license = "AGPL-3.0"
publish = false

[features]

[dependencies]
# Domain
adex_primitives = { path = "../../primitives", package = "primitives", features = ["test-util"] }
adview-manager = { path = "../" }
chrono = "0.4"

# Async runtime
tokio = { version = "1", features = ["macros", "time", "rt-multi-thread"] }

# Web Server
warp = { version = "0.3" }

# Template engine
tera = { version = "1" }

# Mocking Market calls
wiremock = { version = "0.5" }

# (De)Serialization
serde = { version = "^1.0", features = ["derive"] }

# Logging
log = "0.4"
env_logger = { version = "0.9" }
152 changes: 152 additions & 0 deletions adview-manager/serve/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
use adex_primitives::{
supermarket::units_for_slot,
targeting::{input::Global, Input},
test_util::{DUMMY_CAMPAIGN, DUMMY_IPFS},
ToHex,
};
use adview_manager::{get_unit_html_with_events, Manager, Options, Size};
use chrono::Utc;
use log::{debug, info};
use warp::Filter;
use wiremock::{
matchers::{method, path, query_param},
Mock, MockServer, ResponseTemplate,
};


use tera::{Tera, Context};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();

let serve_dir = match std::env::current_dir().unwrap() {
serve_path if serve_path.ends_with("serve") => serve_path,
adview_manager_path if adview_manager_path.ends_with("adview-manager") => adview_manager_path.join("serve"),
// running from the Validator stack workspace
workspace_path => workspace_path.join("adview-manager/serve")
};

let templates_glob = format!("{}/templates/**/*.html", serve_dir.display());

info!("Tera templates glob path: {templates_glob}");
// Use globbing
let tera = Tera::new(&templates_glob)?;

// `GET /ad`
let get_ad = warp::get().and(warp::path("ad")).then(move || {
let tera = tera.clone();

async move {
// let logger = logger.clone();
// For mocking the `get_market_demand_resp` call
let mock_server = MockServer::start().await;

let market_url = mock_server.uri().parse().unwrap();
let whitelisted_tokens = vec!["0x6B175474E89094C44Da98b954EedeAC495271d0F"
.parse()
.expect("Valid token Address")];
let disabled_video = false;
let publisher_addr = "0x0000000000000000626f62627973686d75726461"
.parse()
.unwrap();

let options = Options {
market_url,
market_slot: DUMMY_IPFS[0],
publisher_addr,
// All passed tokens must be of the same price and decimals, so that the amounts can be accurately compared
whitelisted_tokens,
size: Some(Size::new(300, 100)),
// TODO: Check this value
navigator_language: Some("bg".into()),
/// Defaulted
disabled_video,
disabled_sticky: false,
};

let manager = Manager::new(options.clone(), Default::default())
.expect("Failed to create Adview Manager");
let pub_prefix = publisher_addr.to_hex();

let units_for_slot_resp = units_for_slot::response::Response {
targeting_input_base: Input {
ad_view: None,
global: Global {
ad_slot_id: options.market_slot.to_string(),
ad_slot_type: "".into(),
publisher_id: publisher_addr,
country: Some("Bulgaria".into()),
event_type: "IMPRESSION".into(),
seconds_since_epoch: Utc::now(),
user_agent_os: None,
user_agent_browser_family: None,
},
campaign: None,
balances: None,
ad_unit_id: None,
ad_slot: None,
},
accepted_referrers: vec![],
fallback_unit: None,
campaigns: vec![],
};

// Mock the `get_market_demand_resp` call
let mock_call = Mock::given(method("GET"))
// &depositAsset={}&depositAsset={}
.and(path(format!("units-for-slot/{}", options.market_slot)))
// pubPrefix=HEX&depositAsset=0xASSET1&depositAsset=0xASSET2
.and(query_param("pubPrefix", pub_prefix))
.and(query_param(
"depositAsset",
"0x6B175474E89094C44Da98b954EedeAC495271d0F",
))
// .and(query_param("depositAsset[]", "0x6B175474E89094C44Da98b954EedeAC495271d03"))
.respond_with(ResponseTemplate::new(200).set_body_json(units_for_slot_resp))
.expect(1)
.named("get_market_demand_resp");

// Mounting the mock on the mock server - it's now effective!
mock_call.mount(&mock_server).await;

let demand_resp = manager
.get_market_demand_resp()
.await
.expect("Should return Mocked response");

debug!("Mocked response: {demand_resp:?}");

let supermarket_ad_unit =
adex_primitives::supermarket::units_for_slot::response::AdUnit {
/// Same as `ipfs`
id: DUMMY_IPFS[1],
media_url: "ipfs://QmcUVX7fvoLMM93uN2bD3wGTH8MXSxeL8hojYfL2Lhp7mR".to_string(),
media_mime: "image/jpeg".to_string(),
target_url: "https://www.adex.network/?stremio-test-banner-1".to_string(),
};

let code = get_unit_html_with_events(
&options,
&supermarket_ad_unit,
"localhost",
DUMMY_CAMPAIGN.id,
&DUMMY_CAMPAIGN.validators,
false,
);

let html = {
let mut context = Context::new();
context.insert("ad_code", &code);

tera.render("ad.html", &context).expect("Should render")
};

warp::reply::html(html)
}
});

warp::serve(get_ad).run(([127, 0, 0, 1], 3030)).await;

Ok(())
}
15 changes: 15 additions & 0 deletions adview-manager/serve/templates/ad.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Serve an Ad</title>
</head>

<body>
{{ ad_code | safe }}
</body>

</html>
Loading