1use std::{collections::HashSet, time::Duration};
3
4use serde::Serialize;
5use uuid::Uuid;
6
7use crate::{
8 app_state::AppState,
9 jobs::registry::JobRegistry,
10 observability::declarations::{HogqlCheck, HogqlComparison, HogqlSeverity},
11};
12
13#[derive(Debug, thiserror::Error)]
14#[error("invalid manifest declaration: {0}")]
15pub struct ManifestDeclarationError(String);
16
17pub struct BootManifest<'a, S: AppState> {
18 pub app: &'a str,
19 pub git_sha: Option<&'a str>,
20 #[cfg(feature = "cron")]
21 pub registry: &'a crate::cron::CronRegistry<S>,
22 pub timezone: &'a jiff::tz::TimeZone,
23 pub critical_jobs: &'a [&'a str],
24 pub hogql_checks: &'a [HogqlCheck],
25 #[cfg(not(feature = "cron"))]
26 _state: std::marker::PhantomData<S>,
27}
28
29impl<'a, S: AppState> BootManifest<'a, S> {
30 #[cfg(feature = "cron")]
31 pub fn new(
32 app: &'a str,
33 registry: &'a crate::cron::CronRegistry<S>,
34 timezone: &'a jiff::tz::TimeZone,
35 critical_jobs: &'a [&'a str],
36 hogql_checks: &'a [HogqlCheck],
37 ) -> Self {
38 Self {
39 app,
40 git_sha: None,
41 registry,
42 timezone,
43 critical_jobs,
44 hogql_checks,
45 }
46 }
47 #[cfg(not(feature = "cron"))]
48 pub fn new(
49 app: &'a str,
50 timezone: &'a jiff::tz::TimeZone,
51 critical_jobs: &'a [&'a str],
52 hogql_checks: &'a [HogqlCheck],
53 ) -> Self {
54 Self {
55 app,
56 git_sha: None,
57 timezone,
58 critical_jobs,
59 hogql_checks,
60 _state: std::marker::PhantomData,
61 }
62 }
63 #[must_use]
64 pub fn git_sha(mut self, sha: &'a str) -> Self {
65 self.git_sha = Some(sha);
66 self
67 }
68}
69
70fn invalid(reason: impl Into<String>) -> ManifestDeclarationError {
71 ManifestDeclarationError(reason.into())
72}
73fn valid_name(name: &str) -> bool {
74 !name.is_empty()
75 && name.len() <= 128
76 && name
77 .bytes()
78 .all(|b| b.is_ascii_alphanumeric() || b"._:-".contains(&b))
79}
80fn validate_names<'a>(
81 names: impl IntoIterator<Item = &'a str>,
82) -> Result<(), ManifestDeclarationError> {
83 let mut seen = HashSet::new();
84 for name in names {
85 if !valid_name(name) || !seen.insert(name) {
86 return Err(invalid(format!("invalid or duplicate name: {name:?}")));
87 }
88 }
89 if seen.len() > 100 {
90 return Err(invalid("more than 100 declarations"));
91 }
92 Ok(())
93}
94
95#[derive(Serialize)]
96struct CronDeclaration {
97 name: String,
98 kind: &'static str,
99 #[serde(skip_serializing_if = "Option::is_none")]
100 interval_ms: Option<i64>,
101 #[serde(skip_serializing_if = "Option::is_none")]
102 expression: Option<String>,
103 #[serde(skip_serializing_if = "Option::is_none")]
104 timezone: Option<String>,
105 enabled: bool,
106}
107#[derive(Serialize)]
108struct JobDeclaration {
109 name: String,
110 critical: bool,
111 enabled: bool,
112}
113#[derive(Serialize)]
114struct MonitorDeclaration {
115 id: String,
116 target: String,
117 method: &'static str,
118 interval_seconds: u64,
119 timeout_seconds: u64,
120 expected_status_min: u16,
121 expected_status_max: u16,
122 failure_threshold: u32,
123 enabled: bool,
124}
125#[derive(Serialize)]
126struct CheckDeclaration<'a> {
127 name: &'a str,
128 query: &'a str,
129 comparison: HogqlComparison,
130 threshold: f64,
131 interval_seconds: u64,
132 severity: HogqlSeverity,
133 enabled: bool,
134}
135#[derive(Serialize)]
136struct Properties<'a> {
137 #[serde(rename = "$process_person_profile")]
138 process_person_profile: bool,
139 manifest_version: u8,
140 event_id: Uuid,
141 app: &'a str,
142 booted_at: String,
143 app_version: &'a str,
144 #[serde(skip_serializing_if = "Option::is_none")]
145 git_sha: Option<&'a str>,
146 #[serde(skip_serializing_if = "Option::is_none")]
147 base_url: Option<&'a str>,
148 crons: Vec<CronDeclaration>,
149 jobs: Vec<JobDeclaration>,
150 monitors: Vec<MonitorDeclaration>,
151 hogql_checks: Vec<CheckDeclaration<'a>>,
152}
153#[derive(Serialize)]
154struct Envelope<'a> {
155 uuid: Uuid,
156 api_key: &'a str,
157 event: &'static str,
158 distinct_id: String,
159 properties: Properties<'a>,
160}
161
162fn build_monitors<S: AppState>(
163 state: &S,
164) -> Result<(Option<&str>, Vec<MonitorDeclaration>), ManifestDeclarationError> {
165 let base_url = state.eyes_base_url();
166 let base = base_url
167 .map(|s| url::Url::parse(s).map_err(|_| invalid("invalid base URL")))
168 .transpose()?;
169 if base
170 .as_ref()
171 .is_some_and(|u| !matches!(u.scheme(), "http" | "https") || u.host().is_none())
172 {
173 return Err(invalid("invalid base URL"));
174 }
175 let mut monitors = Vec::new();
176 for m in state.eyes_http_monitors() {
177 if m.target.contains(['\\', '\t', '\r', '\n']) {
178 return Err(invalid("invalid monitor target"));
179 }
180 let (parsed, relative) = match url::Url::parse(&m.target) {
181 Ok(url) => (url, false),
182 Err(_) => (
183 base.as_ref()
184 .ok_or_else(|| invalid("relative monitor requires base URL"))?
185 .join(&m.target)
186 .map_err(|_| invalid("invalid monitor target"))?,
187 true,
188 ),
189 };
190 if !matches!(parsed.scheme(), "http" | "https")
191 || parsed.host().is_none()
192 || (relative && base.as_ref().is_some_and(|b| b.origin() != parsed.origin()))
193 {
194 return Err(invalid("invalid monitor origin"));
195 }
196 if m.interval_seconds == 0
197 || m.interval_seconds > i64::MAX as u64
198 || m.timeout_seconds == 0
199 || m.timeout_seconds > m.interval_seconds
200 || m.failure_threshold == 0
201 || m.failure_threshold > i32::MAX as u32
202 || !(100..=599).contains(&m.expected_status_min)
203 || !(100..=599).contains(&m.expected_status_max)
204 || m.expected_status_min > m.expected_status_max
205 {
206 return Err(invalid("invalid monitor bounds"));
207 }
208 monitors.push(MonitorDeclaration {
209 id: m.id,
210 target: m.target,
211 method: match m.method {
212 crate::app_state::HttpMethod::Get => "GET",
213 crate::app_state::HttpMethod::Head => "HEAD",
214 },
215 interval_seconds: m.interval_seconds,
216 timeout_seconds: m.timeout_seconds,
217 expected_status_min: m.expected_status_min,
218 expected_status_max: m.expected_status_max,
219 failure_threshold: m.failure_threshold,
220 enabled: m.enabled,
221 });
222 }
223 validate_names(monitors.iter().map(|m| m.id.as_str()))?;
224 monitors.sort_by(|a, b| a.id.cmp(&b.id));
225 Ok((base_url, monitors))
226}
227
228fn build_checks(
229 checks: &[HogqlCheck],
230) -> Result<Vec<CheckDeclaration<'_>>, ManifestDeclarationError> {
231 validate_names(checks.iter().map(|c| c.name.as_str()))?;
232 let mut declarations = Vec::new();
233 for c in checks {
234 if c.query.len() > 16 * 1024
235 || c.query.is_empty()
236 || !c.threshold.is_finite()
237 || !(300..=i64::MAX as u64).contains(&c.interval_seconds)
238 {
239 return Err(invalid("invalid HogQL check"));
240 }
241 declarations.push(CheckDeclaration {
242 name: &c.name,
243 query: &c.query,
244 comparison: c.comparison,
245 threshold: c.threshold,
246 interval_seconds: c.interval_seconds,
247 severity: c.severity,
248 enabled: true,
249 });
250 }
251 declarations.sort_by(|a, b| a.name.cmp(b.name));
252 Ok(declarations)
253}
254
255fn snapshot<'a, J, S>(
256 state: &'a S,
257 input: &'a BootManifest<'_, S>,
258 token: &'a str,
259 id: Uuid,
260 booted_at: &str,
261) -> Result<Vec<u8>, ManifestDeclarationError>
262where
263 J: JobRegistry<S>,
264 S: AppState,
265{
266 crate::observability::posthog::slug(input.app).map_err(invalid)?;
267 #[cfg(feature = "cron")]
268 let mut crons: Vec<CronDeclaration> = Vec::new();
269 #[cfg(not(feature = "cron"))]
270 let crons: Vec<CronDeclaration> = Vec::new();
271 #[cfg(feature = "cron")]
272 for job in input.registry.jobs().values() {
273 let (kind, interval_ms, expression, timezone) = match &job.schedule {
274 crate::cron::Schedule::Interval(interval) => {
275 let ms = interval.0.as_millis();
276 let ms =
277 i64::try_from(ms).map_err(|_| invalid("interval exceeds i64 milliseconds"))?;
278 if ms == 0 {
279 return Err(invalid("interval must be positive"));
280 }
281 ("interval", Some(ms), None, None)
282 }
283 crate::cron::Schedule::Cron(cron) => {
284 let zone = input
285 .timezone
286 .iana_name()
287 .ok_or_else(|| invalid("timezone must be IANA"))?;
288 let expr = cron.0.to_string();
289 crate::cron::parse_cron(&expr)
290 .map_err(|_| invalid("unparseable cron expression"))?;
291 ("cron", None, Some(expr), Some(zone.to_owned()))
292 }
293 };
294 crons.push(CronDeclaration {
295 name: job.name.to_owned(),
296 kind,
297 interval_ms,
298 expression,
299 timezone,
300 enabled: true,
301 });
302 }
303 validate_names(crons.iter().map(|c| c.name.as_str()))?;
304 #[cfg(feature = "cron")]
305 crons.sort_by(|a, b| a.name.cmp(&b.name));
306 validate_names(J::job_names().iter().copied())?;
307 validate_names(input.critical_jobs.iter().copied())?;
308 let critical: HashSet<_> = input.critical_jobs.iter().copied().collect();
309 if !critical.iter().all(|name| J::job_names().contains(name)) {
310 return Err(invalid("unknown critical job"));
311 }
312 let mut jobs: Vec<_> = J::job_names()
313 .iter()
314 .map(|name| JobDeclaration {
315 name: (*name).to_owned(),
316 critical: critical.contains(name),
317 enabled: true,
318 })
319 .collect();
320 jobs.sort_by(|a, b| a.name.cmp(&b.name));
321 let (base_url, monitors) = build_monitors(state)?;
322 let checks = build_checks(input.hogql_checks)?;
323 let properties = Properties {
324 process_person_profile: false,
325 manifest_version: 1,
326 event_id: id,
327 app: input.app,
328 booted_at: booted_at.to_owned(),
329 app_version: state.version(),
330 git_sha: input.git_sha,
331 base_url,
332 crons,
333 jobs,
334 monitors,
335 hogql_checks: checks,
336 };
337 let size = serde_json::to_vec(&properties)
338 .map_err(|e| invalid(e.to_string()))?
339 .len();
340 if size > 256 * 1024 {
341 return Err(invalid("manifest properties exceed 256 KiB"));
342 }
343 serde_json::to_vec(&Envelope {
344 uuid: id,
345 api_key: token,
346 event: "cja_manifest",
347 distinct_id: format!("cja:{}", input.app),
348 properties,
349 })
350 .map_err(|e| invalid(e.to_string()))
351}
352
353pub fn emit_boot_manifest<J, S>(
355 state: &S,
356 input: &BootManifest<'_, S>,
357) -> Result<(), ManifestDeclarationError>
358where
359 J: JobRegistry<S>,
360 S: AppState,
361{
362 let id = Uuid::new_v4();
364 let booted_at = jiff::Timestamp::now()
365 .round(
366 jiff::TimestampRound::new()
367 .smallest(jiff::Unit::Microsecond)
368 .mode(jiff::RoundMode::Trunc),
369 )
370 .map_err(|_| invalid("invalid boot time"))?
371 .to_string();
372 let validation = snapshot::<J, S>(state, input, "", id, &booted_at)?;
373 drop(validation);
374 let credentials = match crate::setup::posthog::PostHogCredentials::from_env() {
375 Ok(Some(c)) => c,
376 Ok(None) => return Ok(()),
377 Err(error) => {
378 tracing::warn!(%error, "skipping PostHog manifest capture");
379 return Ok(());
380 }
381 };
382 let bytes = snapshot::<J, S>(state, input, &credentials.token, id, &booted_at)?;
383 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
384 tracing::warn!("PostHog manifest capture requires a Tokio runtime");
385 return Ok(());
386 };
387 runtime.spawn(send(bytes, credentials.host));
388 Ok(())
389}
390
391async fn send(bytes: Vec<u8>, host: String) {
392 let tls = match crate::tls::ring_client_config() {
393 Ok(t) => t,
394 Err(e) => {
395 tracing::warn!(%e, "manifest TLS unavailable");
396 return;
397 }
398 };
399 let client = match reqwest_012::Client::builder()
400 .use_preconfigured_tls(tls)
401 .redirect(reqwest_012::redirect::Policy::none())
402 .connect_timeout(Duration::from_secs(2))
403 .timeout(Duration::from_secs(5))
404 .build()
405 {
406 Ok(c) => c,
407 Err(e) => {
408 tracing::warn!(%e, "manifest HTTP client unavailable");
409 return;
410 }
411 };
412 let endpoint = format!("{host}/i/v0/e/");
414 let started = tokio::time::Instant::now();
415 let mut delay = Duration::from_secs(1);
416 let mut last_class = None;
417 while started.elapsed() < Duration::from_hours(24) {
418 let response = client
419 .post(&endpoint)
420 .header("content-type", "application/json")
421 .body(bytes.clone())
422 .send()
423 .await;
424 let (class, retry_after) = match response {
425 Ok(r) if r.status().is_success() => {
426 if last_class.is_some() {
427 tracing::info!("manifest capture recovered");
428 }
429 return;
430 }
431 Ok(r) => {
432 let code = r.status().as_u16();
433 if code != 408 && code != 429 && code < 500 {
434 tracing::warn!(code, "manifest capture rejected");
435 return;
436 }
437 let retry = retry_after(r.headers());
438 (format!("HTTP {code}"), retry)
439 }
440 Err(e) => (
441 if e.is_timeout() { "timeout" } else { "network" }.to_owned(),
442 None,
443 ),
444 };
445 if last_class.as_ref() != Some(&class) {
446 tracing::warn!(%class, "manifest capture retrying");
447 last_class = Some(class);
448 }
449 tokio::time::sleep(retry_after.unwrap_or(delay)).await;
450 delay = (delay * 2).min(Duration::from_secs(300));
451 }
452 tracing::warn!("manifest capture expired after 24 hours");
453}
454
455fn retry_after(headers: &reqwest_012::header::HeaderMap) -> Option<Duration> {
456 headers
457 .get("retry-after")
458 .and_then(|v| v.to_str().ok())
459 .and_then(|s| s.parse::<u64>().ok())
460 .map(|s| Duration::from_secs(s.clamp(1, 300)))
461}
462
463#[cfg(test)]
464mod tests {
465 use super::*;
466 use crate::{app_state::HttpMonitor, server::cookies::CookieKey};
467
468 #[derive(Clone)]
469 struct EventLog(std::sync::Arc<std::sync::Mutex<Vec<String>>>);
470 impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for EventLog {
471 fn on_event(
472 &self,
473 event: &tracing::Event<'_>,
474 _: tracing_subscriber::layer::Context<'_, S>,
475 ) {
476 struct Message(String);
477 impl tracing::field::Visit for Message {
478 fn record_debug(
479 &mut self,
480 field: &tracing::field::Field,
481 value: &dyn std::fmt::Debug,
482 ) {
483 if field.name() == "message" {
484 self.0 = format!("{value:?}");
485 }
486 }
487 }
488 let mut message = Message(String::new());
489 event.record(&mut message);
490 self.0.lock().unwrap().push(message.0);
491 }
492 }
493 fn count_log(log: &EventLog, needle: &str) -> usize {
494 log.0
495 .lock()
496 .unwrap()
497 .iter()
498 .filter(|entry| entry.contains(needle))
499 .count()
500 }
501
502 #[derive(Clone)]
503 struct State {
504 db: sqlx::PgPool,
505 key: CookieKey,
506 target: &'static str,
507 monitor: Option<HttpMonitor>,
508 base_url: Option<&'static str>,
509 }
510 impl AppState for State {
511 fn version(&self) -> &'static str {
512 "1.0.0"
513 }
514 fn db(&self) -> &sqlx::PgPool {
515 &self.db
516 }
517 fn cookie_key(&self) -> &CookieKey {
518 &self.key
519 }
520 fn eyes_base_url(&self) -> Option<&str> {
521 self.base_url
522 }
523 fn eyes_http_monitors(&self) -> Vec<HttpMonitor> {
524 vec![
525 self.monitor
526 .clone()
527 .unwrap_or_else(|| HttpMonitor::new("home", self.target)),
528 ]
529 }
530 }
531 fn state() -> State {
532 State {
533 db: sqlx::postgres::PgPoolOptions::new()
534 .connect_lazy("postgres:///test")
535 .unwrap(),
536 key: CookieKey::from_env_or_generate().unwrap(),
537 target: "/health",
538 monitor: None,
539 base_url: Some("https://demo.example.com"),
540 }
541 }
542 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
543 struct Work;
544 #[async_trait::async_trait]
545 impl crate::jobs::Job<State> for Work {
546 const NAME: &'static str = "work";
547 async fn run(&self, _: State) -> crate::Result<()> {
548 Ok(())
549 }
550 }
551 crate::impl_job_registry!(State, Work);
552 mod invalid_jobs {
553 use super::*;
554 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
555 pub(super) struct Invalid;
556 #[async_trait::async_trait]
557 impl crate::jobs::Job<State> for Invalid {
558 const NAME: &'static str = "bad job";
559 async fn run(&self, _: State) -> crate::Result<()> {
560 Ok(())
561 }
562 }
563 crate::impl_job_registry!(State, Invalid);
564 }
565 #[test]
566 fn declaration_name_limits_and_duplicates() {
567 assert!(validate_names(["A".repeat(128).as_str()]).is_ok());
568 assert!(validate_names(["A".repeat(129).as_str()]).is_err());
569 assert!(validate_names(["duplicate", "duplicate"]).is_err());
570 let names: Vec<_> = (0..100).map(|n| format!("item-{n}")).collect();
571 assert!(validate_names(names.iter().map(String::as_str)).is_ok());
572 let names: Vec<_> = (0..101).map(|n| format!("item-{n}")).collect();
573 assert!(validate_names(names.iter().map(String::as_str)).is_err());
574 }
575 #[test]
576 fn invalid_checks_are_rejected_without_credentials() {
577 let invalid = [
578 HogqlCheck::new(
579 "bad name",
580 "SELECT 1",
581 HogqlComparison::Gt,
582 1.0,
583 300,
584 HogqlSeverity::Warning,
585 ),
586 HogqlCheck::new(
587 "ok",
588 "SELECT 1",
589 HogqlComparison::Gt,
590 f64::NAN,
591 300,
592 HogqlSeverity::Warning,
593 ),
594 HogqlCheck::new(
595 "ok",
596 "SELECT 1",
597 HogqlComparison::Gt,
598 1.0,
599 299,
600 HogqlSeverity::Warning,
601 ),
602 ];
603 for check in invalid {
604 assert!(build_checks(&[check]).is_err());
605 }
606 let duplicates = [
607 HogqlCheck::new(
608 "same",
609 "SELECT 1",
610 HogqlComparison::Gt,
611 1.0,
612 300,
613 HogqlSeverity::Warning,
614 ),
615 HogqlCheck::new(
616 "same",
617 "SELECT 1",
618 HogqlComparison::Gt,
619 1.0,
620 300,
621 HogqlSeverity::Warning,
622 ),
623 ];
624 assert!(build_checks(&duplicates).is_err());
625 }
626 #[test]
627 fn retry_after_is_bounded() {
628 let mut headers = reqwest_012::header::HeaderMap::new();
629 assert_eq!(retry_after(&headers), None);
630 headers.insert("retry-after", "0".parse().unwrap());
631 assert_eq!(retry_after(&headers), Some(Duration::from_secs(1)));
632 headers.insert("retry-after", "300".parse().unwrap());
633 assert_eq!(retry_after(&headers), Some(Duration::from_secs(300)));
634 headers.insert("retry-after", "301".parse().unwrap());
635 assert_eq!(retry_after(&headers), Some(Duration::from_secs(300)));
636 headers.insert("retry-after", "bogus".parse().unwrap());
637 assert_eq!(retry_after(&headers), None);
638 }
639 #[allow(clippy::too_many_lines)] #[tokio::test]
641 async fn snapshot_validates_declaration_boundaries() {
642 let id = Uuid::new_v4();
643 let zone = jiff::tz::TimeZone::UTC;
644 let registry = crate::cron::CronRegistry::new();
645 let valid = |state: &State,
646 registry: &crate::cron::CronRegistry<State>,
647 zone: &jiff::tz::TimeZone,
648 checks: &[HogqlCheck]| {
649 let input = BootManifest::new("demo", registry, zone, &["work"], checks);
650 snapshot::<Jobs, State>(state, &input, "", id, "2026-11-18T18:00:00Z").is_ok()
651 };
652 for (label, monitor, base, expected) in [
653 (
654 "interval zero",
655 HttpMonitor::new("home", "/health").interval_seconds(0),
656 Some("https://demo.example.com"),
657 false,
658 ),
659 (
660 "interval one",
661 HttpMonitor::new("home", "/health")
662 .interval_seconds(1)
663 .timeout_seconds(1),
664 Some("https://demo.example.com"),
665 true,
666 ),
667 (
668 "timeout zero",
669 HttpMonitor::new("home", "/health").timeout_seconds(0),
670 Some("https://demo.example.com"),
671 false,
672 ),
673 (
674 "timeout greater",
675 HttpMonitor::new("home", "/health")
676 .interval_seconds(1)
677 .timeout_seconds(2),
678 Some("https://demo.example.com"),
679 false,
680 ),
681 (
682 "timeout equal",
683 HttpMonitor::new("home", "/health")
684 .interval_seconds(10)
685 .timeout_seconds(10),
686 Some("https://demo.example.com"),
687 true,
688 ),
689 (
690 "failure zero",
691 HttpMonitor::new("home", "/health").failure_threshold(0),
692 Some("https://demo.example.com"),
693 false,
694 ),
695 (
696 "status 99",
697 HttpMonitor::new("home", "/health").expected_status(99, 200),
698 Some("https://demo.example.com"),
699 false,
700 ),
701 (
702 "status 100",
703 HttpMonitor::new("home", "/health").expected_status(100, 100),
704 Some("https://demo.example.com"),
705 true,
706 ),
707 (
708 "status 599",
709 HttpMonitor::new("home", "/health").expected_status(599, 599),
710 Some("https://demo.example.com"),
711 true,
712 ),
713 (
714 "status 600",
715 HttpMonitor::new("home", "/health").expected_status(200, 600),
716 Some("https://demo.example.com"),
717 false,
718 ),
719 (
720 "status reversed",
721 HttpMonitor::new("home", "/health").expected_status(300, 200),
722 Some("https://demo.example.com"),
723 false,
724 ),
725 (
726 "missing base",
727 HttpMonitor::new("home", "health"),
728 None,
729 false,
730 ),
731 (
732 "cross origin relative",
733 HttpMonitor::new("home", "//evil.example/x"),
734 Some("https://demo.example.com"),
735 false,
736 ),
737 (
738 "other absolute origin",
739 HttpMonitor::new("home", "https://other.example/x"),
740 Some("https://demo.example.com"),
741 true,
742 ),
743 (
744 "invalid id",
745 HttpMonitor::new("bad id", "/health"),
746 Some("https://demo.example.com"),
747 false,
748 ),
749 ] {
750 let state = State {
751 monitor: Some(monitor),
752 base_url: base,
753 ..state()
754 };
755 assert_eq!(valid(&state, ®istry, &zone, &[]), expected, "{label}");
756 }
757 let state = state();
758 for (label, interval, query, expected) in [
759 ("check interval 299", 299, "SELECT 1".to_owned(), false),
760 ("check interval 300", 300, "SELECT 1".to_owned(), true),
761 ("empty query", 300, String::new(), false),
762 ("query 16KiB", 300, "x".repeat(16 * 1024), true),
763 ("query 16KiB+1", 300, "x".repeat(16 * 1024 + 1), false),
764 ] {
765 let checks = [HogqlCheck::new(
766 "check",
767 query,
768 HogqlComparison::Gt,
769 1.0,
770 interval,
771 HogqlSeverity::Warning,
772 )];
773 assert_eq!(
774 valid(&state, ®istry, &zone, &checks),
775 expected,
776 "{label}"
777 );
778 }
779 for (count, query) in [(20, "x".repeat(15 * 1024)), (101, "SELECT 1".to_owned())] {
780 let checks: Vec<_> = (0..count)
781 .map(|i| {
782 HogqlCheck::new(
783 format!("check-{i}"),
784 query.clone(),
785 HogqlComparison::Gt,
786 1.0,
787 300,
788 HogqlSeverity::Warning,
789 )
790 })
791 .collect();
792 assert!(!valid(&state, ®istry, &zone, &checks), "count={count}");
793 }
794 let mut zero = crate::cron::CronRegistry::new();
795 zero.register_job(Work, None, Duration::ZERO);
796 assert!(!valid(&state, &zero, &zone, &[]));
797 let fixed = jiff::tz::TimeZone::fixed(jiff::tz::Offset::from_seconds(3600).unwrap());
798 let mut interval = crate::cron::CronRegistry::new();
799 interval.register_job(Work, None, Duration::from_secs(300));
800 assert!(valid(&state, &interval, &fixed, &[]));
801 let mut cron = crate::cron::CronRegistry::new();
802 cron.register_job_with_cron(Work, None, "0 * * * * *")
803 .unwrap();
804 assert!(!valid(&state, &cron, &fixed, &[]));
805 let unknown = BootManifest::new("demo", ®istry, &zone, &["missing"], &[]);
806 assert!(snapshot::<Jobs, State>(&state, &unknown, "", id, "2026-11-18T18:00:00Z").is_err());
807 let invalid_job = BootManifest::new("demo", ®istry, &zone, &[], &[]);
808 assert!(
809 snapshot::<invalid_jobs::Jobs, State>(
810 &state,
811 &invalid_job,
812 "",
813 id,
814 "2026-11-18T18:00:00Z"
815 )
816 .is_err()
817 );
818 }
819 #[tokio::test]
820 async fn exact_fixture_shape_and_validation() {
821 let state = state();
822 let mut registry = crate::cron::CronRegistry::new();
823 registry.register_job(Work, None, Duration::from_secs(300));
824 let zone = jiff::tz::TimeZone::get("America/New_York").unwrap();
825 let check = HogqlCheck::new(
826 "errors",
827 "SELECT count() FROM events",
828 HogqlComparison::Gt,
829 0.0,
830 300,
831 HogqlSeverity::Warning,
832 );
833 let checks = [check];
834 let input =
835 BootManifest::new("demo", ®istry, &zone, &["work"], &checks).git_sha("abc123");
836 let id = Uuid::parse_str("a0000000-0000-0000-0000-000000000001").unwrap();
837 let bytes =
838 snapshot::<Jobs, State>(&state, &input, "token", id, "2026-11-18T18:00:00Z").unwrap();
839 let event: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
840 let mut fixture: serde_json::Value =
841 serde_json::from_str(include_str!("../tests/fixtures/cja_manifest_v1.json")).unwrap();
842 fixture["properties"]["hogql_checks"][0]["severity"] = "warning".into();
844 fixture["properties"]["crons"][0]["name"] = "work".into();
845 fixture["properties"]["app_version"] = "1.0.0".into();
846 fixture["properties"]["hogql_checks"][0]["threshold"] = serde_json::json!(0.0);
847 fixture["uuid"] = id.to_string().into();
848 fixture["api_key"] = "token".into();
849 assert_eq!(event, fixture);
850 assert!(event.get("timestamp").is_none());
851 assert!(event.get("sent_at").is_none());
852 assert!(event["properties"].get("process_role").is_none());
853 assert!(crate::cron::parse_cron("0 */5 * * * *").is_ok());
854 let mut cron_registry = crate::cron::CronRegistry::new();
855 cron_registry
856 .register_job_with_cron(Work, None, "0 */5 * * * *")
857 .unwrap();
858 let cron_input = BootManifest::new("demo", &cron_registry, &zone, &[], &[]);
859 let cron_event: serde_json::Value = serde_json::from_slice(
860 &snapshot::<Jobs, State>(&state, &cron_input, "", id, "2026-11-18T18:00:00Z").unwrap(),
861 )
862 .unwrap();
863 let cron = &cron_event["properties"]["crons"][0];
864 assert_eq!(cron["kind"], "cron");
865 assert_eq!(cron["timezone"], "America/New_York");
866 assert!(cron.get("interval_ms").is_none());
867 assert!(crate::cron::parse_cron(cron["expression"].as_str().unwrap()).is_ok());
868 let invalid = BootManifest::new("demo", ®istry, &zone, &["missing"], &checks);
869 assert!(snapshot::<Jobs, State>(&state, &invalid, "", id, "2026-11-18T18:00:00Z").is_err());
870 let escaped = State {
871 target: "//evil.example/health",
872 ..state.clone()
873 };
874 assert!(snapshot::<Jobs, State>(&escaped, &input, "", id, "2026-11-18T18:00:00Z").is_err());
875 let comparisons = [
876 HogqlComparison::Gt,
877 HogqlComparison::Gte,
878 HogqlComparison::Lt,
879 HogqlComparison::Lte,
880 HogqlComparison::Eq,
881 HogqlComparison::Neq,
882 ];
883 let all_checks: Vec<_> = comparisons
884 .into_iter()
885 .enumerate()
886 .map(|(n, comparison)| {
887 HogqlCheck::new(
888 format!("check-{n}"),
889 "SELECT 1",
890 comparison,
891 1.0,
892 300,
893 HogqlSeverity::Critical,
894 )
895 })
896 .collect();
897 let input = BootManifest::new("demo", ®istry, &zone, &[], &all_checks);
898 let event: serde_json::Value = serde_json::from_slice(
899 &snapshot::<Jobs, State>(&state, &input, "", id, "2026-11-18T18:00:00Z").unwrap(),
900 )
901 .unwrap();
902 let actual: Vec<_> = event["properties"]["hogql_checks"]
903 .as_array()
904 .unwrap()
905 .iter()
906 .map(|c| c["comparison"].as_str().unwrap())
907 .collect();
908 assert_eq!(actual, ["gt", "gte", "lt", "lte", "eq", "neq"]);
909 assert_eq!(event["properties"]["jobs"][0]["critical"], false);
910 let oversized = [HogqlCheck::new(
911 "bad",
912 "x".repeat(16 * 1024 + 1),
913 HogqlComparison::Gt,
914 0.0,
915 300,
916 HogqlSeverity::Info,
917 )];
918 let invalid = BootManifest::new("demo", ®istry, &zone, &[], &oversized);
919 assert!(snapshot::<Jobs, State>(&state, &invalid, "", id, "2026-11-18T18:00:00Z").is_err());
920 }
921
922 #[tokio::test]
927 async fn same_origin_relative_target_without_leading_slash_is_accepted() {
928 let registry = crate::cron::CronRegistry::new();
929 let zone = jiff::tz::TimeZone::UTC;
930 let input = BootManifest::new("demo", ®istry, &zone, &[], &[]);
931 let id = Uuid::parse_str("a0000000-0000-0000-0000-000000000001").unwrap();
932 let relative = State {
933 target: "health",
934 ..state()
935 };
936 let bytes = snapshot::<Jobs, State>(&relative, &input, "", id, "2026-11-18T18:00:00Z")
937 .expect("same-origin relative target accepted by Blink must be accepted by cja");
938 let event: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
939 assert_eq!(event["properties"]["monitors"][0]["target"], "health");
940 }
941
942 #[tokio::test]
943 async fn child_boot_marker() {
944 if std::env::var_os("CJA_MANIFEST_CHILD").is_none() {
945 return;
946 }
947 let state = state();
948 let registry = crate::cron::CronRegistry::new();
949 let zone = jiff::tz::TimeZone::UTC;
950 let input = BootManifest::new("demo", ®istry, &zone, &[], &[]);
951 emit_boot_manifest::<Jobs, State>(&state, &input).unwrap();
952 println!("BOOT_READY");
953 }
954
955 #[tokio::test]
956 async fn child_emit_and_linger() {
957 if std::env::var_os("CJA_MANIFEST_EMIT_CHILD").is_none() {
958 return;
959 }
960 use tracing_subscriber::prelude::*;
961 let subscriber = tracing_subscriber::registry()
962 .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr));
963 let _guard = tracing::subscriber::set_default(subscriber);
964 let state = state();
965 let mut registry = crate::cron::CronRegistry::new();
966 registry.register_job(Work, None, Duration::from_secs(300));
967 let zone = jiff::tz::TimeZone::UTC;
968 let checks = [HogqlCheck::new(
969 "errors",
970 "SELECT count() FROM events",
971 HogqlComparison::Gt,
972 0.0,
973 300,
974 HogqlSeverity::Warning,
975 )];
976 let input =
977 BootManifest::new("demo", ®istry, &zone, &["work"], &checks).git_sha("abc123");
978 emit_boot_manifest::<Jobs, State>(&state, &input).unwrap();
979 println!("BOOT_READY");
980 tokio::time::sleep(Duration::from_secs(3)).await;
981 }
982
983 #[allow(clippy::too_many_lines)] #[test]
985 fn emitter_reads_capture_credentials_independently_of_otlp() {
986 use std::{
987 io::{Read, Write},
988 process::{Command, Stdio},
989 time::Instant,
990 };
991 for (host_override, token, bad_otlp, expect_capture, expect_warning) in [
992 (None, Some("test-token"), false, true, false),
993 (None, Some("test-token"), true, true, false),
994 (Some("not a url"), Some("test-token"), false, false, true),
995 (Some("ftp://x"), Some("test-token"), false, false, true),
996 (None, Some("bad\ntoken"), false, false, true),
997 (None, None, false, false, false),
998 ] {
999 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1000 listener.set_nonblocking(true).unwrap();
1001 let mock_host = format!("http://{}", listener.local_addr().unwrap());
1002 let mut command = Command::new(std::env::current_exe().unwrap());
1003 crate::testing::scrub_telemetry_env(&mut command);
1004 command
1005 .args([
1006 "--exact",
1007 "posthog_manifest::tests::child_emit_and_linger",
1008 "--nocapture",
1009 ])
1010 .env("CJA_MANIFEST_EMIT_CHILD", "1")
1011 .env("POSTHOG_HOST", host_override.unwrap_or(&mock_host))
1012 .stdout(Stdio::piped())
1013 .stderr(Stdio::piped());
1014 if let Some(token) = token {
1015 command.env("POSTHOG_PROJECT_TOKEN", token);
1016 } else {
1017 command.env_remove("POSTHOG_PROJECT_TOKEN");
1018 }
1019 if bad_otlp {
1020 command
1021 .env("POSTHOG_LOG_LEVEL", "bogus")
1022 .env("POSTHOG_TRACES_SAMPLE_RATIO", "7");
1023 } else {
1024 command
1025 .env_remove("POSTHOG_LOG_LEVEL")
1026 .env_remove("POSTHOG_TRACES_SAMPLE_RATIO");
1027 }
1028 let mut child = command.spawn().unwrap();
1029 let started = Instant::now();
1030 let mut captured = None;
1031 while started.elapsed() < Duration::from_secs(4) {
1032 match listener.accept() {
1033 Ok((mut stream, _)) => {
1034 stream
1035 .set_read_timeout(Some(Duration::from_secs(2)))
1036 .unwrap();
1037 let mut data = Vec::new();
1038 let header_end;
1039 loop {
1040 let mut chunk = [0; 4096];
1041 let n = stream.read(&mut chunk).unwrap();
1042 assert!(n > 0);
1043 data.extend_from_slice(&chunk[..n]);
1044 if let Some(pos) = data.windows(4).position(|w| w == b"\r\n\r\n") {
1045 header_end = pos + 4;
1046 break;
1047 }
1048 }
1049 let headers =
1050 String::from_utf8_lossy(&data[..header_end]).to_ascii_lowercase();
1051 assert!(headers.starts_with("post /i/v0/e/ http/1.1\r\n"));
1052 let len: usize = headers
1053 .lines()
1054 .find_map(|line| line.strip_prefix("content-length: "))
1055 .unwrap()
1056 .parse()
1057 .unwrap();
1058 while data.len() < header_end + len {
1059 let mut chunk = [0; 4096];
1060 let n = stream.read(&mut chunk).unwrap();
1061 assert!(n > 0);
1062 data.extend_from_slice(&chunk[..n]);
1063 }
1064 captured = Some(
1065 serde_json::from_slice::<serde_json::Value>(
1066 &data[header_end..header_end + len],
1067 )
1068 .unwrap(),
1069 );
1070 stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap();
1071 }
1072 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
1073 Err(e) => panic!("accept failed: {e}"),
1074 }
1075 if child.try_wait().unwrap().is_some() {
1076 break;
1077 }
1078 std::thread::sleep(Duration::from_millis(10));
1079 }
1080 if child.try_wait().unwrap().is_none() {
1081 child.kill().unwrap();
1082 panic!("child did not exit");
1083 }
1084 let output = child.wait_with_output().unwrap();
1085 assert!(
1086 output.status.success(),
1087 "{}",
1088 String::from_utf8_lossy(&output.stderr)
1089 );
1090 assert!(String::from_utf8_lossy(&output.stdout).contains("BOOT_READY"));
1091 assert_eq!(captured.is_some(), expect_capture);
1092 assert_eq!(
1093 String::from_utf8_lossy(&output.stderr)
1094 .contains("skipping PostHog manifest capture"),
1095 expect_warning
1096 );
1097 if let Some(body) = captured {
1098 assert_eq!(body["event"], "cja_manifest");
1099 assert_eq!(body["api_key"], "test-token");
1100 assert_eq!(body["distinct_id"], "cja:demo");
1101 assert_eq!(body["uuid"], body["properties"]["event_id"]);
1102 let fixture: serde_json::Value =
1103 serde_json::from_str(include_str!("../tests/fixtures/cja_manifest_v1.json"))
1104 .unwrap();
1105 let actual: std::collections::BTreeSet<_> =
1106 body["properties"].as_object().unwrap().keys().collect();
1107 let expected: std::collections::BTreeSet<_> =
1108 fixture["properties"].as_object().unwrap().keys().collect();
1109 assert_eq!(actual, expected);
1110 assert_eq!(body["properties"]["crons"].as_array().unwrap().len(), 1);
1111 assert_eq!(body["properties"]["jobs"][0]["critical"], true);
1112 assert_eq!(body["properties"]["monitors"].as_array().unwrap().len(), 1);
1113 assert_eq!(
1114 body["properties"]["hogql_checks"].as_array().unwrap().len(),
1115 1
1116 );
1117 }
1118 }
1119 }
1120
1121 #[tokio::test]
1122 async fn retry_reuses_identical_capture_bytes_and_uuid() {
1123 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
1124 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1125 let host = format!("http://{}", listener.local_addr().unwrap());
1126 let server = tokio::spawn(async move {
1127 let mut bodies = Vec::new();
1128 for status in ["503 Service Unavailable", "200 OK"] {
1129 let (mut stream, _) = listener.accept().await.unwrap();
1130 let mut buf = Vec::new();
1131 let header_end;
1132 loop {
1133 let mut chunk = [0u8; 4096];
1134 let count = stream.read(&mut chunk).await.unwrap();
1135 assert!(count > 0);
1136 buf.extend_from_slice(&chunk[..count]);
1137 if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
1138 header_end = pos + 4;
1139 break;
1140 }
1141 }
1142 let headers = String::from_utf8_lossy(&buf[..header_end]).to_ascii_lowercase();
1143 assert!(headers.starts_with("post /i/v0/e/ http/1.1\r\n"));
1144 let len: usize = headers
1145 .lines()
1146 .find_map(|line| line.strip_prefix("content-length: "))
1147 .unwrap()
1148 .parse()
1149 .unwrap();
1150 while buf.len() < header_end + len {
1151 let mut chunk = [0u8; 4096];
1152 let count = stream.read(&mut chunk).await.unwrap();
1153 assert!(count > 0);
1154 buf.extend_from_slice(&chunk[..count]);
1155 }
1156 bodies.push(buf[header_end..header_end + len].to_vec());
1157 stream
1158 .write_all(
1159 format!(
1160 "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1161 )
1162 .as_bytes(),
1163 )
1164 .await
1165 .unwrap();
1166 }
1167 bodies
1168 });
1169 let id = Uuid::new_v4();
1170 let state = state();
1171 let registry = crate::cron::CronRegistry::new();
1172 let zone = jiff::tz::TimeZone::UTC;
1173 let input = BootManifest::new("demo", ®istry, &zone, &[], &[]);
1174 let bytes =
1175 snapshot::<Jobs, State>(&state, &input, "test-token", id, "2026-11-18T18:00:00Z")
1176 .unwrap();
1177 tokio::time::timeout(Duration::from_secs(4), send(bytes.clone(), host))
1178 .await
1179 .unwrap();
1180 let received = server.await.unwrap();
1181 assert_eq!(received, [bytes.clone(), bytes]);
1182 let event: serde_json::Value = serde_json::from_slice(&received[0]).unwrap();
1183 assert_eq!(event["uuid"], id.to_string());
1184 assert_eq!(event["properties"]["event_id"], id.to_string());
1185 assert_eq!(event["api_key"], "test-token");
1186 assert_eq!(event["distinct_id"], "cja:demo");
1187 }
1188
1189 #[tokio::test]
1190 async fn sender_logs_only_transitions_and_never_follows_redirects() {
1191 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
1192 use tracing_subscriber::prelude::*;
1193 for (statuses, retries, recovered, rejected) in [
1194 (vec![503, 503, 200], 1, 1, 0),
1195 (vec![503, 0, 200], 2, 1, 0),
1196 (vec![503, 400], 1, 0, 1),
1197 (vec![400], 0, 0, 1),
1198 (vec![302], 0, 0, 1),
1199 ] {
1200 let log = EventLog(std::sync::Arc::default());
1201 let _guard =
1202 tracing::subscriber::set_default(tracing_subscriber::registry().with(log.clone()));
1203 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1204 let host = format!("http://{}", listener.local_addr().unwrap());
1205 let destination = host.clone();
1206 let expected = statuses.len();
1207 let server = tokio::spawn(async move {
1208 for code in statuses {
1209 let (mut stream, _) = listener.accept().await.unwrap();
1210 let mut request = [0u8; 4096];
1211 let n = stream.read(&mut request).await.unwrap();
1212 assert!(request[..n].starts_with(b"POST /i/v0/e/ HTTP/1.1"));
1213 if code == 0 {
1214 continue;
1215 }
1216 let response = format!(
1217 "HTTP/1.1 {code} test\r\nLocation: {destination}/elsewhere\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1218 );
1219 stream.write_all(response.as_bytes()).await.unwrap();
1220 }
1221 tokio::time::timeout(Duration::from_millis(200), listener.accept())
1222 .await
1223 .is_err()
1224 });
1225 tokio::time::timeout(Duration::from_secs(6), send(b"{}".to_vec(), host))
1226 .await
1227 .unwrap();
1228 assert!(
1229 server.await.unwrap(),
1230 "unexpected request after {expected} expected attempts"
1231 );
1232 assert_eq!(count_log(&log, "manifest capture retrying"), retries);
1233 assert_eq!(count_log(&log, "manifest capture recovered"), recovered);
1234 assert_eq!(count_log(&log, "manifest capture rejected"), rejected);
1235 }
1236 }
1237
1238 #[tokio::test]
1239 async fn permanent_capture_rejections_stop() {
1240 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
1241 for status in ["400 Bad Request", "413 Payload Too Large"] {
1242 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1243 let host = format!("http://{}", listener.local_addr().unwrap());
1244 let server = tokio::spawn(async move {
1245 let (mut stream, _) = listener.accept().await.unwrap();
1246 let mut bytes = [0u8; 4096];
1247 let n = stream.read(&mut bytes).await.unwrap();
1248 assert!(bytes[..n].starts_with(b"POST /i/v0/e/ HTTP/1.1"));
1249 stream
1250 .write_all(
1251 format!(
1252 "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1253 )
1254 .as_bytes(),
1255 )
1256 .await
1257 .unwrap();
1258 tokio::time::timeout(Duration::from_millis(1200), listener.accept())
1259 .await
1260 .is_err()
1261 });
1262 tokio::time::timeout(Duration::from_secs(2), send(b"{}".to_vec(), host))
1263 .await
1264 .unwrap();
1265 assert!(server.await.unwrap(), "{status} was retried");
1266 }
1267 }
1268
1269 #[tokio::test]
1270 async fn retry_after_delays_second_capture_attempt() {
1271 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
1272 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1273 let host = format!("http://{}", listener.local_addr().unwrap());
1274 let server = tokio::spawn(async move {
1275 let mut attempts = Vec::new();
1276 for response in [
1277 "HTTP/1.1 429 Too Many Requests\r\nRetry-After: 2\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
1278 "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
1279 ] {
1280 let (mut stream, _) = listener.accept().await.unwrap();
1281 attempts.push(tokio::time::Instant::now());
1282 let mut request = [0; 4096];
1283 let count = stream.read(&mut request).await.unwrap();
1284 assert!(request[..count].starts_with(b"POST /i/v0/e/ HTTP/1.1"));
1285 stream.write_all(response.as_bytes()).await.unwrap();
1286 }
1287 attempts
1288 });
1289 tokio::time::timeout(Duration::from_secs(4), send(b"{}".to_vec(), host))
1290 .await
1291 .unwrap();
1292 let attempts = server.await.unwrap();
1293 assert!(attempts[1].duration_since(attempts[0]) >= Duration::from_secs(2));
1294 }
1295
1296 #[tokio::test(start_paused = true)]
1297 async fn retry_queue_expires_after_twenty_four_hours() {
1298 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
1299 use tracing_subscriber::prelude::*;
1300 let log = EventLog(std::sync::Arc::default());
1301 let _guard =
1302 tracing::subscriber::set_default(tracing_subscriber::registry().with(log.clone()));
1303 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1304 let host = format!("http://{}", listener.local_addr().unwrap());
1305 let attempts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1306 let seen = attempts.clone();
1307 let server = tokio::spawn(async move {
1308 loop {
1309 let (mut stream, _) = listener.accept().await.unwrap();
1310 let mut bytes = [0u8; 4096];
1311 let count = stream.read(&mut bytes).await.unwrap();
1312 assert!(bytes[..count].starts_with(b"POST /i/v0/e/ HTTP/1.1"));
1313 seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1314 stream.write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await.unwrap();
1315 }
1316 });
1317 let sender = tokio::spawn(send(b"{}".to_vec(), host));
1318 for _ in 0..10 {
1319 if attempts.load(std::sync::atomic::Ordering::SeqCst) >= 2 {
1320 break;
1321 }
1322 tokio::time::advance(Duration::from_secs(1)).await;
1323 }
1324 assert!(
1325 attempts.load(std::sync::atomic::Ordering::SeqCst) > 1,
1326 "sender did not retry before expiry"
1327 );
1328 tokio::time::advance(Duration::from_hours(24)).await;
1329 sender.await.unwrap();
1330 assert_eq!(
1331 count_log(&log, "manifest capture expired after 24 hours"),
1332 1
1333 );
1334 let at_expiry = attempts.load(std::sync::atomic::Ordering::SeqCst);
1335 tokio::time::advance(Duration::from_secs(300)).await;
1336 assert_eq!(
1337 attempts.load(std::sync::atomic::Ordering::SeqCst),
1338 at_expiry,
1339 "capture retried after queue expiry"
1340 );
1341 server.abort();
1342 }
1343
1344 #[test]
1345 fn unreachable_capture_does_not_delay_boot_over_one_second() {
1346 use std::{
1347 process::{Command, Stdio},
1348 time::Instant,
1349 };
1350 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1351 let stalled = format!("http://{}", listener.local_addr().unwrap());
1352 let _server = std::thread::spawn(move || {
1353 if let Ok((stream, _)) = listener.accept() {
1354 std::thread::sleep(Duration::from_secs(3));
1355 drop(stream);
1356 }
1357 });
1358 for (host, token) in [
1359 ("http://127.0.0.1:1".to_owned(), false),
1360 ("http://127.0.0.1:1".to_owned(), true),
1361 (stalled, true),
1362 ] {
1363 let start = Instant::now();
1364 let mut command = Command::new(std::env::current_exe().unwrap());
1365 crate::testing::scrub_telemetry_env(&mut command);
1366 command
1367 .args([
1368 "--exact",
1369 "posthog_manifest::tests::child_boot_marker",
1370 "--nocapture",
1371 ])
1372 .env("CJA_MANIFEST_CHILD", "1")
1373 .env("POSTHOG_HOST", &host)
1374 .stdout(Stdio::piped())
1375 .stderr(Stdio::piped());
1376 if token {
1377 command.env("POSTHOG_PROJECT_TOKEN", "test-token");
1378 } else {
1379 command.env_remove("POSTHOG_PROJECT_TOKEN");
1380 }
1381 let mut child = command.spawn().unwrap();
1382 loop {
1383 if let Some(status) = child.try_wait().unwrap() {
1384 let output = child.wait_with_output().unwrap();
1385 assert!(
1386 status.success(),
1387 "child failed: {}",
1388 String::from_utf8_lossy(&output.stderr)
1389 );
1390 assert!(output.stdout.windows(10).any(|w| w == b"BOOT_READY"));
1391 assert!(
1392 start.elapsed() < Duration::from_secs(1),
1393 "boot latency exceeded one second for {host}"
1394 );
1395 break;
1396 }
1397 if start.elapsed() >= Duration::from_secs(1) {
1398 child.kill().unwrap();
1399 let output = child.wait_with_output().unwrap();
1400 panic!(
1401 "boot latency exceeded one second for {host}: {}",
1402 String::from_utf8_lossy(&output.stderr)
1403 );
1404 }
1405 std::thread::sleep(Duration::from_millis(10));
1406 }
1407 }
1408 }
1409}