:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture): accept recording sent_at in request body (#73077)
Manoel Aranda Netoe05be3aa266a
diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rsindex 41343ab3fba5..218064bd0da4 100644--- a/rust/capture/src/events/recordings.rs+++ b/rust/capture/src/events/recordings.rs@@ -16,8 +16,9 @@ use chrono::DateTime;use common_types::{CapturedEvent, HasEventName};use limiters::redis::RedisLimiter;use metrics::{counter, histogram};-use serde::{Deserialize, Serialize};+use serde::{Deserialize, Deserializer, Serialize};use serde_json::{json, Value};+use time::{format_description::well_known::Iso8601, OffsetDateTime};use tokio::time::Instant;use tracing::{error, instrument, Span};use uuid::Uuid;@@ -37,6 +38,16 @@ use crate::{},};+fn deserialize_sent_at<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>+where+ D: Deserializer<'de>,+{+ Ok(match Option::<Value>::deserialize(deserializer)? {+ Some(Value::String(value)) => Some(value),+ _ => None,+ })+}+/// A recording event optimized for minimal deserialization overhead./// Instead of fully parsing all properties into a HashMap, we only extract/// the fields we need and keep snapshot data as serde_json::Value for direct@@ -66,6 +77,14 @@ pub struct RawRecording {#[serde(skip_serializing_if = "Option::is_none")]pub timestamp: Option<String>,+ /// ISO 8601 request dispatch timestamp.+ #[serde(+ default,+ deserialize_with = "deserialize_sent_at",+ skip_serializing_if = "Option::is_none"+ )]+ pub sent_at: Option<String>,+/// Timezone offset#[serde(skip_serializing_if = "Option::is_none")]pub offset: Option<i64>,@@ -122,6 +141,12 @@ pub enum RecordingRequest {}impl RawRecording {+ pub fn sent_at(&self) -> Option<OffsetDateTime> {+ self.sent_at+ .as_deref()+ .and_then(|value| OffsetDateTime::parse(value, &Iso8601::DEFAULT).ok())+ }+/// Extract the distinct_id, checking both root field and propertiespub fn extract_distinct_id(&self) -> Option<String> {let value = match &self.distinct_id {@@ -491,6 +516,7 @@ mod tests {let json = json!({"event": "$snapshot","distinct_id": "user123",+ "sent_at": "2024-01-02T03:04:05.678Z","properties": {"$session_id": "session-abc","$window_id": "window-xyz",@@ -501,11 +527,23 @@ mod tests {let recording: RawRecording = serde_json::from_value(json).unwrap();assert_eq!(recording.event, "$snapshot");+ assert_eq!(+ recording.sent_at(),+ Some(OffsetDateTime::from_unix_timestamp_nanos(1_704_164_645_678_000_000).unwrap())+ );assert_eq!(recording.extract_distinct_id(), Some("user123".to_string()));assert_eq!(recording.properties.session_id,Some(Value::String("session-abc".to_string())));++ let recording: RawRecording = serde_json::from_value(json!({+ "event": "$snapshot",+ "sent_at": 1_704_164_645_678_i64,+ "properties": {}+ }))+ .unwrap();+ assert_eq!(recording.sent_at(), None);}#[test]diff --git a/rust/capture/src/payload/recordings.rs b/rust/capture/src/payload/recordings.rsindex 27f25fdd873f..a49206583288 100644--- a/rust/capture/src/payload/recordings.rs+++ b/rust/capture/src/payload/recordings.rs@@ -113,7 +113,7 @@ pub async fn handle_recording_payload(counter!("capture_events_received_total").increment(events.len() as u64);let now = state.timesource.current_time();- let sent_at = query_params.sent_at();+ let sent_at = events[0].sent_at().or_else(|| query_params.sent_at());let context = ProcessingContext {sent_at,diff --git a/rust/capture/tests/recordings.rs b/rust/capture/tests/recordings.rsindex d8f411fcf181..2062b0223993 100644--- a/rust/capture/tests/recordings.rs+++ b/rust/capture/tests/recordings.rs@@ -68,6 +68,51 @@ async fn it_captures_one_recording() -> Result<()> {Ok(())}+#[tokio::test]+async fn it_prefers_body_sent_at_and_falls_back_to_query_for_recordings() -> Result<()> {+ setup_tracing();+ let token = random_string("token", 16);+ let main_topic = EphemeralTopic::new().await;+ let server = ServerHandle::for_recordings(&main_topic).await;+ let query_sent_at = 1_704_067_200_000_i64;++ for (body_sent_at, expected_sent_at) in [+ (+ json!("2024-01-02T03:04:05.678Z"),+ "2024-01-02T03:04:05.678Z",+ ),+ (json!("invalid"), "2024-01-01T00:00:00Z"),+ (json!(1_704_164_645_678_i64), "2024-01-01T00:00:00Z"),+ ] {+ let session_id = Uuid::now_v7().to_string();+ let recording_events = json!([{+ "token": token,+ "event": "$snapshot",+ "distinct_id": random_string("id", 16),+ "sent_at": body_sent_at,+ "properties": {+ "$session_id": session_id,+ "$window_id": Uuid::now_v7().to_string(),+ "$snapshot_data": [],+ }+ }]);++ let response = reqwest::Client::new()+ .post(format!(+ "http://{:?}/s/?sent_at={query_sent_at}",+ server.addr+ ))+ .body(recording_events.to_string())+ .send()+ .await?;++ assert_eq!(StatusCode::OK, response.status());+ assert_eq!(expected_sent_at, main_topic.next_event()?["sent_at"]);+ }++ Ok(())+}+#[tokio::test]async fn it_captures_one_recording_with_user_agent_fallback_for_lib() -> Result<()> {setup_tracing();