1use serde::{Deserialize, Serialize};
2
3use crate::{
4 types::{
5 EndCause, Holder, JobClass, JobProfile, JobRun, Lease, LeaseKind, LeaseState, NoiseReport,
6 SessionKey, SessionUsage,
7 },
8 ui::Notice,
9};
10
11#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct HealthResponse {
15 pub version: String,
17 pub pid: u32,
19 pub uptime_secs: u64,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub config_error: Option<String>,
25}
26
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30#[non_exhaustive]
31pub enum ProfileSpec {
32 Class(JobClass),
34 Preset(String),
37 Custom(JobProfile),
39}
40
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct CanFitRequest {
44 pub profile: ProfileSpec,
46 pub kind: LeaseKind,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub label: Option<String>,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub cwd: Option<String>,
54}
55
56pub const REASON_BEYOND_LEASES: &str = "more than the machine can free";
59
60#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub struct Verdict {
64 pub fits: bool,
66 pub reasons: Vec<String>,
68 pub wait_estimate_secs: Option<u64>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub benchmark: Option<BenchmarkProgress>,
73}
74
75#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
77#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
78#[serde(tag = "phase", rename_all = "snake_case")]
79#[non_exhaustive]
80pub enum BenchmarkProgress {
81 Draining {
83 active_leases: u32,
85 },
86 Measuring {
88 measured_secs: u64,
90 needed_secs: u64,
92 cpu_avg_pct: f32,
94 gpu_avg_pct: f32,
96 },
97 Noisy {
100 cpu_avg_pct: f32,
102 gpu_avg_pct: f32,
104 cpu_limit_pct: f32,
106 gpu_limit_pct: f32,
108 grant_anyway_in_secs: u64,
110 },
111}
112
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115pub struct AcquireRequest {
116 pub holder: Holder,
118 pub profile: ProfileSpec,
120 pub kind: LeaseKind,
122 pub label: String,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub cwd: Option<String>,
127 pub wait_timeout_secs: u64,
129}
130
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
133pub struct AcquireResponse {
134 pub lease: Lease,
136 pub verdict: Verdict,
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
142pub struct WaitRequest {
143 pub wait_timeout_secs: u64,
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153pub struct LeaseOwner {
154 pub session: SessionKey,
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
160pub struct HeartbeatResponse {
161 pub state: LeaseState,
163 pub expires_at_ms: i64,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub end_cause: Option<EndCause>,
169}
170
171#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
173pub struct ReleaseResponse {
174 pub lease: Lease,
176 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub noise: Option<NoiseReport>,
180}
181
182#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
184#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
185pub struct KillResponse {
186 pub lease: Lease,
188 pub terminated: Vec<KilledProcess>,
190 pub failed: Vec<UnkilledProcess>,
192 pub spared: Vec<UnkilledProcess>,
194 pub untouched_reason: Option<String>,
197}
198
199#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
202pub struct KilledProcess {
203 pub pid: u32,
205 pub name: String,
207}
208
209#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub struct UnkilledProcess {
213 pub pid: u32,
215 pub name: String,
217 pub reason: String,
219}
220
221#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
224pub struct RemoveResponse {
225 pub lease: Lease,
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231pub struct BindRequest {
232 pub tool_use_id: String,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub command: Option<String>,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241pub struct NoticesResponse {
242 pub notices: Vec<Notice>,
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
248pub struct DeliveredResponse {
249 pub delivered: bool,
252}
253
254#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
256pub struct LeaseQuery {
257 pub session: Option<SessionKey>,
259 pub state: Option<LeaseState>,
261}
262
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
265pub struct LeasesResponse {
266 pub leases: Vec<Lease>,
268}
269
270#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
272pub struct SessionsResponse {
273 pub sessions: Vec<SessionUsage>,
275}
276
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280pub struct RegisterSessionRequest {
281 pub holder: Holder,
283}
284
285#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
287pub struct HistoryResponse {
288 pub jobs: Vec<JobSummary>,
290}
291
292#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
294#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
295pub struct JobSummary {
296 pub fingerprint: String,
298 pub command: String,
300 pub cwd: String,
302 pub runs: u32,
304 pub estimate_runs: u32,
306 pub last_ended_at_ms: i64,
308 pub learned: Option<JobProfile>,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315pub struct HistoryRunsQuery {
316 pub fingerprint: String,
318 pub limit: Option<u32>,
320}
321
322#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
324pub struct HistoryRunsResponse {
325 pub runs: Vec<JobRun>,
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332 use crate::test_support::{
333 assert_json_round_trip, sample_holder, sample_lease, sample_session_usage,
334 };
335
336 fn sample_verdict() -> Verdict {
337 Verdict {
338 fits: false,
339 reasons: vec!["RAM: 6144 MB requested, 4096 MB free after headroom".into()],
340 wait_estimate_secs: Some(90),
341 benchmark: None,
342 }
343 }
344
345 fn custom_profile() -> ProfileSpec {
346 ProfileSpec::Custom(JobProfile {
347 cores: 3.5,
348 ram_mb: 6144,
349 gpu_pct: 40.0,
350 vram_mb: 2048,
351 est_secs: 120,
352 })
353 }
354
355 #[test]
356 fn test_health_response_json_round_trip_preserves_every_field() {
357 assert_json_round_trip(&HealthResponse {
358 version: "0.1.0".into(),
359 pid: 4242,
360 uptime_secs: 3600,
361 config_error: Some("config.toml: invalid configuration: x".into()),
362 });
363 }
364
365 #[test]
366 fn test_can_fit_request_json_round_trip_preserves_both_profile_forms() {
367 assert_json_round_trip(&CanFitRequest {
368 profile: ProfileSpec::Class(JobClass::GpuHeavy),
369 kind: LeaseKind::Normal,
370 label: None,
371 cwd: None,
372 });
373 assert_json_round_trip(&CanFitRequest {
374 profile: custom_profile(),
375 kind: LeaseKind::BenchmarkExclusive,
376 label: Some("cargo bench".into()),
377 cwd: Some(r"E:\work\app".into()),
378 });
379 }
380
381 #[test]
382 fn test_can_fit_request_without_label_and_cwd_deserializes_as_none() {
383 let request: CanFitRequest =
384 serde_json::from_str(r#"{"profile":{"class":"light"},"kind":"normal"}"#).unwrap();
385 assert_eq!((request.label, request.cwd), (None, None));
386 }
387
388 #[test]
389 fn test_profile_spec_json_is_externally_tagged() {
390 let class = serde_json::to_value(ProfileSpec::Class(JobClass::CpuHeavy)).unwrap();
391 assert_eq!(class, serde_json::json!({ "class": "cpu_heavy" }));
392 let custom = serde_json::to_value(custom_profile()).unwrap();
393 assert_eq!(custom["custom"]["ram_mb"], 6144);
394 }
395
396 #[test]
397 fn test_verdict_json_round_trip_preserves_every_field() {
398 assert_json_round_trip(&sample_verdict());
399 assert_json_round_trip(&Verdict {
400 fits: true,
401 reasons: vec![],
402 wait_estimate_secs: None,
403 benchmark: None,
404 });
405 }
406
407 #[test]
408 fn test_verdict_benchmark_progress_round_trips_every_phase() {
409 let phases = [
410 BenchmarkProgress::Draining { active_leases: 2 },
411 BenchmarkProgress::Measuring {
412 measured_secs: 4,
413 needed_secs: 10,
414 cpu_avg_pct: 6.5,
415 gpu_avg_pct: 0.0,
416 },
417 BenchmarkProgress::Noisy {
418 cpu_avg_pct: 12.5,
419 gpu_avg_pct: 1.0,
420 cpu_limit_pct: 10.0,
421 gpu_limit_pct: 10.0,
422 grant_anyway_in_secs: 35,
423 },
424 ];
425 for phase in phases {
426 assert_json_round_trip(&Verdict {
427 benchmark: Some(phase),
428 ..sample_verdict()
429 });
430 }
431 let value = serde_json::to_value(phases[0]).unwrap();
432 assert_eq!(
433 value,
434 serde_json::json!({ "phase": "draining", "active_leases": 2 })
435 );
436 }
437
438 #[test]
439 fn test_verdict_without_benchmark_field_deserializes_as_none() {
440 let verdict: Verdict =
441 serde_json::from_str(r#"{"fits":true,"reasons":[],"wait_estimate_secs":null}"#)
442 .unwrap();
443 assert_eq!(verdict.benchmark, None);
444 }
445
446 #[test]
447 fn test_acquire_request_json_round_trip_preserves_every_field() {
448 assert_json_round_trip(&AcquireRequest {
449 holder: sample_holder(),
450 profile: custom_profile(),
451 kind: LeaseKind::Normal,
452 label: "cargo build --release".into(),
453 cwd: Some(r"E:\work\app".into()),
454 wait_timeout_secs: 30,
455 });
456 }
457
458 #[test]
459 fn test_acquire_response_json_round_trip_preserves_every_field() {
460 assert_json_round_trip(&AcquireResponse {
461 lease: sample_lease(),
462 verdict: sample_verdict(),
463 });
464 }
465
466 #[test]
467 fn test_lease_owner_json_round_trip_preserves_every_field() {
468 assert_json_round_trip(&LeaseOwner {
469 session: sample_holder().session,
470 });
471 }
472
473 #[test]
474 fn test_heartbeat_response_json_round_trip_preserves_every_field() {
475 assert_json_round_trip(&HeartbeatResponse {
476 state: LeaseState::Queued,
477 expires_at_ms: 1_793_000_060_000,
478 end_cause: None,
479 });
480 assert_json_round_trip(&HeartbeatResponse {
481 state: LeaseState::Expired,
482 expires_at_ms: 1_793_000_060_000,
483 end_cause: Some(EndCause::Killed),
484 });
485 }
486
487 #[test]
488 fn test_heartbeat_response_from_an_older_allotd_has_no_cause() {
489 let old: HeartbeatResponse =
490 serde_json::from_str(r#"{"state":"expired","expires_at_ms":5}"#).unwrap();
491 assert_eq!(old.end_cause, None);
492 }
493
494 #[test]
495 fn test_release_response_json_round_trip_preserves_every_field() {
496 assert_json_round_trip(&ReleaseResponse {
497 lease: sample_lease(),
498 noise: None,
499 });
500 assert_json_round_trip(&ReleaseResponse {
501 lease: sample_lease(),
502 noise: Some(NoiseReport {
503 avg_cpu_pct: 1.5,
504 peak_cpu_pct: 4.0,
505 avg_gpu_pct: 0.0,
506 peak_gpu_pct: 2.0,
507 quiet_at_start: true,
508 }),
509 });
510 }
511
512 #[test]
513 fn test_wait_request_json_round_trip_preserves_every_field() {
514 assert_json_round_trip(&WaitRequest {
515 wait_timeout_secs: 90,
516 });
517 }
518
519 #[test]
520 fn test_lease_query_json_round_trip_preserves_empty_and_full_filters() {
521 assert_json_round_trip(&LeaseQuery::default());
522 assert_json_round_trip(&LeaseQuery {
523 session: Some(sample_holder().session),
524 state: Some(LeaseState::Active),
525 });
526 }
527
528 #[test]
529 fn test_lease_query_missing_fields_deserialize_as_none() {
530 let query: LeaseQuery = serde_json::from_str("{}").unwrap();
531 assert_eq!(query, LeaseQuery::default());
532 }
533
534 #[test]
535 fn test_leases_response_json_round_trip_preserves_every_field() {
536 assert_json_round_trip(&LeasesResponse {
537 leases: vec![sample_lease()],
538 });
539 }
540
541 #[test]
542 fn test_sessions_response_json_round_trip_preserves_every_field() {
543 assert_json_round_trip(&SessionsResponse {
544 sessions: vec![sample_session_usage()],
545 });
546 }
547
548 #[test]
549 fn test_history_dtos_json_round_trip_preserve_every_field() {
550 let summary = JobSummary {
551 fingerprint: r"cargo build|e:\work\app".into(),
552 command: "cargo build".into(),
553 cwd: r"E:\work\app".into(),
554 runs: 5,
555 estimate_runs: 4,
556 last_ended_at_ms: 1_793_000_095_000,
557 learned: match custom_profile() {
558 ProfileSpec::Custom(profile) => Some(profile),
559 _ => None,
560 },
561 };
562 assert_json_round_trip(&HistoryResponse {
563 jobs: vec![
564 summary.clone(),
565 JobSummary {
566 learned: None,
567 ..summary
568 },
569 ],
570 });
571 assert_json_round_trip(&HistoryRunsQuery {
572 fingerprint: "cargo build|".into(),
573 limit: Some(10),
574 });
575 assert_json_round_trip(&HistoryRunsResponse { runs: Vec::new() });
576 }
577
578 #[test]
579 fn test_kill_and_remove_responses_json_round_trip_preserve_every_field() {
580 assert_json_round_trip(&KillResponse {
581 lease: sample_lease(),
582 terminated: vec![KilledProcess {
583 pid: 30_112,
584 name: "bash.exe".into(),
585 }],
586 failed: vec![UnkilledProcess {
587 pid: 30_140,
588 name: "cargo.exe".into(),
589 reason: "Access is denied.".into(),
590 }],
591 spared: vec![UnkilledProcess {
592 pid: 30_150,
593 name: "claude.exe".into(),
594 reason: "protected".into(),
595 }],
596 untouched_reason: None,
597 });
598 let untouched = KillResponse {
599 lease: sample_lease(),
600 terminated: Vec::new(),
601 failed: Vec::new(),
602 spared: Vec::new(),
603 untouched_reason: Some("the lease has no bound process tree".into()),
604 };
605 assert_json_round_trip(&untouched);
606 assert_json_round_trip(&RemoveResponse {
607 lease: sample_lease(),
608 });
609 }
610
611 #[test]
612 fn test_bind_request_without_command_omits_it() {
613 let request = BindRequest {
614 tool_use_id: "toolu_01AbC".into(),
615 command: None,
616 };
617 assert_json_round_trip(&request);
618 let value = serde_json::to_value(&request).unwrap();
619 assert_eq!(value, serde_json::json!({ "tool_use_id": "toolu_01AbC" }));
620 assert_json_round_trip(&BindRequest {
621 command: Some("cargo build".into()),
622 ..request
623 });
624 }
625
626 #[test]
627 fn test_notice_dtos_json_round_trip_preserve_every_field() {
628 assert_json_round_trip(&NoticesResponse {
629 notices: Vec::new(),
630 });
631 assert_json_round_trip(&DeliveredResponse { delivered: true });
632 }
633
634 #[test]
635 fn test_register_session_request_json_round_trip_preserves_every_field() {
636 assert_json_round_trip(&RegisterSessionRequest {
637 holder: sample_holder(),
638 });
639 }
640}