Skip to content
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
7 changes: 7 additions & 0 deletions crates/pulse-common/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,14 @@ pub struct EventPayload {
pub struct IdentifyPayload {
#[serde(default)]
pub user_id: Option<String>,
/// Person properties to set (overwrites existing values).
pub traits: serde_json::Value,
/// Person properties set only if not already present (`$set_once`).
#[serde(default)]
pub set_once: Option<serde_json::Value>,
/// Person properties to remove (`$unset`).
#[serde(default)]
pub unset: Option<Vec<String>>,
#[serde(default)]
pub account_id: Option<String>,
#[serde(default)]
Expand Down
30 changes: 30 additions & 0 deletions crates/pulse-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,11 @@ async fn main() -> anyhow::Result<()> {
// Scheduled alert evaluation (fires drop/outage alerts without traffic)
services::alerts::start_alert_evaluator_task(state.clone());

// Person merges: make sure ingest can follow redirects even after a Redis flush
if let Err(e) = services::persons::warm_redirects(&state).await {
tracing::warn!("Failed to warm person redirects: {e}");
}

// Recalculate stale dynamic person cohorts
services::person_cohorts::start_recalc_task(state.clone());
info!("Email report scheduler started");
Expand Down Expand Up @@ -234,6 +239,31 @@ async fn main() -> anyhow::Result<()> {
"/api/v1/saved-insights/{id}/versions/{version}/restore",
axum::routing::post(routes::saved_insights::restore),
)
// Persons
.route(
"/api/v2/persons/query",
axum::routing::post(routes::persons::query),
)
.route(
"/api/v2/persons/{visitor_id}",
get(routes::persons::get).delete(routes::persons::delete),
)
.route(
"/api/v2/persons/{visitor_id}/events",
get(routes::persons::events),
)
.route(
"/api/v2/persons/{visitor_id}/sessions",
get(routes::persons::sessions),
)
.route(
"/api/v2/persons/{visitor_id}/properties",
axum::routing::patch(routes::persons::update_properties),
)
.route(
"/api/v2/persons/{visitor_id}/merge",
axum::routing::post(routes::persons::merge),
)
// Person cohorts (v1 /api/v1/cohorts remains the acquisition cohort matrix)
.route(
"/api/v2/cohorts",
Expand Down
22 changes: 22 additions & 0 deletions crates/pulse-server/src/routes/ingest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,12 @@ async fn process_collect_envelope(
});
}

// Events from a merged-away visitor id belong to the person it was merged into.
let mut envelope = envelope;
envelope.visitor_id =
crate::services::persons::resolve_visitor(state, auth.project_id, &envelope.visitor_id)
.await;

let now = envelope
.timestamp
.map(|ts| chrono::DateTime::from_timestamp_millis(ts).unwrap_or_else(Utc::now))
Expand Down Expand Up @@ -304,6 +310,20 @@ async fn process_collect_envelope(
.await
.map_err(|e| AppError::Internal(e.to_string()))?;

// `$set` / `$set_once` / `$unset` in event properties update the person.
if let Some(update) = identity::PersonUpdate::from_event_data(payload.data.as_ref()) {
identity::apply_person_update(
&state.db,
auth.project_id,
&envelope.visitor_id,
None,
&update,
now,
false,
)
.await?;
}

let event = BufferedEvent {
project_id: auth.project_id,
session_id,
Expand Down Expand Up @@ -379,6 +399,8 @@ async fn process_collect_envelope(
&envelope.visitor_id,
payload.user_id.as_deref(),
&payload.traits,
payload.set_once.as_ref(),
payload.unset.as_deref().unwrap_or_default(),
payload.account_id.as_deref(),
payload.account_name.as_deref(),
payload.account_traits.as_ref(),
Expand Down
1 change: 1 addition & 0 deletions crates/pulse-server/src/routes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod features_ext;
pub mod health;
pub mod ingest;
pub mod insights;
pub mod persons;
pub mod query;
pub mod saved_insights;
pub mod script;
153 changes: 153 additions & 0 deletions crates/pulse-server/src/routes/persons.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
use axum::extract::{Path, Query};
use axum::response::IntoResponse;
use axum::{Extension, Json};
use serde::Deserialize;

use crate::error::AppResult;
use crate::middleware::auth::AuthenticatedProject;
use crate::services;
use crate::services::persons::{self, EventsQuery, PersonsQuery, PropertiesPatch};
use crate::state::SharedState;

/// People data is governed by the `identity` module.
const MODULE: &str = "identity";

async fn can_read(state: &SharedState, auth: &AuthenticatedProject) -> AppResult<()> {
auth.require_scope("query")?;
services::modules::require_module_read(state, auth.project_id, MODULE, &auth.allowed_modules)
.await
}

async fn can_write(state: &SharedState, auth: &AuthenticatedProject) -> AppResult<()> {
auth.require_scope("query")?;
services::modules::require_module_write(state, auth.project_id, MODULE, &auth.allowed_modules)
.await
}

// POST /api/v2/persons/query
pub async fn query(
Extension(state): Extension<SharedState>,
auth: AuthenticatedProject,
Json(q): Json<PersonsQuery>,
) -> AppResult<impl IntoResponse> {
can_read(&state, &auth).await?;
if q.uses_cohorts() {
services::modules::require_module_read(
&state,
auth.project_id,
"cohorts",
&auth.allowed_modules,
)
.await?;
}
Ok(Json(persons::list(&state.db, auth.project_id, &q).await?))
}

// GET /api/v2/persons/{visitor_id}
pub async fn get(
Extension(state): Extension<SharedState>,
auth: AuthenticatedProject,
Path(visitor_id): Path<String>,
) -> AppResult<impl IntoResponse> {
can_read(&state, &auth).await?;
// Cohort memberships are cohorts-module data: include them only if readable.
let include_cohorts = services::modules::require_module_read(
&state,
auth.project_id,
"cohorts",
&auth.allowed_modules,
)
.await
.is_ok();
Ok(Json(
persons::get(&state.db, auth.project_id, &visitor_id, include_cohorts).await?,
))
}

// GET /api/v2/persons/{visitor_id}/events
pub async fn events(
Extension(state): Extension<SharedState>,
auth: AuthenticatedProject,
Path(visitor_id): Path<String>,
Query(q): Query<EventsQuery>,
) -> AppResult<impl IntoResponse> {
can_read(&state, &auth).await?;
Ok(Json(
persons::events(&state.db, auth.project_id, &visitor_id, &q).await?,
))
}

#[derive(Debug, Deserialize)]
pub struct Page {
#[serde(default = "default_limit")]
pub limit: i64,
#[serde(default)]
pub offset: i64,
}

fn default_limit() -> i64 {
100
}

// GET /api/v2/persons/{visitor_id}/sessions
pub async fn sessions(
Extension(state): Extension<SharedState>,
auth: AuthenticatedProject,
Path(visitor_id): Path<String>,
Query(p): Query<Page>,
) -> AppResult<impl IntoResponse> {
can_read(&state, &auth).await?;
Ok(Json(
persons::sessions(&state.db, auth.project_id, &visitor_id, p.limit, p.offset).await?,
))
}

// PATCH /api/v2/persons/{visitor_id}/properties
pub async fn update_properties(
Extension(state): Extension<SharedState>,
auth: AuthenticatedProject,
Path(visitor_id): Path<String>,
Json(p): Json<PropertiesPatch>,
) -> AppResult<impl IntoResponse> {
can_write(&state, &auth).await?;
Ok(Json(
persons::update_properties(&state.db, auth.project_id, &visitor_id, &p).await?,
))
}

#[derive(Debug, Deserialize)]
pub struct MergeBody {
pub visitor_ids: Vec<String>,
}

// POST /api/v2/persons/{visitor_id}/merge
pub async fn merge(
Extension(state): Extension<SharedState>,
auth: AuthenticatedProject,
Path(visitor_id): Path<String>,
Json(b): Json<MergeBody>,
) -> AppResult<impl IntoResponse> {
can_write(&state, &auth).await?;
Ok(Json(
persons::merge(&state, auth.project_id, &visitor_id, &b.visitor_ids).await?,
))
}

#[derive(Debug, Deserialize, Default)]
pub struct DeleteParams {
#[serde(default)]
pub delete_events: bool,
}

// DELETE /api/v2/persons/{visitor_id}
pub async fn delete(
Extension(state): Extension<SharedState>,
auth: AuthenticatedProject,
Path(visitor_id): Path<String>,
Query(p): Query<DeleteParams>,
) -> AppResult<impl IntoResponse> {
can_write(&state, &auth).await?;
Ok(Json(
persons::delete(&state.db, auth.project_id, &visitor_id, p.delete_events).await?,
))
}
Loading
Loading