Skip to content

Commit

Permalink
Simplify public API (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
buinauskas authored Oct 8, 2022
1 parent f695c27 commit 1ab31a9
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 160 deletions.
19 changes: 8 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
# Event Tracker

A Rust port of [vinted/event-tracker](https://github.com/vinted/event-tracker)
An abstraction for event tracking

## Installation

Add this line to your application's `Cargo.toml`:
Add event tracker as a dependency to your `Cargo.toml`:

```toml
vinted_event_tracker = { git = "https://github.com/vinted/event-tracker-rs" }
```

## Usage

Configure the crate in your application executable, e.g. `src/main.rs` or `src/bin/executable_name.rs`.
Configure relay once during the startup.

```rust
use serde::Serialize;
use vinted_event_tracker::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let udp_relay = Udp::new("0.0.0.0:5005").await?;

set_relay(udp_relay)?;
#[tokio::main]
async fn main() {
let udp_relay = UdpRelay::new("0.0.0.0:5005").await.unwrap();

Ok(())
set_relay(udp_relay).unwrap();
}
```

Expand All @@ -51,8 +50,6 @@ fn track_search_event() {
query: "shoes",
};

let event = Event::new(event, portal, debug_pin, search_event);

let _ = track(event);
track(event, portal, debug_pin, search_event);
}
```
16 changes: 4 additions & 12 deletions examples/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,11 @@ use vinted_event_tracker::*;
async fn main() {
tracing_subscriber::fmt::init();

let url = "https://0.0.0.0:9999".parse().expect("valid url");
let relay = HttpRelay::new("https://0.0.0.0:9999".parse().unwrap());

let http_relay = Http::new(url);
set_relay(relay).unwrap();

if let Err(ref error) = set_relay(http_relay) {
tracing::error!(%error, "Couldn't set HTTP relay");
}

track_events(5);
track_events(1_000);
}

fn track_events(iterations: i32) {
Expand All @@ -23,10 +19,6 @@ fn track_events(iterations: i32) {
}

for iteration in 1..iterations {
let event = Event::new("system.test", "fr", Some(1234), SearchEvent { iteration });

if let Err(ref error) = track(event) {
tracing::error!(%error, "Couldn't track an event");
}
vinted_event_tracker::track("event", "portal", Some(1234), SearchEvent { iteration });
}
}
12 changes: 3 additions & 9 deletions examples/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ use vinted_event_tracker::*;
async fn main() {
tracing_subscriber::fmt::init();

let udp_relay = Udp::new("0.0.0.0:5005").await.expect("valid udp relay");
let relay = UdpRelay::new("0.0.0.0:5005").await.unwrap();

if let Err(ref error) = set_relay(udp_relay) {
tracing::error!(%error, "Couldn't set UDP relay");
}
set_relay(relay).unwrap();

track_events(1_000)
}
Expand All @@ -21,10 +19,6 @@ fn track_events(iterations: i32) {
}

for iteration in 1..iterations {
let event = Event::new("event", "portal", Some(1234), SearchEvent { iteration });

if let Err(ref error) = track(event) {
tracing::error!(%error, "Couldn't track an event");
}
vinted_event_tracker::track("event", "portal", Some(1234), SearchEvent { iteration });
}
}
22 changes: 0 additions & 22 deletions src/error.rs

This file was deleted.

59 changes: 0 additions & 59 deletions src/event.rs

This file was deleted.

38 changes: 18 additions & 20 deletions src/http.rs → src/http_relay.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use crate::{EventBase, Relay};
use crate::{Metadata, Relay};
use reqwest::{header, Client, Url};

/// A [`Relay`] that will print events to HTTP listener
#[derive(Debug, Clone)]
pub struct Http {
pub struct HttpRelay {
client: Client,
url: Url,
}

impl Http {
/// Creates an instance of [`Http`] [`Relay`]
impl HttpRelay {
/// Creates an instance of [HttpRelay]
pub fn new(url: Url) -> Self {
Self {
client: Client::new(),
Expand All @@ -18,24 +18,22 @@ impl Http {
}
}

impl Relay for Http {
fn transport(&self, event_base: EventBase, bytes: Vec<u8>) {
let url = self.url.clone();
let client = self.client.clone();
impl Relay for HttpRelay {
fn transport(&self, metadata: Metadata, serialized_event: Vec<u8>) {
let mut request = self
.client
.post(self.url.clone())
.body(serialized_event)
.header(header::CONTENT_TYPE, "application/json")
.header("X-Local-Time", metadata.time.to_string())
.header("X-Platform", "web")
.header("X-Portal", metadata.portal);

if let Some(debug_pin) = metadata.debug_pin {
request = request.header("X-Debug-Pin", debug_pin);
}

let _ = tokio::spawn(async move {
let mut request = client
.post(url)
.body(bytes)
.header(header::CONTENT_TYPE, "application/json")
.header("X-Local-Time", event_base.time.to_string())
.header("X-Platform", "web")
.header("X-Portal", event_base.portal);

if let Some(debug_pin) = event_base.debug_pin {
request = request.header("X-Debug-Pin", debug_pin);
}

let response = match request.send().await {
Ok(response) => response,
Err(error) => {
Expand Down
98 changes: 80 additions & 18 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,14 @@
clippy::wildcard_imports
)]

mod error;
mod event;
mod http_relay;
mod udp_relay;

mod http;
mod udp;

pub use self::error::*;
pub use self::event::*;
pub use self::http::*;
pub use self::udp::*;
pub use self::http_relay::*;
pub use self::udp_relay::*;

use serde::Serialize;
use std::time::SystemTime;
use std::{
hint::spin_loop,
sync::atomic::{AtomicUsize, Ordering},
Expand Down Expand Up @@ -123,31 +120,96 @@ impl std::fmt::Display for SetRelayError {

impl std::error::Error for SetRelayError {}

/// Tracks the actual event
pub fn track<T>(event: Event<T>) -> Result<(), Error>
/// Tracks event
#[tracing::instrument(skip(debug_pin, tracking_data))]
pub fn track<T>(event: &'static str, portal: &'static str, debug_pin: Option<i32>, tracking_data: T)
where
T: std::fmt::Debug + serde::Serialize,
T: Serialize,
{
let event_vec = serde_json::to_vec(&event)?;
#[derive(Serialize)]
struct EventWithTrackingData<'a, T>
where
T: Serialize,
{
#[serde(flatten)]
metadata: &'a Metadata,

#[serde(flatten)]
tracking_data: T,
}

let metadata = Metadata {
event,
portal,
time: SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("SystemTime before UNIX_EPOCH")
.as_millis(),
debug_pin,
};

let event_with_tracking_data = {
EventWithTrackingData {
metadata: &metadata,
tracking_data,
}
};

match serde_json::to_vec(&event_with_tracking_data) {
Ok(bytes) => relay().transport(metadata, bytes),
Err(error) => {
tracing::error!(%error, "Could not serialize event")
}
}
}

relay().transport(event.base, event_vec);
/// Event metadata
#[derive(Debug, Serialize)]
pub struct Metadata {
event: &'static str,

Ok(())
portal: &'static str,

time: u128,

debug_pin: Option<i32>,
}

impl Metadata {
/// Event name
pub fn event(&self) -> &'static str {
self.event
}

/// Portal it's happening in
pub fn portal(&self) -> &'static str {
self.portal
}

/// Current time in milliseconds since unix epoch
pub fn time(&self) -> u128 {
self.time
}

/// Debug pin
pub fn debug_pin(&self) -> Option<i32> {
self.debug_pin
}
}

/// Trait for event transportation
/// An abstraction for event transmission over the wire
pub trait Relay {
/// Accepts event, serialized in JSON, in a form of bytes.
///
/// Use these bytes to send the event over the wire using protocols, such as:
/// - HTTP
/// - TCP
/// - UDP
fn transport(&self, event_base: EventBase, event: Vec<u8>);
fn transport(&self, metadata: Metadata, serialized_event: Vec<u8>);
}

struct NopRelay;

impl Relay for NopRelay {
fn transport(&self, _: EventBase, _: Vec<u8>) {}
fn transport(&self, _: Metadata, _: Vec<u8>) {}
}
Loading

0 comments on commit 1ab31a9

Please sign in to comment.