返回 CodeWhale
telemetry.rs
根目录 / crates / config / src / telemetry.rs
1 use crate::display_redaction::parse_bool;
2
3 /// Where an enabled session's batches go when nobody has said otherwise.
4 ///
5 /// The first-party ingest service — a Cloudflare Worker that appends to Workers
6 /// Analytics Engine. See
7 /// `docs/TELEMETRY.md` for what a batch contains and `telemetry-ingest/` for the handler.
8 ///
9 /// This is a *default*, not a floor, and it changes nothing about permission:
10 /// `CODEWHALE_TELEMETRY=0`, `telemetry = false`, and a recorded decline all
11 /// stop the session long before an endpoint is read.
12 ///
13 /// An explicit value — `CODEWHALE_TELEMETRY_ENDPOINT` or `telemetry_endpoint` in
14 /// the config file — wins outright, and an explicit *empty* value resolves to no
15 /// endpoint at all, which is the local dry-run sink: batches are serialized
16 /// exactly as a server would see them and appended to
17 /// `$CODEWHALE_HOME/telemetry/dryrun.jsonl`, and no HTTP client is constructed.
18 pub const DEFAULT_TELEMETRY_ENDPOINT: &str = "https://telemetry.codewhale.net/v1/telemetry";
19
20 /// Provider-neutral credential value forwarded from the CLI dispatcher to the
21 /// in-process TUI when `--api-key` must survive profile-late route selection.
22 pub const CLI_API_KEY_ENV: &str = "CODEWHALE_CLI_API_KEY";
23
24 /// Source marker paired with [`CLI_API_KEY_ENV`] on the CLI-to-TUI boundary.
25 pub const CLI_API_KEY_SOURCE_ENV: &str = "CODEWHALE_CLI_API_KEY_SOURCE";
26
27 /// Read-only compatibility alias used by dispatchers before v0.9.12.
28 pub const LEGACY_CLI_API_KEY_SOURCE_ENV: &str = "DEEPSEEK_API_KEY_SOURCE";
29
30 /// The dispatcher's statement to the TUI child about *why* telemetry is off.
31 ///
32 /// Private to the `codewhale` → `codewhale-tui` hop, in the same spirit as
33 /// [`CLI_API_KEY_SOURCE_ENV`]. Set to `1`/`0` on every delegated run.
34 pub const TELEMETRY_FLOOR_ENV: &str = "CODEWHALE_TELEMETRY_FLOOR";
35
36 pub const TELEMETRY_SOURCE_ENV: &str = "CODEWHALE_TELEMETRY_SOURCE";
37
38 /// Whether an environment-level kill switch forces telemetry off here.
39 ///
40 /// A floor is *not* the same as "telemetry resolved to false": off is the
41 /// default, and the dispatcher forwards a resolved `CODEWHALE_TELEMETRY=false`
42 /// on every ordinary run, so a child reading only that value cannot tell an
43 /// operator's declared kill switch from the shipped default. That distinction
44 /// matters exactly once — the first-run notice must not ask a question whose
45 /// answer this environment overrides — so the dispatcher states it outright in
46 /// [`TELEMETRY_FLOOR_ENV`] and the child believes the statement.
47 ///
48 /// With no statement (a directly launched `codewhale-tui`) the raw environment
49 /// is read instead, where an explicit "off" or an unreadable value is a floor.
50 #[must_use]
51 pub fn telemetry_floor_in_force() -> bool {
52 if do_not_track() {
53 return true;
54 }
55 if let Ok(raw) = std::env::var(TELEMETRY_FLOOR_ENV)
56 && let Ok(declared) = parse_bool(&raw)
57 {
58 return declared;
59 }
60 let Ok(raw) =
61 std::env::var("CODEWHALE_TELEMETRY").or_else(|_| std::env::var("DEEPSEEK_TELEMETRY"))
62 else {
63 return false;
64 };
65 !matches!(parse_bool(&raw), Ok(true))
66 }
67
68 #[must_use]
69 pub fn is_do_not_track_value(raw: &str) -> bool {
70 let trimmed = raw.trim();
71 if trimmed.is_empty() {
72 return false;
73 }
74 !matches!(
75 trimmed.to_ascii_lowercase().as_str(),
76 "0" | "false" | "no" | "off"
77 )
78 }
79
80 #[must_use]
81 pub fn do_not_track() -> bool {
82 std::env::var("DO_NOT_TRACK").is_ok_and(|raw| is_do_not_track_value(&raw))
83 }
84
85 /// Where resolved telemetry consent came from (#5441).
86 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
87 pub enum TelemetrySource {
88 /// `--telemetry` on this run's command line.
89 Cli,
90 /// `CODEWHALE_TELEMETRY`/`DEEPSEEK_TELEMETRY`, including the dispatcher's
91 /// floor statement and every environment kill switch.
92 Env,
93 /// `telemetry = …` written to the config file.
94 Config,
95 /// Nobody said anything; the shipped preference is on.
96 Default,
97 }
98
99 impl TelemetrySource {
100 /// Stable label for the doctor row and config display.
101 #[must_use]
102 pub const fn as_str(self) -> &'static str {
103 match self {
104 Self::Cli => "cli",
105 Self::Env => "env",
106 Self::Config => "config",
107 Self::Default => "default",
108 }
109 }
110
111 #[must_use]
112 pub fn from_label(label: &str) -> Option<Self> {
113 match label {
114 "cli" => Some(Self::Cli),
115 "env" => Some(Self::Env),
116 "config" => Some(Self::Config),
117 "default" => Some(Self::Default),
118 _ => None,
119 }
120 }
121 }
122
123 #[must_use]
124 pub fn dispatched_telemetry_source() -> Option<TelemetrySource> {
125 parse_bool(&std::env::var(TELEMETRY_FLOOR_ENV).ok()?).ok()?;
126 TelemetrySource::from_label(&std::env::var(TELEMETRY_SOURCE_ENV).ok()?)
127 }
128
129 #[must_use]
130 pub fn dispatched_telemetry_consent(file_telemetry: Option<bool>) -> (bool, TelemetrySource) {
131 let (on, source) = resolved_telemetry_consent(file_telemetry);
132 match (source, dispatched_telemetry_source()) {
133 (TelemetrySource::Env, Some(declared)) => (on, declared),
134 _ => (on, source),
135 }
136 }
137
138 /// Read the telemetry environment override, reporting an unreadable value
139 /// instead of swallowing it.
140 ///
141 /// Returns `(value, invalid)`. `invalid` is `true` only when the variable
142 /// was set to something [`parse_bool`] rejected; an unset variable is
143 /// simply `(None, false)`. Shared by the runtime resolver and the
144 /// provenance surfaces so they cannot drift.
145 pub(crate) fn read_telemetry_env() -> (Option<bool>, bool) {
146 if do_not_track() {
147 return (Some(false), false);
148 }
149 let Some(raw) = std::env::var("CODEWHALE_TELEMETRY")
150 .or_else(|_| std::env::var("DEEPSEEK_TELEMETRY"))
151 .ok()
152 else {
153 return (None, false);
154 };
155 match parse_bool(&raw) {
156 Ok(value) => (Some(value), false),
157 Err(_) => {
158 tracing::warn!(
159 "Invalid CODEWHALE_TELEMETRY/DEEPSEEK_TELEMETRY value; expected one of \
160 1/0, true/false, yes/no, on/off, enabled/disabled. Telemetry is forced off."
161 );
162 (None, true)
163 }
164 }
165 }
166
167 /// Resolved telemetry consent with its source, for surfaces that hold the
168 /// config-file value but not the full CLI/env resolution chain — the doctor
169 /// runtime-posture row and the `config get telemetry` display (#5441).
170 ///
171 /// This is the same resolution `ConfigToml::resolve_runtime_options`
172 /// applies without its CLI term: environment first (an explicit value, an
173 /// unreadable one, or a dispatcher floor), then the file, then the shipped
174 /// default of `on`; a persisted `telemetry = false` is a floor no later
175 /// term can climb over. The runtime resolver calls this directly, so the
176 /// preference surfaces agree. The telemetry owner also checks historical
177 /// durable declines and fails closed on unreadable privacy state.
178 #[must_use]
179 pub fn resolved_telemetry_consent(file_telemetry: Option<bool>) -> (bool, TelemetrySource) {
180 let (env_telemetry, env_invalid) = read_telemetry_env();
181 telemetry_consent_from_env(
182 env_telemetry,
183 env_invalid,
184 telemetry_floor_in_force(),
185 file_telemetry,
186 )
187 }
188
189 /// The decision core shared by [`resolved_telemetry_consent`] and the runtime
190 /// resolver, which already holds a snapshot of the same environment facts.
191 #[must_use]
192 pub(crate) fn telemetry_consent_from_env(
193 env_telemetry: Option<bool>,
194 env_invalid: bool,
195 floor: bool,
196 file_telemetry: Option<bool>,
197 ) -> (bool, TelemetrySource) {
198 let persisted_off = file_telemetry == Some(false);
199 let allowed = env_telemetry.or(file_telemetry).unwrap_or(true);
200 let on = allowed && env_telemetry != Some(false) && !env_invalid && !floor && !persisted_off;
201 let source = if !on && (env_telemetry == Some(false) || env_invalid || floor) {
202 // An environment kill switch decided the outcome.
203 TelemetrySource::Env
204 } else if !on && persisted_off {
205 // The persistent opt-out outranked everything else in play.
206 TelemetrySource::Config
207 } else if env_telemetry.is_some() {
208 TelemetrySource::Env
209 } else if file_telemetry.is_some() {
210 TelemetrySource::Config
211 } else {
212 TelemetrySource::Default
213 };
214 (on, source)
215 }
216
217 #[cfg(test)]
218 mod tests {
219 use super::is_do_not_track_value;
220
221 #[test]
222 fn do_not_track_matches_console_do_not_track_spec() {
223 for active in ["1", "true", "TRUE", "yes", "on", "please", "anything"] {
224 assert!(
225 is_do_not_track_value(active),
226 "expected active for {active:?}"
227 );
228 }
229 for inactive in ["", " ", "0", "false", "FALSE", "no", "off", " 0 "] {
230 assert!(
231 !is_do_not_track_value(inactive),
232 "expected inactive for {inactive:?}"
233 );
234 }
235 }
236 }
237
237 lines RUST