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

Group Analytics #9

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
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
21 changes: 6 additions & 15 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
[package]
name = "posthog-rs"
license = "MIT"
version = "0.2.3"
authors = ["christos <[email protected]>"]
description = "An unofficial Rust client for Posthog (https://posthog.com/)."
repository = "https://github.com/openquery-io/posthog-rs"
edition = "2018"
[workspace]
members = [
"async",
"core",
"sync",
]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.11.3", default-features = false, features = ["blocking", "rustls-tls"] }
serde = { version = "1.0.125", features = ["derive"] }
chrono = {version = "0.4.19", features = ["serde"] }
serde_json = "1.0.64"
37 changes: 36 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@ Add `posthog-rs` to your `Cargo.toml`.

```toml
[dependencies]
posthog_rs = "0.2.0"
posthog-rs = "0.2.0" # for sync client
async-posthog = "0.2.0" # for async client
```

## Events

Capture events with `capture`.

```rust
let client = crate::client(env!("POSTHOG_API_KEY"));

Expand All @@ -21,6 +26,36 @@ event.insert_prop("key1", "value1").unwrap();
event.insert_prop("key2", vec!["a", "b"]).unwrap();

client.capture(event).unwrap();
```

## Groups

[Group analytics](https://posthog.com/docs/product-analytics/group-analytics) are supported.

### Identifying Groups

Groups can be created with [`group_identify`](https://posthog.com/docs/product-analytics/group-analytics#how-to-create-groups).

```rust
let client = crate::client(env!("POSTHOG_API_KEY"));

let mut event = GroupIdentify::new("organisation", "some_id");
event.insert_prop("status", "active").unwrap();

client.group_identify(event).unwrap();

```

### Associating Events with a Group

```rust
let client = crate::client(env!("POSTHOG_API_KEY"));

let mut event = Event::new("test", "1234");

// Optionally associate this event with a group (in this case,
// a "company" group type with key "company_id_123").
event.insert_group("company", "company_id_123");

client.capture(event).unwrap();
```
15 changes: 15 additions & 0 deletions async/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "async-posthog"
license = "MIT"
version = "0.2.3"
description = "An unofficial Rust client for Posthog (https://posthog.com/)."
repository = "https://github.com/openquery-io/posthog-rs"
edition = "2021"

[dependencies]
posthog-core = { path = "../core" }
reqwest = { version = "0.11.3", default-features = false, features = ["json", "rustls-tls"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0.125", features = ["derive"] }
serde_json = "1.0.64"
thiserror = "1.0.38"
75 changes: 75 additions & 0 deletions async/src/client.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
use posthog_core::event::{Event, InnerEvent, InnerEventBatch};
use posthog_core::group_identify::GroupIdentify;
use reqwest::{Client as HttpClient, Method};
use serde::{de::DeserializeOwned, Serialize};

use crate::client_options::ClientOptions;
use crate::error::Error;

pub struct Client {
options: ClientOptions,
http_client: HttpClient,
}

impl Client {
pub(crate) fn new(options: ClientOptions) -> Self {
let http_client = HttpClient::builder()
.timeout(options.timeout)
.build()
.unwrap(); // Unwrap here is as safe as `HttpClient::new`
Client {
options,
http_client,
}
}

async fn send_request<P: AsRef<str>, Body: Serialize, Res: DeserializeOwned>(
&self,
method: Method,
path: P,
body: &Body,
) -> Result<Res, Error> {
let res = self
.http_client
.request(
method,
format!("{}{}", self.options.api_endpoint, path.as_ref()),
)
.json(body)
.send()
.await
.map_err(|source| Error::SendRequest { source })?
.error_for_status()
.map_err(|source| Error::ResponseStatus { source })?
.json::<Res>()
.await
.map_err(|source| Error::DecodeResponse { source })?;
Ok(res)
}

pub async fn capture(&self, event: Event) -> Result<(), Error> {
let inner_event = InnerEvent::new(event, self.options.api_key.clone());
self.send_request::<_, _, serde_json::Value>(Method::POST, "/capture/", &inner_event)
.await?;
Ok(())
}

pub async fn capture_batch(&self, events: Vec<Event>) -> Result<(), Error> {
let inner_event_batch = InnerEventBatch::new(events, self.options.api_key.clone());
self.send_request::<_, _, serde_json::Value>(Method::POST, "/batch/", &inner_event_batch)
.await?;
Ok(())
}

pub async fn group_identify(&self, identify: GroupIdentify) -> Result<(), Error> {
let inner_event = InnerEvent::new(
identify
.try_into()
.map_err(|source| Error::PostHogCore { source })?,
self.options.api_key.clone(),
);
self.send_request::<_, _, serde_json::Value>(Method::POST, "/capture/", &inner_event)
.await?;
Ok(())
}
}
42 changes: 42 additions & 0 deletions async/src/client_options.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use std::time::Duration;

use crate::client::Client;

const API_ENDPOINT: &str = "https://app.posthog.com";
const TIMEOUT: Duration = Duration::from_millis(800); // This should be specified by the user

pub struct ClientOptions {
pub(crate) api_endpoint: String,
pub(crate) api_key: String,
pub(crate) timeout: Duration,
}

impl ClientOptions {
pub fn new(api_key: impl ToString) -> ClientOptions {
ClientOptions {
api_endpoint: API_ENDPOINT.to_string(),
api_key: api_key.to_string(),
timeout: TIMEOUT,
}
}

pub fn api_endpoint(&mut self, api_endpoint: impl ToString) -> &mut Self {
self.api_endpoint = api_endpoint.to_string();
self
}

pub fn timeout(&mut self, timeout: Duration) -> &mut Self {
self.timeout = timeout;
self
}

pub fn build(self) -> Client {
Client::new(self)
}
}

impl From<&str> for ClientOptions {
fn from(api_key: &str) -> Self {
ClientOptions::new(api_key)
}
}
11 changes: 11 additions & 0 deletions async/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{source}")]
PostHogCore { source: posthog_core::error::Error },
#[error("send request: {source}")]
SendRequest { source: reqwest::Error },
#[error("response status: {source}")]
ResponseStatus { source: reqwest::Error },
#[error("decode response: {source}")]
DecodeResponse { source: reqwest::Error },
}
14 changes: 14 additions & 0 deletions async/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
mod client;
mod client_options;
mod error;

pub use client::Client;
pub use client_options::ClientOptions;
pub use error::Error;

pub use posthog_core::event::{Event, Properties};
pub use posthog_core::group_identify::GroupIdentify;

pub fn client<C: Into<ClientOptions>>(options: C) -> Client {
options.into().build()
}
54 changes: 54 additions & 0 deletions async/tests/basic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use async_posthog::{Event, GroupIdentify};
use std::collections::HashMap;

fn build_client() -> async_posthog::Client {
async_posthog::client(env!("POSTHOG_API_KEY"))
}

#[tokio::test]
async fn capture() {
let client = build_client();

let mut child_map = HashMap::new();
child_map.insert("child_key1", "child_value1");

let mut event = Event::new("test async capture", "1234");
event.insert_prop("key1", "value1").unwrap();
event.insert_prop("key2", vec!["a", "b"]).unwrap();
event.insert_prop("key3", child_map).unwrap();

event.insert_group("company", "company_key");

client.capture(event).await.unwrap();
}

#[tokio::test]
async fn capture_batch() {
let client = build_client();

let events = (0..16)
.map(|_| {
let mut child_map = HashMap::new();
child_map.insert("child_key1", "child_value1");

let mut event = Event::new("test async capture batch", "1234");
event.insert_prop("key1", "value1").unwrap();
event.insert_prop("key2", vec!["a", "b"]).unwrap();
event.insert_prop("key3", child_map).unwrap();

event
})
.collect::<Vec<_>>();

client.capture_batch(events).await.unwrap();
}

#[tokio::test]
async fn group_identify() {
let client = build_client();

let mut event = GroupIdentify::new("organisation", "some_id");
event.insert_prop("status", "active").unwrap();

client.group_identify(event).await.unwrap();
}
13 changes: 13 additions & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "posthog-core"
license = "MIT"
version = "0.1.0"
description = "An unofficial Rust client for Posthog (https://posthog.com/)."
repository = "https://github.com/openquery-io/posthog-rs"
edition = "2021"

[dependencies]
chrono = {version = "0.4.19", features = ["serde"] }
serde = { version = "1.0.125", features = ["derive"] }
serde_json = "1.0.64"
thiserror = "1.0.38"
8 changes: 8 additions & 0 deletions core/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("serialization: {source}")]
Serialization {
#[from]
source: serde_json::Error,
},
}
Loading