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