aKode fase 2c: eliminato il codice di invio dati (crate analytics, otel-trace-websocket, sentry, esportatori OTLP); /feedback salva solo in locale; chiavi legacy [analytics]/[otel] accettate e ignorate; test di analytics/OTLP/upload rimossi
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled

This commit is contained in:
Andrea
2026-11-09 18:45:41 +01:00
parent 981745ccc8
commit 60532b6337
509 changed files with 2043 additions and 46606 deletions

View File

@@ -9,19 +9,12 @@ workspace = true
[dependencies]
anyhow = { workspace = true }
bytes = { workspace = true }
codex-http-client = { workspace = true }
codex-login = { workspace = true }
codex-protocol = { workspace = true }
codex-rollout = { workspace = true }
codex-state = { workspace = true }
flate2 = { workspace = true }
http = { workspace = true }
httpdate = { workspace = true }
mime_guess = { workspace = true }
sentry = { version = "0.46", default-features = false }
serde_json = { workspace = true }
tar = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["time"] }
tracing = { workspace = true }
@@ -32,7 +25,6 @@ zip = { workspace = true }
log = { workspace = true }
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }
wiremock = { workspace = true }
[lib]
doctest = false

View File

@@ -1,13 +1,13 @@
use super::*;
use crate::CodexFeedback;
use crate::FeedbackUploadOptions;
use crate::FeedbackSaveOptions;
use pretty_assertions::assert_eq;
use std::fs::File;
use std::io::Read;
use zip::ZipArchive;
fn options() -> FeedbackUploadOptions<'static> {
FeedbackUploadOptions {
fn options() -> FeedbackSaveOptions<'static> {
FeedbackSaveOptions {
classification: "bug",
reason: Some("synthetic feedback"),
tags: None,
@@ -126,7 +126,7 @@ fn save_preserves_report_and_log_consent() -> Result<()> {
CodexFeedback::new()
.snapshot(/*session_id*/ None)
.save_feedback(
FeedbackUploadOptions {
FeedbackSaveOptions {
include_logs,
..options()
},
@@ -162,7 +162,7 @@ fn save_rejects_oversized_events_without_publishing() -> Result<()> {
let error = CodexFeedback::new()
.snapshot(/*session_id*/ None)
.save_feedback(
FeedbackUploadOptions {
FeedbackSaveOptions {
reason: Some(&reason),
..options()
},

View File

@@ -1,14 +1,29 @@
//! Feedback event contracts for titles, report grouping, and lossless comment bodies.
//! Local feedback report contracts for titles, tags, and lossless comment bodies.
use crate::CodexFeedback;
use pretty_assertions::assert_eq;
use sentry::protocol::Event;
use sentry::protocol::Exception;
use sentry::protocol::Level;
use serde_json::json;
use std::collections::BTreeMap;
fn expected_report(
level: &str,
title: &str,
reason: Option<&str>,
tags: BTreeMap<String, String>,
) -> serde_json::Value {
let mut report = json!({
"level": level,
"message": title,
"tags": tags,
});
if let Some(reason) = reason {
report["exception"] = json!({ "values": [{ "type": title, "value": reason }] });
}
report
}
#[test]
fn custom_titles_preserve_comments_and_keep_submissions_separate() {
fn custom_titles_preserve_comments() {
let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None);
let tags = BTreeMap::from([
(
@@ -26,8 +41,8 @@ fn custom_titles_preserve_comments_and_keep_submissions_separate() {
(Some(""), Some("")),
(None, None),
] {
let event =
snapshot.feedback_event("other", reason, Some(&tags), /*session_source*/ None);
let report =
snapshot.feedback_report("other", reason, Some(&tags), /*session_source*/ None);
let mut expected_tags = tags.clone();
expected_tags.extend([
("thread_id".to_string(), snapshot.thread_id.clone()),
@@ -41,40 +56,20 @@ fn custom_titles_preserve_comments_and_keep_submissions_separate() {
expected_tags.insert("reason".to_string(), reason_tag.to_string());
}
assert_eq!(
event,
Event {
event_id: event.event_id,
timestamp: event.timestamp,
level: Level::Info,
message: Some(title.to_string()),
exception: reason
.map(|reason| Exception {
ty: title.to_string(),
value: Some(reason.to_string()),
..Default::default()
})
.into_iter()
.collect::<Vec<_>>()
.into(),
tags: expected_tags,
fingerprint: vec![event.event_id.to_string().into()].into(),
..Default::default()
}
report,
expected_report("info", title, reason, expected_tags)
);
let next_event =
snapshot.feedback_event("other", reason, Some(&tags), /*session_source*/ None);
assert_ne!(event.fingerprint, next_event.fingerprint);
}
}
#[test]
fn missing_or_blank_titles_preserve_session_titles_and_default_grouping() {
fn missing_or_blank_titles_preserve_session_titles() {
let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None);
let reason = " Feedback\nwith 🌍 context. ";
for custom_title in [None, Some(""), Some(" \t\n\u{2003} ")] {
let tags = custom_title
.map(|title| BTreeMap::from([("feedback_title".to_string(), title.to_string())]));
let event = snapshot.feedback_event(
let report = snapshot.feedback_report(
"bug",
Some(reason),
tags.as_ref(),
@@ -95,21 +90,8 @@ fn missing_or_blank_titles_preserve_session_titles_and_default_grouping() {
),
]);
assert_eq!(
event,
Event {
event_id: event.event_id,
timestamp: event.timestamp,
level: Level::Error,
message: Some(title.clone()),
exception: vec![Exception {
ty: title,
value: Some(reason.to_string()),
..Default::default()
}]
.into(),
tags: expected_tags,
..Default::default()
}
report,
expected_report("error", &title, Some(reason), expected_tags)
);
}
}
@@ -128,26 +110,19 @@ fn reason_tag_previews_preserve_full_comments_in_the_exception() {
("a".repeat(201), "a".repeat(200)),
(format!("{}extra", "界🌍".repeat(100)), "界🌍".repeat(100)),
] {
let event = snapshot.feedback_event(
let report = snapshot.feedback_report(
"bug",
Some(&reason),
/*tags*/ None,
/*session_source*/ None,
);
assert_eq!(
event,
Event {
event_id: event.event_id,
timestamp: event.timestamp,
level: Level::Error,
message: Some(title.clone()),
exception: vec![Exception {
ty: title.clone(),
value: Some(reason),
..Default::default()
}]
.into(),
tags: BTreeMap::from([
report,
expected_report(
"error",
&title,
Some(&reason),
BTreeMap::from([
("thread_id".to_string(), snapshot.thread_id.clone()),
("classification".to_string(), "bug".to_string()),
(
@@ -156,8 +131,7 @@ fn reason_tag_previews_preserve_full_comments_in_the_exception() {
),
("reason".to_string(), preview),
]),
..Default::default()
}
)
);
}
}

View File

@@ -9,15 +9,8 @@ use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::RouteAwareClientPool;
use codex_login::AuthEnvTelemetry;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionSource;
@@ -36,9 +29,6 @@ mod daemon_logs;
pub use daemon_logs::daemon_log_attachments;
pub(crate) mod feedback_diagnostics;
mod guardian;
mod report_upload;
mod rollout_archive;
mod upload;
pub use feedback_diagnostics::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME;
pub use feedback_diagnostics::FeedbackDiagnostic;
pub use feedback_diagnostics::FeedbackDiagnostics;
@@ -46,9 +36,6 @@ pub use guardian::GuardianReviewFailures;
pub use guardian::GuardianReviewRecord;
pub use guardian::guardian_review_failures;
pub use guardian::record_guardian_review_failure;
pub use report_upload::FeedbackDelivery;
pub use report_upload::FeedbackTransport;
pub use report_upload::prepare_report_attachment;
/// Filename used for the redacted `codex doctor --json` feedback attachment.
pub const DOCTOR_REPORT_ATTACHMENT_FILENAME: &str = "codex-doctor-report.json";
@@ -59,24 +46,15 @@ pub const CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME: &str = "codex-app-direc
/// Filename used for the Windows sandbox log feedback attachment.
pub const WINDOWS_SANDBOX_LOG_ATTACHMENT_FILENAME: &str = "windows-sandbox.log";
const DEFAULT_MAX_BYTES: usize = 4 * 1024 * 1024; // 4 MiB
// aKode: the upstream Sentry DSN has been removed. This placeholder only keeps
// DSN parsing valid; `upload::send_envelope` refuses to send anything.
const SENTRY_DSN: &str = "https://disabled@127.0.0.1/0";
const UPLOAD_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 300);
// Raw collection budgets used by the report API, not the interactive upload.
// Raw collection budgets for rollout history attachments.
pub const MAX_ATTACHMENT_BYTES: usize = 64 * 1024 * 1024;
pub const MAX_ATTACHMENTS_BYTES: usize = 126 * 1024 * 1024;
// Bound decoded envelopes, including framing. Do not shorten attachments to fit:
// they may already be compressed, and callers need an error for incomplete delivery.
// This bounds the decoded request including framing, not guaranteed attachment storage.
// https://develop.sentry.dev/sdk/foundations/envelopes/#size-limits
const MAX_DECODED_UPLOAD_BYTES: usize = 200 * 1024 * 1024;
const MAX_EVENT_BYTES: usize = 1024 * 1024;
const FEEDBACK_TAGS_TARGET: &str = "feedback_tags";
// Leave room for every feature, usage settings, and request/auth diagnostics.
const MAX_FEEDBACK_TAGS: usize = 512;
/// Structured request/auth fields that should be attached to feedback uploads.
/// Structured request/auth fields that should be attached to saved feedback reports.
pub struct FeedbackRequestTags<'a> {
pub endpoint: &'a str,
pub auth_header_attached: bool,
@@ -256,7 +234,7 @@ impl CodexFeedback {
.with_filter(
Targets::new()
.with_default(Level::TRACE)
// Opted-in content belongs to the configured OTLP destination, not feedback.
// Opted-in content is never part of feedback.
.with_target("codex_otel.log_only", LevelFilter::OFF)
.with_target("codex_http_client::transport", LevelFilter::DEBUG)
.with_target("codex_api::sse", LevelFilter::DEBUG)
@@ -272,7 +250,7 @@ impl CodexFeedback {
/// Returns a [`tracing_subscriber`] layer that collects structured metadata for feedback.
///
/// Events with `target: "feedback_tags"` are treated as key/value tags to attach to feedback
/// uploads later.
/// saved reports later.
pub fn metadata_layer<S>(&self) -> impl Layer<S> + Send + Sync + 'static
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
@@ -406,7 +384,7 @@ pub struct FeedbackSnapshot {
pub struct FeedbackAttachmentPath {
pub path: PathBuf,
/// Optional filename to use for the uploaded attachment instead of `path`'s basename.
/// Optional filename to use for the saved attachment instead of `path`'s basename.
pub attachment_filename_override: Option<String>,
}
@@ -511,32 +489,32 @@ impl FeedbackAttachmentPath {
}
}
/// In-memory attachment to include in a feedback upload.
/// In-memory attachment to include in a saved feedback report.
///
/// Use this for generated diagnostics that should not be materialized on disk,
/// such as the redacted doctor report. File-backed artifacts should use
/// `FeedbackAttachmentPath` so upload-time read failures can be logged and
/// `FeedbackAttachmentPath` so save-time read failures can be logged and
/// skipped independently.
pub struct FeedbackAttachment {
/// Attachment filename shown in Sentry and in the feedback consent UI.
/// Attachment filename shown in the saved archive and in the feedback consent UI.
pub filename: String,
/// Optional MIME type for consumers that render or classify attachments.
pub content_type: Option<String>,
/// Attachment bytes captured before the upload starts.
/// Attachment bytes captured before the report is saved.
pub buffer: Vec<u8>,
}
/// Inputs that control one feedback upload to Sentry.
/// Inputs that control one locally saved feedback report.
///
/// The caller is responsible for applying any user-consent gate before setting
/// `include_logs` or passing diagnostic attachments. This type only describes
/// what to upload once that decision has been made.
pub struct FeedbackUploadOptions<'a> {
/// what to save once that decision has been made.
pub struct FeedbackSaveOptions<'a> {
pub classification: &'a str,
pub reason: Option<&'a str>,
pub tags: Option<&'a BTreeMap<String, String>>,
pub include_logs: bool,
/// Owned diagnostics and frozen rollout prefixes that are safe to upload.
/// Owned diagnostics and frozen rollout prefixes that are safe to save.
///
/// Diagnostics follow `codex-logs.log`; rollout prefixes join the archive with
/// path-backed rollouts. Callers must apply any user consent gate first.
@@ -557,21 +535,17 @@ impl FeedbackSnapshot {
.snapshot_bytes();
}
fn feedback_event(
/// Builds the local JSON report saved next to the feedback attachments.
fn feedback_report(
&self,
classification: &str,
reason: Option<&str>,
tags: Option<&BTreeMap<String, String>>,
session_source: Option<&SessionSource>,
) -> sentry::protocol::Event<'static> {
use sentry::protocol::Event;
use sentry::protocol::Exception;
use sentry::protocol::Level;
use sentry::protocol::Values;
) -> serde_json::Value {
let level = match classification {
"bug" | "bad_result" | "safety_check" => Level::Error,
_ => Level::Info,
"bug" | "bad_result" | "safety_check" => "error",
_ => "info",
};
let custom_title = tags
.and_then(|tags| tags.get("feedback_title"))
@@ -587,24 +561,17 @@ impl FeedbackSnapshot {
},
str::to_owned,
);
let mut event = Event {
level,
message: Some(title.clone()),
tags: self.upload_tags(classification, reason, tags, session_source),
..Default::default()
};
if custom_title.is_some() {
// A shared title must not merge independent reports and suppress new-issue alerts.
event.fingerprint = vec![event.event_id.to_string().into()].into();
}
let mut report = serde_json::json!({
"level": level,
"message": title,
"tags": self.report_tags(classification, reason, tags, session_source),
});
if let Some(reason) = reason {
event.exception = Values::from(vec![Exception {
ty: title,
value: Some(reason.to_string()),
..Default::default()
}]);
report["exception"] = serde_json::json!({
"values": [{ "type": title, "value": reason }],
});
}
event
report
}
pub fn log_attachment(&self, logs_override: Option<Vec<u8>>) -> FeedbackAttachment {
@@ -632,28 +599,10 @@ impl FeedbackSnapshot {
self.feedback_diagnostics.attachment_text()
}
/// Submit feedback to Sentry with whole attachments within a shared deadline.
/// Success means HTTP acceptance, not durable attachment storage. Callers must
/// retain their source files; errors can occur after part of a report is accepted.
/// https://github.com/getsentry/relay/blob/master/relay-server/src/endpoints/common.rs
pub async fn upload_feedback(
&self,
options: FeedbackUploadOptions<'_>,
http_client_factory: &HttpClientFactory,
) -> Result<()> {
self.upload_feedback_with_dsn(
options,
http_client_factory,
SENTRY_DSN,
Instant::now() + UPLOAD_TIMEOUT,
)
.await
}
/// Atomically saves the consent-selected report and attachments without uploading.
/// Atomically saves the consent-selected report and attachments to a local file.
/// Existing paths are rejected and failures never publish a partial archive.
pub fn save_feedback(&self, options: FeedbackUploadOptions<'_>, path: &Path) -> Result<()> {
let report = serde_json::to_vec(&self.feedback_event(
pub fn save_feedback(&self, options: FeedbackSaveOptions<'_>, path: &Path) -> Result<()> {
let report = serde_json::to_vec(&self.feedback_report(
options.classification,
options.reason,
options.tags,
@@ -690,144 +639,7 @@ impl FeedbackSnapshot {
)
}
async fn upload_feedback_with_dsn(
&self,
options: FeedbackUploadOptions<'_>,
http_client_factory: &HttpClientFactory,
dsn: &str,
deadline: Instant,
) -> Result<()> {
use std::str::FromStr;
use sentry::protocol::Envelope;
use sentry::protocol::EnvelopeItem;
use sentry::types::Dsn;
let started_at = Instant::now();
let dsn = Dsn::from_str(dsn).map_err(|error| anyhow!("invalid DSN: {error}"))?;
let event = self.feedback_event(
options.classification,
options.reason,
options.tags,
options.session_source.as_ref(),
);
let mut envelope = Envelope::new();
envelope.add_item(EnvelopeItem::Event(event));
let (event_body, event_bytes) =
upload::encode_envelope(&envelope).context("failed to serialize feedback event")?;
anyhow::ensure!(
event_bytes <= MAX_EVENT_BYTES,
"feedback event exceeds the size limit"
);
let headers = envelope.headers().clone();
drop(envelope);
let client_pool = RouteAwareClientPool::new_without_redirects_or_request_logging(
http_client_factory.clone(),
ClientRouteClass::Other,
);
// Accept the report before reading diagnostics; all envelopes share one deadline.
let mut rate_limited = false;
let status = upload::send_envelope(
&client_pool,
&dsn,
event_body,
upload::EnvelopeKind::Event,
deadline,
&mut rate_limited,
)
.await?;
anyhow::ensure!(
status.is_success(),
"Sentry rejected feedback upload with HTTP status {status}"
);
let mut attachments = self.feedback_attachments(
&headers,
options.include_logs,
options.extra_attachments,
options.extra_attachment_paths,
options.logs_override,
);
let mut uploaded_attachments = 0;
let mut attachments_failed = false;
// Keep attachments linked to the accepted event, without replaying its contents.
// Inspect the upper bound without reading the next file after the deadline.
while attachments.size_hint().1 != Some(0) {
if rate_limited || Instant::now() >= deadline {
attachments_failed = true;
tracing::error!(
reason = if rate_limited {
"rate limit"
} else {
"upload deadline"
},
"remaining feedback attachments skipped"
);
break;
}
let Some(attachment) = attachments.next() else {
break;
};
if Instant::now() >= deadline {
attachments_failed = true;
tracing::error!(
"remaining feedback attachments skipped: upload deadline reached while reading attachment"
);
break;
}
let mut status = None;
let result: Result<()> = async {
let body = upload::encode_attachment_envelope(&headers, attachment?)?;
let response_status = upload::send_envelope(
&client_pool,
&dsn,
body,
upload::EnvelopeKind::Attachment,
deadline,
&mut rate_limited,
)
.await
.map_err(|error| {
// Transport error strings can contain credential-bearing URLs.
if let Some(cause) = error.downcast_ref::<codex_http_client::RouteAwareRequestError>() {
anyhow!(
"feedback transport failed: class={:?}, timeout={}, connect={}, request={}, body={}",
cause.failure_class(), cause.is_timeout(), cause.is_connect(), cause.is_request(), cause.is_body()
)
} else {
error
}
})?;
status = Some(response_status.as_u16());
anyhow::ensure!(response_status.is_success(), "Sentry rejected attachment");
Ok(())
}
.await;
if let Err(error) = result {
attachments_failed = true;
// Keep trying other diagnostics before reporting the partial failure.
tracing::error!(status, error = %format!("{error:#}"), "feedback attachment upload failed; continuing");
} else {
uploaded_attachments += 1;
}
}
tracing::info!(
thread_id = %self.thread_id,
uploaded_attachments,
attachments_failed,
elapsed_ms = started_at.elapsed().as_millis(),
"feedback event uploaded to Sentry"
);
anyhow::ensure!(
!attachments_failed,
"feedback report was accepted, but some attachments failed to upload"
);
Ok(())
}
fn upload_tags(
fn report_tags(
&self,
classification: &str,
reason: Option<&str>,
@@ -844,8 +656,8 @@ impl FeedbackSnapshot {
tags.insert(String::from("session_source"), source.to_string());
}
if let Some(reason) = reason {
// Sentry tags cannot contain newlines or exceed 200 characters. Keep the
// full comment in the exception body and a preview for tag consumers.
// Keep the full comment in the exception body and a single-line,
// 200-character preview for tag consumers.
let preview = reason
.chars()
.take(200)
@@ -882,105 +694,6 @@ impl FeedbackSnapshot {
tags
}
fn feedback_attachments<'a>(
&'a self,
headers: &'a sentry::protocol::EnvelopeHeaders,
include_logs: bool,
extra_attachments: Vec<FeedbackAttachment>,
extra_attachment_paths: &'a [FeedbackAttachmentPath],
logs_override: Option<Vec<u8>>,
) -> impl Iterator<Item = Result<sentry::protocol::Attachment>> + 'a {
use sentry::protocol::Attachment;
// Partition metadata without reading files before the event is accepted. Keep
// generated diagnostics first, then rollouts, then remaining files in caller order.
let (rollouts, diagnostics_attachments): (Vec<_>, Vec<_>) =
extra_attachments.into_iter().partition(|attachment| {
codex_rollout::rollout_id_from_path(Path::new(&attachment.filename)).is_some()
});
let (rollout_paths, diagnostic_paths): (Vec<_>, Vec<_>) =
extra_attachment_paths.iter().partition(|attachment| {
codex_rollout::rollout_id_from_path(&attachment.path).is_some()
});
let has_rollouts = !rollouts.is_empty() || !rollout_paths.is_empty();
let archive = has_rollouts
.then_some((rollout_paths, rollouts))
.into_iter()
.flat_map(move |(paths, rollouts)| {
let archive =
tempfile::tempdir()
.map_err(anyhow::Error::from)
.and_then(|directory| {
let output_path = directory.path().join("rollouts.tar.gz");
let Some(archive) = rollout_archive::archive_rollouts(
&output_path,
paths.iter().copied(),
&rollouts,
MAX_DECODED_UPLOAD_BYTES,
)?
else {
return Ok(None);
};
let attachment = archive
.read_attachment(MAX_DECODED_UPLOAD_BYTES)?
.context("rollout archive is missing or exceeds the size limit")?;
// Measure framing without copying the archive. Account for the extra
// decimal digits when the empty attachment's length becomes nonzero.
let mut envelope =
sentry::protocol::Envelope::new().with_headers(headers.clone());
envelope.add_item(Attachment {
filename: attachment.filename.clone(),
content_type: attachment.content_type.clone(),
..Default::default()
});
let mut framing = Vec::new();
envelope.to_writer(&mut framing)?;
let archive_bytes = attachment.buffer.len();
let envelope_bytes = framing.len()
+ archive_bytes
+ archive_bytes.checked_ilog10().unwrap_or(0) as usize;
anyhow::ensure!(
envelope_bytes <= MAX_DECODED_UPLOAD_BYTES,
"rollout archive envelope exceeds the size limit"
);
Ok(Some(attachment))
});
rollout_archive::with_individual_fallback(
archive,
paths,
rollouts,
MAX_DECODED_UPLOAD_BYTES,
)
});
let logs = include_logs.then(|| self.log_attachment(logs_override));
let diagnostics = self
.feedback_diagnostics_attachment_text(include_logs)
.map(|text| FeedbackAttachment {
buffer: text.into_bytes(),
filename: FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME.to_string(),
content_type: Some("text/plain".to_string()),
});
logs.into_iter()
.chain(diagnostics_attachments)
.chain(diagnostics)
.map(Ok)
.chain(archive)
.chain(diagnostic_paths.into_iter().map(|attachment_path| {
attachment_path
.read_attachment(MAX_DECODED_UPLOAD_BYTES)?
.context("feedback attachment is not a regular file or exceeds the size limit")
}))
.map(|attachment| {
attachment.map(|attachment| Attachment {
buffer: attachment.buffer,
filename: attachment.filename,
content_type: attachment.content_type,
ty: None,
})
})
}
}
fn display_classification(classification: &str) -> String {

View File

@@ -2,16 +2,12 @@
//! Unit tests for the crate and its related test suites.
use std::ffi::OsStr;
use std::fs;
use super::*;
use crate::FeedbackDiagnostic;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use wiremock::MockServer;
#[test]
fn ring_buffer_drops_front_when_full() {
@@ -94,132 +90,6 @@ fn metadata_layer_records_tags_from_feedback_target() {
pretty_assertions::assert_eq!(snap.tags.get("cached").map(String::as_str), Some("true"));
}
async fn upload_test_feedback(
feedback: &CodexFeedback,
dsn: &str,
extra_attachments: Vec<FeedbackAttachment>,
) -> Result<()> {
feedback
.snapshot(/*session_id*/ None)
.with_feedback_diagnostics(FeedbackDiagnostics::default())
.upload_feedback_with_dsn(
FeedbackUploadOptions {
classification: "bug",
reason: Some("private feedback"),
tags: None,
include_logs: true,
extra_attachments,
extra_attachment_paths: &[],
session_source: Some(SessionSource::Cli),
logs_override: Some(b"private log contents".to_vec()),
},
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
dsn,
Instant::now() + UPLOAD_TIMEOUT,
)
.await
}
// aKode: feedback is never uploaded; the upload path fails without sending any request.
#[tokio::test]
async fn feedback_upload_is_disabled_and_sends_nothing() {
let server = MockServer::start().await;
let dsn = format!("http://public@{}/42", server.address());
upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new())
.await
.expect_err("feedback upload must be disabled");
assert!(server.received_requests().await.unwrap().is_empty());
}
#[test]
fn feedback_attachments_gate_connectivity_diagnostics() {
let extra_filename = format!("codex-feedback-extra-{}.jsonl", ThreadId::new());
let extra_path = std::env::temp_dir().join(&extra_filename);
let extra_attachment_path = FeedbackAttachmentPath {
path: extra_path.clone(),
attachment_filename_override: None,
};
fs::write(&extra_path, "rollout").expect("extra attachment should be written");
let snapshot_with_diagnostics = CodexFeedback::new()
.snapshot(/*session_id*/ None)
.with_feedback_diagnostics(FeedbackDiagnostics::new(vec![FeedbackDiagnostic {
headline: "Proxy environment variables are set and may affect connectivity."
.to_string(),
details: vec!["HTTPS_PROXY = https://example.com:443".to_string()],
}]));
let attachments_with_diagnostics = snapshot_with_diagnostics
.feedback_attachments(
&sentry::protocol::EnvelopeHeaders::default(),
/*include_logs*/ true,
vec![FeedbackAttachment {
filename: DOCTOR_REPORT_ATTACHMENT_FILENAME.to_string(),
content_type: Some("application/json".to_string()),
buffer: b"{\"overallStatus\":\"ok\"}".to_vec(),
}],
&[extra_attachment_path],
Some(vec![1]),
)
.collect::<Result<Vec<_>>>()
.unwrap();
assert_eq!(
attachments_with_diagnostics
.iter()
.map(|attachment| attachment.filename.as_str())
.collect::<Vec<_>>(),
vec![
"codex-logs.log",
DOCTOR_REPORT_ATTACHMENT_FILENAME,
FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME,
extra_filename.as_str()
]
);
assert_eq!(attachments_with_diagnostics[0].buffer, vec![1]);
assert_eq!(
attachments_with_diagnostics[1].buffer,
b"{\"overallStatus\":\"ok\"}".to_vec()
);
assert_eq!(
attachments_with_diagnostics[2].buffer,
b"Connectivity diagnostics\n\n- Proxy environment variables are set and may affect connectivity.\n - HTTPS_PROXY = https://example.com:443".to_vec()
);
assert_eq!(attachments_with_diagnostics[3].buffer, b"rollout".to_vec());
assert_eq!(
attachments_with_diagnostics[3].content_type.as_deref(),
Some("text/plain")
);
assert_eq!(
OsStr::new(attachments_with_diagnostics[3].filename.as_str()),
OsStr::new(extra_filename.as_str())
);
let attachments_without_diagnostics = CodexFeedback::new()
.snapshot(/*session_id*/ None)
.with_feedback_diagnostics(FeedbackDiagnostics::default())
.feedback_attachments(
&sentry::protocol::EnvelopeHeaders::default(),
/*include_logs*/ true,
Vec::new(),
&[],
Some(vec![1]),
)
.collect::<Result<Vec<_>>>()
.unwrap();
assert_eq!(
attachments_without_diagnostics
.iter()
.map(|attachment| attachment.filename.as_str())
.collect::<Vec<_>>(),
vec!["codex-logs.log"]
);
assert_eq!(attachments_without_diagnostics[0].buffer, vec![1]);
fs::remove_file(extra_path).expect("extra attachment should be removed");
}
#[test]
fn path_backed_attachments_use_binary_content_types() {
let suffix = ThreadId::new();
@@ -232,26 +102,18 @@ fn path_backed_attachments_use_binary_content_types() {
fs::write(&gzip_path, gzip_bytes).expect("gzip attachment should be written");
fs::write(&unknown_path, unknown_bytes).expect("unknown attachment should be written");
let attachments = CodexFeedback::new()
.snapshot(/*session_id*/ None)
.feedback_attachments(
&sentry::protocol::EnvelopeHeaders::default(),
/*include_logs*/ false,
Vec::new(),
&[
FeedbackAttachmentPath {
path: gzip_path.clone(),
attachment_filename_override: None,
},
FeedbackAttachmentPath {
path: unknown_path.clone(),
attachment_filename_override: None,
},
],
/*logs_override*/ None,
)
.collect::<Result<Vec<_>>>()
.unwrap();
let attachments = [&gzip_path, &unknown_path]
.into_iter()
.map(|path| {
FeedbackAttachmentPath {
path: path.clone(),
attachment_filename_override: None,
}
.read_attachment(DEFAULT_MAX_BYTES)
.unwrap()
.expect("attachment should be readable")
})
.collect::<Vec<_>>();
fs::remove_file(gzip_path).expect("gzip attachment should be removed");
fs::remove_file(unknown_path).expect("unknown attachment should be removed");
@@ -280,7 +142,7 @@ fn path_backed_attachments_use_binary_content_types() {
}
#[test]
fn upload_tags_include_client_tags_and_preserve_reserved_fields() {
fn report_tags_include_client_tags_and_preserve_reserved_fields() {
let mut tags = BTreeMap::new();
tags.insert("thread_id".to_string(), "wrong-thread".to_string());
tags.insert("turn_id".to_string(), "wrong-turn".to_string());
@@ -320,7 +182,7 @@ fn upload_tags_include_client_tags_and_preserve_reserved_fields() {
client_tags.insert("model".to_string(), "mewthree".to_string());
client_tags.insert("effort".to_string(), "Some(Ultra)".to_string());
let upload_tags = snapshot.upload_tags(
let report_tags = snapshot.report_tags(
"bug",
Some("actual reason"),
Some(&client_tags),
@@ -328,39 +190,39 @@ fn upload_tags_include_client_tags_and_preserve_reserved_fields() {
);
assert_eq!(
upload_tags.get("thread_id").map(String::as_str),
report_tags.get("thread_id").map(String::as_str),
Some("thread-123")
);
assert_eq!(
upload_tags.get("turn_id").map(String::as_str),
report_tags.get("turn_id").map(String::as_str),
Some("turn-456")
);
assert_eq!(
upload_tags.get("classification").map(String::as_str),
report_tags.get("classification").map(String::as_str),
Some("bug")
);
assert_eq!(
upload_tags.get("session_source").map(String::as_str),
report_tags.get("session_source").map(String::as_str),
Some("cli")
);
assert_eq!(
upload_tags.get("reason").map(String::as_str),
report_tags.get("reason").map(String::as_str),
Some("actual reason")
);
assert_eq!(
upload_tags.get("account_id").map(String::as_str),
report_tags.get("account_id").map(String::as_str),
Some("actual-account")
);
assert_eq!(
upload_tags.get("model").map(String::as_str),
report_tags.get("model").map(String::as_str),
Some("mewthree")
);
assert_eq!(
upload_tags.get("effort").map(String::as_str),
report_tags.get("effort").map(String::as_str),
Some("Some(Ultra)")
);
assert_eq!(
upload_tags.get("client_tag").map(String::as_str),
report_tags.get("client_tag").map(String::as_str),
Some("from-client")
);
}

View File

@@ -1,10 +1,8 @@
//! Exercise dynamic tag collection, upload serialization, and bounded updates.
//! Exercise dynamic tag collection, report serialization, and bounded updates.
use crate::CodexFeedback;
use crate::*;
use pretty_assertions::assert_eq;
use sentry::protocol::Envelope;
use sentry::protocol::EnvelopeItem;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
@@ -35,7 +33,7 @@ fn refreshing_logs_preserves_captured_metadata() {
}
#[test]
fn dynamic_tags_survive_upload_alongside_static_fields() {
fn dynamic_tags_survive_in_report_alongside_static_fields() {
let feedback = CodexFeedback::new();
let _guard = tracing_subscriber::registry()
.with(feedback.metadata_layer())
@@ -57,7 +55,7 @@ fn dynamic_tags_survive_upload_alongside_static_fields() {
expected.insert("model".to_string(), "test-model".to_string());
let snapshot = feedback.snapshot(/*session_id*/ None);
assert_eq!(snapshot.tags, expected);
let event = snapshot.feedback_event(
let report = snapshot.feedback_report(
"bug", /*reason*/ None, /*tags*/ None, /*session_source*/ None,
);
expected.extend([
@@ -68,10 +66,8 @@ fn dynamic_tags_survive_upload_alongside_static_fields() {
env!("CARGO_PKG_VERSION").to_string(),
),
]);
assert_eq!(event.tags, expected);
let mut envelope = Envelope::new();
envelope.add_item(EnvelopeItem::Event(event));
let (_, size) = crate::upload::encode_envelope(&envelope).unwrap();
assert_eq!(report["tags"], serde_json::json!(expected));
let size = serde_json::to_vec(&report).unwrap().len();
assert!(size < crate::MAX_EVENT_BYTES);
}

View File

@@ -1,154 +0,0 @@
use std::collections::BTreeMap;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::RouteAwareClientPool;
use codex_protocol::protocol::SessionSource;
use http::StatusCode;
use sentry::protocol::Attachment;
use sentry::protocol::Envelope;
use sentry::protocol::EnvelopeHeaders;
use sentry::protocol::EnvelopeItem;
use sentry::types::Dsn;
use sentry::types::Uuid;
use crate::FeedbackAttachment;
use crate::FeedbackSnapshot;
use crate::MAX_DECODED_UPLOAD_BYTES;
use crate::MAX_EVENT_BYTES;
use crate::SENTRY_DSN;
use crate::upload;
// Background parts must tolerate slow links without inheriting the interactive
// upload's ten-second budget. The report API can cancel the request at any time.
const REPORT_PART_UPLOAD_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 300);
/// The upstream HTTP result, not proof of durable storage in Sentry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FeedbackDelivery {
Accepted {
retry_after: Option<Duration>,
},
Rejected {
status: u16,
retry_after: Option<Duration>,
},
/// No response was received. The upstream may still have accepted the envelope.
Unconfirmed,
}
/// Sends persisted report parts without retries or request diagnostics.
pub struct FeedbackTransport {
client_pool: RouteAwareClientPool,
dsn: Dsn,
}
impl FeedbackTransport {
pub fn new(http_client_factory: HttpClientFactory) -> Result<Self> {
Ok(Self {
client_pool: RouteAwareClientPool::new_without_redirects_or_request_logging(
http_client_factory,
ClientRouteClass::Other,
),
dsn: SENTRY_DSN
.parse()
.map_err(|_| anyhow!("invalid feedback DSN"))?,
})
}
/// Make one attempt. Callers own retry decisions and must retain the same bytes.
pub async fn send(&self, envelope: Vec<u8>) -> FeedbackDelivery {
let response = upload::envelope_request(
&self.client_pool,
&self.dsn,
envelope.into(),
REPORT_PART_UPLOAD_TIMEOUT,
)
.send()
.await;
let Ok(response) = response else {
return FeedbackDelivery::Unconfirmed;
};
let status = response.status();
let headers = response.headers();
let mut retry_after = headers
.get_all("Retry-After")
.iter()
.map(|value| {
upload::parse_retry_after(value.to_str().unwrap_or_default())
.unwrap_or(upload::DEFAULT_RATE_LIMIT)
})
.max();
// Report events and attachments share one conservative cooldown. Honor quotas on
// successful responses too; ignore quotas for unrelated Sentry categories.
// https://develop.sentry.dev/sdk/foundations/transport/rate-limiting/
retry_after = retry_after.max(upload::sentry_rate_limit_delay(headers));
if status == StatusCode::TOO_MANY_REQUESTS && retry_after.is_none() {
retry_after = Some(upload::DEFAULT_RATE_LIMIT);
}
if status.is_success() {
FeedbackDelivery::Accepted { retry_after }
} else {
FeedbackDelivery::Rejected {
status: status.as_u16(),
retry_after,
}
}
}
}
impl FeedbackSnapshot {
/// Prepare only the core report, using the caller's stable UUID as its Sentry event ID.
pub fn prepare_report_event(
&self,
report_id: &str,
classification: &str,
reason: Option<&str>,
tags: Option<&BTreeMap<String, String>>,
session_source: Option<&SessionSource>,
) -> Result<Vec<u8>> {
let mut event = self.feedback_event(classification, reason, tags, session_source);
// Auth tags must come from this report's caller, not metadata retained
// from an earlier account in the process-wide tracing layer.
event.tags.retain(|key, _| {
!matches!(key.as_str(), "account_id" | "chatgpt_user_id")
|| tags.is_some_and(|tags| tags.contains_key(key))
});
event.event_id =
Uuid::parse_str(report_id).map_err(|_| anyhow!("invalid feedback report ID"))?;
let mut envelope = Envelope::new();
envelope.add_item(EnvelopeItem::Event(event));
prepare_envelope(envelope, MAX_EVENT_BYTES)
}
}
/// Prepare one whole attachment linked to an existing report, without replaying its event.
/// The caller must apply consent and the report's cumulative attachment budget first.
pub fn prepare_report_attachment(
report_id: &str,
attachment: FeedbackAttachment,
) -> Result<Vec<u8>> {
let event_id = Uuid::parse_str(report_id).map_err(|_| anyhow!("invalid feedback report ID"))?;
let mut envelope = Envelope::new().with_headers(EnvelopeHeaders::new().with_event_id(event_id));
envelope.add_item(EnvelopeItem::Attachment(Attachment {
buffer: attachment.buffer,
filename: attachment.filename,
content_type: attachment.content_type,
ty: None,
}));
prepare_envelope(envelope, MAX_DECODED_UPLOAD_BYTES)
}
fn prepare_envelope(envelope: Envelope, max_decoded_bytes: usize) -> Result<Vec<u8>> {
let (bytes, decoded_bytes) =
upload::encode_envelope(&envelope).context("failed to serialize feedback envelope")?;
anyhow::ensure!(
decoded_bytes <= max_decoded_bytes,
"feedback envelope exceeds the size limit"
);
Ok(bytes)
}

View File

@@ -1,148 +0,0 @@
//! Writes selected rollouts to a bounded gzip tar at a caller-provided local path.
//! Invalid inputs are logged and skipped; only a complete archive is published.
//! Archive failures fall back to lazy individual attachments using the original sources.
use std::collections::HashSet;
use std::fs;
use std::io;
use std::io::BufWriter;
use std::io::Write;
use std::path::Path;
use anyhow::Context;
use anyhow::Result;
use flate2::Compression;
use flate2::write::GzEncoder;
use crate::FeedbackAttachment;
use crate::FeedbackAttachmentPath;
pub(super) fn archive_rollouts<'a>(
output_path: &Path,
rollout_paths: impl IntoIterator<Item = &'a FeedbackAttachmentPath>,
rollouts: impl IntoIterator<Item = &'a FeedbackAttachment>,
max_bytes: usize,
) -> Result<Option<FeedbackAttachmentPath>> {
let parent = output_path
.parent()
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
fs::create_dir_all(parent).context("failed to create rollout archive directory")?;
let file = tempfile::NamedTempFile::new_in(parent)?;
let writer = BoundedWriter {
inner: BufWriter::new(file),
written: 0,
max_bytes,
};
let mut archive = tar::Builder::new(GzEncoder::new(writer, Compression::default()));
let mut filenames = HashSet::new();
for path in rollout_paths {
match path.read_attachment(max_bytes) {
Ok(Some(rollout)) => append_rollout(&mut archive, &mut filenames, &rollout, max_bytes)?,
Ok(None) => {} // The attachment reader already logs oversized or nonregular files.
Err(error) => tracing::error!(%error, "failed to read rollout; skipping attachment"),
}
}
for rollout in rollouts {
append_rollout(&mut archive, &mut filenames, rollout, max_bytes)?;
}
if filenames.is_empty() {
return Ok(None);
}
let writer = archive
.into_inner()?
.finish()
.context("failed to finish rollout archive")?;
let file = writer.inner.into_inner()?;
// Keep failed writes and incomplete gzip streams out of the destination path.
file.persist_noclobber(output_path)?;
Ok(Some(FeedbackAttachmentPath {
path: output_path.to_path_buf(),
attachment_filename_override: None,
}))
}
pub(super) fn with_individual_fallback<'a>(
archive: Result<Option<FeedbackAttachment>>,
rollout_paths: Vec<&'a FeedbackAttachmentPath>,
rollouts: Vec<FeedbackAttachment>,
max_bytes: usize,
) -> impl Iterator<Item = Result<FeedbackAttachment>> + 'a {
let (archive, fallback) = match archive {
Ok(archive) => (archive, false),
Err(error) => {
tracing::error!(%error, "rollout archiving failed; uploading individual attachments");
(None, true)
}
};
archive
.into_iter()
.map(Ok)
.chain(fallback.then_some(rollouts).into_iter().flatten().map(Ok))
.chain(
fallback
.then_some(rollout_paths)
.into_iter()
.flatten()
.map(move |path| {
path.read_attachment(max_bytes)?.context(
"feedback attachment is not a regular file or exceeds the size limit",
)
}),
)
}
fn append_rollout<W: Write>(
archive: &mut tar::Builder<W>,
filenames: &mut HashSet<String>,
rollout: &FeedbackAttachment,
max_bytes: usize,
) -> Result<()> {
if rollout.buffer.len() > max_bytes {
tracing::error!(
bytes = rollout.buffer.len(),
max_bytes,
"rollout skipped: size limit exceeded"
);
return Ok(());
}
if rollout.filename.is_empty()
|| matches!(rollout.filename.as_str(), "." | "..")
|| rollout.filename.contains(['/', '\\', ':'])
|| filenames.contains(&rollout.filename)
{
tracing::error!("rollout skipped: invalid or duplicate archive filename");
return Ok(());
}
let mut header = tar::Header::new_gnu();
header.set_size(rollout.buffer.len() as u64);
header.set_mode(0o600);
header.set_mtime(0);
header.set_entry_type(tar::EntryType::Regular);
archive
.append_data(&mut header, &rollout.filename, rollout.buffer.as_slice())
.context("failed to write rollout archive")?;
filenames.insert(rollout.filename.clone());
Ok(())
}
struct BoundedWriter<W> {
inner: W,
written: usize,
max_bytes: usize,
}
impl<W: Write> Write for BoundedWriter<W> {
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
if buffer.len() > self.max_bytes.saturating_sub(self.written) {
return Err(io::Error::other("rollout archive exceeds the size limit"));
}
let written = self.inner.write(buffer)?;
self.written += written;
Ok(written)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}

View File

@@ -90,18 +90,5 @@ fn save_preserves_duplicate_names_and_rejects_missing_selected_files() -> Result
.unwrap_err();
assert!(format!("{error:#}").contains("selected attachment"));
assert_eq!(fs::read_dir(output.path())?.count(), 0);
// Upload still uses its existing best-effort aggregation and skips the missing rollout.
let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None);
let uploaded = snapshot
.feedback_attachments(
&sentry::protocol::EnvelopeHeaders::default(),
/*include_logs*/ false,
Vec::new(),
&paths,
/*logs_override*/ None,
)
.collect::<Result<Vec<_>>>()?;
assert_eq!(uploaded.len(), 1);
assert_eq!(uploaded[0].filename, "rollouts.tar.gz");
Ok(())
}

View File

@@ -1,153 +0,0 @@
use std::io;
use std::io::Write;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;
use anyhow::Result;
use bytes::Bytes;
use codex_http_client::RequestBuilder;
use codex_http_client::RouteAwareClientPool;
use flate2::Compression;
use flate2::write::GzEncoder;
use http::HeaderMap;
use http::StatusCode;
use sentry::ClientOptions;
use sentry::protocol::Attachment;
use sentry::protocol::Envelope;
use sentry::protocol::EnvelopeHeaders;
use sentry::protocol::EnvelopeItem;
use sentry::types::Dsn;
use crate::MAX_DECODED_UPLOAD_BYTES;
pub(super) const DEFAULT_RATE_LIMIT: Duration = Duration::from_secs(/*secs*/ 60);
pub(super) enum EnvelopeKind {
Event,
Attachment,
}
pub(super) fn envelope_request(
client_pool: &RouteAwareClientPool,
dsn: &Dsn,
body: Bytes,
timeout: Duration,
) -> RequestBuilder {
let sentry_options = ClientOptions::default();
let sentry_auth = dsn.to_auth(Some(sentry_options.user_agent.as_ref()));
let request = client_pool
.post(dsn.envelope_api_url().as_str())
.header("X-Sentry-Auth", sentry_auth.to_string());
// Persisted parts retain their encoding. Gzip's magic bytes cannot begin
// an uncompressed envelope, which starts with a JSON header.
let request = if body.starts_with(&[0x1f, 0x8b]) {
request.header("Content-Encoding", "gzip")
} else {
request
};
request.body(body).timeout(timeout)
}
/// Send an already-serialized envelope within the report's shared deadline.
///
/// aKode: feedback is never uploaded to a remote service (upstream sent it to
/// Sentry). The signature is kept so callers compile; it always fails.
pub(super) async fn send_envelope(
_client_pool: &RouteAwareClientPool,
_dsn: &Dsn,
_body: Vec<u8>,
_kind: EnvelopeKind,
_deadline: Instant,
_rate_limited: &mut bool,
) -> Result<StatusCode> {
anyhow::bail!("feedback upload is disabled in aKode; use the local save option instead")
}
pub(super) fn sentry_rate_limit_delay(headers: &HeaderMap) -> Option<Duration> {
let mut retry_after = None;
for value in headers.get_all("X-Sentry-Rate-Limits") {
for quota in value.to_str().unwrap_or_default().split(',') {
let mut fields = quota.trim().split(':');
let seconds = fields.next().unwrap_or_default();
let categories = fields.next().unwrap_or_default();
if !categories.is_empty()
&& !categories
.split(';')
.any(|category| matches!(category, "error" | "attachment"))
{
continue;
}
let delay = seconds
.parse::<f64>()
.ok()
.and_then(|seconds| Duration::try_from_secs_f64(seconds.ceil()).ok())
.unwrap_or(DEFAULT_RATE_LIMIT);
retry_after = retry_after.max(Some(delay));
}
}
retry_after
}
pub(super) fn parse_retry_after(value: &str) -> Option<Duration> {
value
.parse::<u64>()
.map(Duration::from_secs)
.or_else(|_| {
httpdate::parse_http_date(value)
.map(|date| date.duration_since(SystemTime::now()).unwrap_or_default())
})
.ok()
}
pub(super) fn encode_envelope(envelope: &Envelope) -> io::Result<(Vec<u8>, usize)> {
let mut writer = CountingWriter {
inner: GzEncoder::new(Vec::new(), Compression::fast()),
bytes: 0,
};
envelope.to_writer(&mut writer)?;
let decoded_bytes = writer.bytes;
let mut body = writer.inner.finish()?;
// Already-compressed attachments can grow beyond Sentry's 200 MiB wire limit.
// Reuse the buffer for the raw envelope when gzip does not make it smaller.
if body.len() >= decoded_bytes {
body.clear();
envelope.to_writer(&mut body)?;
}
Ok((body, decoded_bytes))
}
pub(super) fn encode_attachment_envelope(
headers: &EnvelopeHeaders,
attachment: Attachment,
) -> Result<Vec<u8>> {
anyhow::ensure!(
attachment.buffer.len() <= MAX_DECODED_UPLOAD_BYTES,
"feedback attachment exceeds the size limit"
);
let mut envelope = Envelope::new().with_headers(headers.clone());
envelope.add_item(EnvelopeItem::Attachment(attachment));
let (body, decoded_bytes) = encode_envelope(&envelope)?;
anyhow::ensure!(
decoded_bytes <= MAX_DECODED_UPLOAD_BYTES,
"feedback attachment envelope exceeds the size limit"
);
Ok(body)
}
struct CountingWriter<W> {
inner: W,
bytes: usize,
}
impl<W: Write> Write for CountingWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let written = self.inner.write(buf)?;
self.bytes += written;
Ok(written)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}