-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathhttp_api.rs
More file actions
1387 lines (1309 loc) · 51.8 KB
/
Copy pathhttp_api.rs
File metadata and controls
1387 lines (1309 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Read-only local HTTP API contract.
//!
//! This module is intentionally transport-free: the daemon can hand it a
//! method/path pair and serialize the returned JSON without duplicating Homeboy
//! command behavior. Long-running analysis endpoints enqueue daemon-owned jobs
//! so HTTP requests can return immediately while clients poll job events.
use base64::Engine;
use serde_json::{json, Value};
use uuid::Uuid;
use crate::api_jobs::{self, ActiveRunnerJobSummary, JobStore, RunnerJobProjectionCancelRequest};
use crate::error::{Error, Result};
use crate::observation::{
run_owner_pid, running_status_note, FindingListFilter, ObservationStore, RunListFilter,
RunRecord, RunStatus, MAX_RUN_PAGE_LIMIT, OWNERLESS_RUNNING_STALE_THRESHOLD_MINUTES,
};
use crate::{activity, component, git, paths};
mod analysis_job_runner;
mod sandbox_tools;
mod types;
pub use analysis_job_runner::{
AnalysisJobRunOutput, AnalysisJobRunner, UnsupportedAnalysisJobRunner,
};
pub use types::{
HttpApiRequest, HttpApiResponse, HttpEndpoint, HttpMethod, JobReadyRunKind, RunDetail,
RunSummary,
};
/// Route an HTTP method/path pair to a Homeboy API endpoint.
pub fn route(method: HttpMethod, path: &str) -> Result<HttpEndpoint> {
let segments = path_segments(path);
let refs: Vec<&str> = segments.iter().map(String::as_str).collect();
match (method, refs.as_slice()) {
(HttpMethod::Get, ["components"]) => Ok(HttpEndpoint::Components),
(HttpMethod::Get, ["components", id]) => Ok(HttpEndpoint::Component {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["components", id, "status"]) => Ok(HttpEndpoint::ComponentStatus {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["components", id, "changes"]) => Ok(HttpEndpoint::ComponentChanges {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["rigs"]) => Ok(HttpEndpoint::Rigs),
(HttpMethod::Get, ["rigs", id]) => Ok(HttpEndpoint::Rig {
id: (*id).to_string(),
}),
(HttpMethod::Post, ["rigs", id, "check"]) => Ok(HttpEndpoint::RigCheck {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["stacks"]) => Ok(HttpEndpoint::Stacks),
(HttpMethod::Get, ["stacks", id]) => Ok(HttpEndpoint::Stack {
id: (*id).to_string(),
}),
(HttpMethod::Post, ["stacks", id, "status"]) => Ok(HttpEndpoint::StackStatus {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["runs"]) => Ok(HttpEndpoint::Runs),
(HttpMethod::Get, ["runs", id]) => Ok(HttpEndpoint::Run {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["runs", id, "artifacts"]) => Ok(HttpEndpoint::RunArtifacts {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["runs", id, "artifacts", artifact_id, "content"]) => {
Ok(HttpEndpoint::RunArtifactContent {
id: (*id).to_string(),
artifact_id: (*artifact_id).to_string(),
})
}
(HttpMethod::Get, ["runs", id, "artifacts", artifact_id]) => {
Ok(HttpEndpoint::RunArtifactContent {
id: (*id).to_string(),
artifact_id: (*artifact_id).to_string(),
})
}
(HttpMethod::Get, ["runs", id, "findings"]) => Ok(HttpEndpoint::RunFindings {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["audit", "runs"]) => Ok(HttpEndpoint::AuditRuns),
(HttpMethod::Get, ["bench", "runs"]) => Ok(HttpEndpoint::BenchRuns),
(HttpMethod::Get, ["activity"]) => Ok(HttpEndpoint::Activity),
(HttpMethod::Get, ["activity", id]) => Ok(HttpEndpoint::ActivityItem {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["agent-task", "runs", id]) => Ok(HttpEndpoint::AgentTaskRun {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["jobs"]) => Ok(HttpEndpoint::Jobs),
(HttpMethod::Get, ["jobs", id]) => Ok(HttpEndpoint::Job {
id: (*id).to_string(),
}),
(HttpMethod::Get, ["jobs", id, "events"]) => Ok(HttpEndpoint::JobEvents {
id: (*id).to_string(),
}),
(HttpMethod::Post, ["jobs", id, "cancel"]) => Ok(HttpEndpoint::JobCancel {
id: (*id).to_string(),
}),
(HttpMethod::Post, ["jobs", id, "cancel-projection"]) => {
Ok(HttpEndpoint::JobProjectionCancel {
id: (*id).to_string(),
})
}
(HttpMethod::Post, ["audit"]) => Ok(HttpEndpoint::JobReadyRun {
kind: JobReadyRunKind::Audit,
}),
(HttpMethod::Post, ["lint"]) => Ok(HttpEndpoint::JobReadyRun {
kind: JobReadyRunKind::Lint,
}),
(HttpMethod::Post, ["test"]) => Ok(HttpEndpoint::JobReadyRun {
kind: JobReadyRunKind::Test,
}),
(HttpMethod::Post, ["bench"]) => Ok(HttpEndpoint::JobReadyRun {
kind: JobReadyRunKind::Bench,
}),
(HttpMethod::Get, ["tools"]) => Ok(HttpEndpoint::SandboxTools),
(HttpMethod::Get, ["tools", id]) => Ok(HttpEndpoint::SandboxTool {
id: (*id).to_string(),
}),
(HttpMethod::Post, ["tools", id, "run"]) => Ok(HttpEndpoint::SandboxToolRun {
id: (*id).to_string(),
}),
_ => Err(Error::validation_invalid_argument(
"path",
format!(
"No read-only HTTP API route for {} {}",
method_label(method),
path
),
Some(path.to_string()),
Some(vec![
"GET /components".to_string(),
"GET /components/:id/status".to_string(),
"GET /rigs".to_string(),
"POST /rigs/:id/check".to_string(),
"GET /stacks".to_string(),
"POST /stacks/:id/status".to_string(),
"GET /runs".to_string(),
"GET /runs/:id".to_string(),
"GET /runs/:id/artifacts".to_string(),
"GET /runs/:id/artifacts/:artifact_id".to_string(),
"GET /runs/:id/artifacts/:artifact_id/content".to_string(),
"GET /runs/:id/findings".to_string(),
"GET /audit/runs".to_string(),
"GET /bench/runs".to_string(),
"GET /activity".to_string(),
"GET /activity/:id".to_string(),
"GET /agent-task/runs/:id".to_string(),
"GET /jobs".to_string(),
"GET /jobs/:id".to_string(),
"GET /jobs/:id/events".to_string(),
"POST /jobs/:id/cancel".to_string(),
"GET /tools".to_string(),
"GET /tools/:id".to_string(),
"POST /tools/:id/run".to_string(),
]),
)),
}
}
/// Execute a routed read-only API request through existing Homeboy core code.
pub fn handle(request: HttpApiRequest) -> Result<HttpApiResponse> {
handle_with_jobs(request, &JobStore::default())
}
/// Execute a routed HTTP API request against the daemon-owned in-memory job store.
pub fn handle_with_jobs(request: HttpApiRequest, job_store: &JobStore) -> Result<HttpApiResponse> {
handle_with_jobs_and_runner(request, job_store, UnsupportedAnalysisJobRunner)
}
/// Execute a routed HTTP API request with an injected analysis job runner.
pub fn handle_with_jobs_and_runner<R>(
request: HttpApiRequest,
job_store: &JobStore,
analysis_runner: R,
) -> Result<HttpApiResponse>
where
R: AnalysisJobRunner,
{
let endpoint = route(request.method, &request.path)?;
let body = match &endpoint {
HttpEndpoint::Components => json!({
"command": "api.components.list",
"components": component::inventory()?,
}),
HttpEndpoint::Component { id } => json!({
"command": "api.components.show",
"component": component::resolve_effective(Some(id), None, None)?,
}),
HttpEndpoint::ComponentStatus { id } => json!({
"command": "api.components.status",
"status": git::status(Some(id))?,
}),
HttpEndpoint::ComponentChanges { id } => json!({
"command": "api.components.changes",
"changes": git::changes(Some(id), None, false)?,
}),
HttpEndpoint::Rigs => json!({
"command": "api.rigs.list",
"rigs": crate::rig_provider::rig_list_json()?,
}),
HttpEndpoint::Rig { id } => json!({
"command": "api.rigs.show",
"rig": crate::rig_provider::rig_show_json(id)?,
}),
HttpEndpoint::RigCheck { id } => {
json!({
"command": "api.rigs.check",
"report": crate::rig_provider::rig_check_json(id)?,
})
}
HttpEndpoint::Stacks => json!({
"command": "api.stacks.list",
"stacks": crate::stack_provider::stack_list_json()?,
}),
HttpEndpoint::Stack { id } => json!({
"command": "api.stacks.show",
"stack": crate::stack_provider::stack_show_json(id)?,
}),
HttpEndpoint::StackStatus { id } => {
json!({
"command": "api.stacks.status",
"report": crate::stack_provider::stack_status_json(id)?,
})
}
HttpEndpoint::Runs => json!({
"command": "api.runs.list",
"runs": list_runs(&request.path, None, job_store)?,
"active_runner_jobs": active_runner_jobs_for_path(&request.path, job_store),
}),
HttpEndpoint::Run { id } => json!({
"command": "api.runs.show",
"run": show_run(id, job_store)?,
}),
HttpEndpoint::RunArtifacts { id } => {
let store = ObservationStore::open_initialized()?;
require_run(&store, id)?;
json!({
"command": "api.runs.artifacts",
"run_id": id,
"artifacts": store.list_artifacts(id)?,
})
}
HttpEndpoint::RunArtifactContent { id, artifact_id } => artifact_content(id, artifact_id)?,
HttpEndpoint::RunFindings { id } => {
let store = ObservationStore::open_initialized()?;
require_run(&store, id)?;
json!({
"command": "api.runs.findings",
"run_id": id,
"findings": store.list_findings(FindingListFilter {
run_id: Some(id.clone()),
tool: query_value(&request.path, "tool"),
file: query_value(&request.path, "file"),
fingerprint: query_value(&request.path, "fingerprint"),
limit: query_value(&request.path, "limit")
.and_then(|value| value.parse::<i64>().ok())
.map(|limit| limit.clamp(1, 1000)),
})?,
})
}
HttpEndpoint::AuditRuns => json!({
"command": "api.audit.runs",
"runs": list_runs(&request.path, Some("audit"), job_store)?,
}),
HttpEndpoint::BenchRuns => json!({
"command": "api.bench.runs",
"runs": list_runs(&request.path, Some("bench"), job_store)?,
}),
HttpEndpoint::Activity => json!({
"command": "api.activity.list",
"activity": activity::activity_report(activity_scope_for_path(&request.path), activity_limit_for_path(&request.path))?,
}),
HttpEndpoint::ActivityItem { id } => json!({
"command": "api.activity.show",
"activity": activity::show_activity(id)?,
}),
HttpEndpoint::AgentTaskRun { id } => agent_task_run(id)?,
HttpEndpoint::Jobs => {
let active_runner_jobs = job_store.active_runner_jobs();
let stale_runner_jobs = job_store.stale_runner_jobs();
json!({
"command": "api.jobs.list",
"jobs": job_store.list(),
"active_runner_job_count": active_runner_jobs.len(),
"active_runner_jobs": active_runner_jobs,
"stale_runner_job_count": stale_runner_jobs.len(),
"stale_runner_jobs": stale_runner_jobs,
})
}
HttpEndpoint::Job { id } => json!({
"command": "api.jobs.show",
"job": job_store.get(parse_job_id(id)?)?,
}),
HttpEndpoint::JobEvents { id } => json!({
"command": "api.jobs.events",
"job_id": id,
"events": job_store.events(parse_job_id(id)?)?,
}),
HttpEndpoint::JobCancel { id } => {
let job_id = parse_job_id(id)?;
json!({
"command": "api.jobs.cancel",
"job": job_store.cancel(job_id, "cancel requested via HTTP API")?,
"events": job_store.events(job_id)?,
})
}
HttpEndpoint::JobProjectionCancel { id } => {
let job_id = parse_job_id(id)?;
let request: RunnerJobProjectionCancelRequest = serde_json::from_value(
request.body.unwrap_or_else(|| json!({})),
)
.map_err(|error| {
Error::validation_invalid_argument(
"body",
format!("invalid strict runner projection cancellation request: {error}"),
Some(id.clone()),
None,
)
})?;
json!({
"command": "api.jobs.cancel_projection",
"job": job_store.cancel_local_runner_projection(job_id, &request)?,
"events": job_store.events(job_id)?,
})
}
HttpEndpoint::JobReadyRun { kind } => {
enqueue_analysis_job(job_store, *kind, request.body, analysis_runner)?
}
HttpEndpoint::SandboxTools => json!({
"command": "api.tools.list",
"tools": sandbox_tools::all(),
}),
HttpEndpoint::SandboxTool { id } => json!({
"command": "api.tools.show",
"tool": sandbox_tools::get(id)?,
}),
HttpEndpoint::SandboxToolRun { id } => {
enqueue_sandbox_tool_job(job_store, id, request.body, analysis_runner)?
}
};
Ok(HttpApiResponse {
status: 200,
endpoint: endpoint.name().to_string(),
body,
})
}
/// Upper bound on an accepted agent-task run id.
///
/// The id arrives as a raw URL path segment and is handed to a durable-store
/// lookup. Every real id is a slug or a UUID-suffixed Cook attempt well under
/// this, so the bound costs nothing and keeps an adversarial multi-kilobyte
/// segment from reaching the record store — the same discipline
/// `daemon_endpoint_identity` applies to its nonce.
const MAX_AGENT_TASK_RUN_ID_LEN: usize = 256;
/// `GET /agent-task/runs/:id` — the durable agent-task run projection.
///
/// # This is a pure read, deliberately
///
/// The CLI's `agent-task status` is `agent_task_lifecycle::status()`, and it is
/// a *reconciling read that writes*: it rewrites the durable record on the way
/// out (admission status, candidate adoption, aggregate projection, terminal
/// model repair) and, for a record that is not controller-local, performs a
/// **live network probe of the runner**. Neither belongs behind this route:
///
/// 1. The daemon accept loop is serial — one connection is handled inline
/// before the next is accepted. A read whose latency is a remote round trip
/// stalls every other client of a long-lived shared process.
/// 2. This module is the read-only contract. `require_run` already refuses the
/// same reconciling facade for the same reason (#6768); a GET that mutates
/// would contradict a decision this file has already made once.
///
/// So this route resolves through the **activity agent-task provider**, whose
/// `probe_by_id` is documented as an indexed, non-mutating lookup precisely
/// because `activity` is a read model that must not reconcile (#10308). It
/// already understands Cook-id aliasing, so the id an operator was handed
/// resolves here too.
///
/// The cost is honesty about staleness, not silence about it: the response
/// carries `reconciles: false` and names the command that does reconcile.
///
/// # Bounding
///
/// Exactly one indexed probe. This is not `activity::show_activity`, which
/// falls back to a full-corpus scan of up to 1000 records across three stores
/// when the probes miss — unbounded work on a serial daemon, and wrong here
/// anyway, since a non-agent-task id has no business resolving on an
/// agent-task route.
///
/// # Redaction
///
/// The `ActivityItem` projection is a typed, field-by-field allowlist built by
/// the agent-task provider, matching the discipline the controller-job
/// `public_*` projections apply to cook job state. It carries ids, timestamps,
/// state, and evidence *references* — `command` and `cwd` are `None` for an
/// agent-task record, and no provider output, prompt, or error text is
/// reachable through it.
fn agent_task_run(run_id: &str) -> Result<Value> {
if run_id.len() > MAX_AGENT_TASK_RUN_ID_LEN {
return Err(Error::validation_invalid_argument(
"run_id",
format!("agent-task run id exceeds {MAX_AGENT_TASK_RUN_ID_LEN} bytes"),
None,
None,
));
}
// A failing probe is reported as a miss with a flag, never with its message.
// Error text from this subsystem can quote durable record contents, and the
// daemon copies `message`/`details` straight into the response body. The
// caller still learns that the lookup itself failed — that is what
// `probe_failed` is for — without being handed the text.
let probe = activity::agent_task_provider::probe_by_id(run_id);
let probe_failed = probe.is_err();
let Some(run) = probe.unwrap_or(None) else {
return Err(Error::validation_invalid_argument(
"run_id",
format!("agent-task run not found: {run_id}"),
Some(run_id.to_string()),
Some(vec![
if probe_failed {
"The agent-task record lookup failed; run `homeboy agent-task status <id>` for the reconciling read."
} else {
"Run `homeboy agent-task active` to list agent-task runs."
}
.to_string(),
]),
));
};
Ok(json!({
"command": "api.agent_task.runs.show",
// The resolved id, which is not always the requested one: a Cook id is
// an alias for its latest attempt record.
"run_id": run.id.clone(),
"requested_id": run_id,
"run": run,
"projection": {
"source": "agent-task.lifecycle",
// A GET that mutates is a decision, not an accident. This one does
// not, and says so rather than leaving a caller to assume freshness.
"reconciles": false,
"probe_failed": probe_failed,
"reconcile_with": "homeboy agent-task status",
},
// A run is not a job: the job supervises the run. Cook and fanout are
// both controller jobs, so watching and cancelling a detached run is
// already the generic controller-job surface — named here so an
// orchestrator does not have to rediscover it.
"job_surface": {
"list": "/jobs",
"show": "/jobs/:job_id",
"events": "/jobs/:job_id/events",
"cancel": "/controller/jobs/:job_id/cancel",
"note": "POST /jobs/:id/cancel refuses controller jobs; controller-owned work is cancelled through its driver so the driver can stop the work it owns.",
},
}))
}
fn activity_scope_for_path(path: &str) -> activity::ActivityScope {
if query_value(path, "all").is_some_and(|value| value == "1" || value == "true") {
activity::ActivityScope::All
} else {
activity::ActivityScope::ActiveRecent
}
}
fn activity_limit_for_path(path: &str) -> usize {
query_value(path, "limit")
.and_then(|value| value.parse::<usize>().ok())
.map(|limit| limit.clamp(1, 1000))
.unwrap_or(20)
}
fn enqueue_sandbox_tool_job(
job_store: &JobStore,
id: &str,
body: Option<Value>,
analysis_runner: impl AnalysisJobRunner,
) -> Result<Value> {
let tool = sandbox_tools::get(id)?;
let kind = sandbox_tools::kind(tool.id)?;
let mut response = enqueue_analysis_job(job_store, kind, body, analysis_runner)?;
if let Value::Object(ref mut fields) = response {
fields.insert("command".to_string(), json!("api.tools.run.enqueue"));
fields.insert(
"tool".to_string(),
serde_json::to_value(tool).unwrap_or(Value::Null),
);
}
Ok(response)
}
fn artifact_content(run_id: &str, artifact_id: &str) -> Result<Value> {
let store = ObservationStore::open_initialized()?;
require_run(&store, run_id)?;
crate::artifacts::index_remote_published_artifact_refs_for_run(&store, run_id)?;
let decoded_artifact_id = crate::execution_contract::decode_uri_component(artifact_id);
let Some(artifact) = store.get_artifact_for_run_token(run_id, &decoded_artifact_id)? else {
return artifact_store_content(run_id, artifact_id, &decoded_artifact_id);
};
if artifact.artifact_type != "file" {
if artifact.artifact_type == "remote_file"
|| crate::execution_contract::is_remote_runner_artifact_path(&artifact.path)
{
let download = crate::observation::runs_service::with_runner_evidence(|provider| {
provider.download_remote_artifact(&artifact.path, None)
})?;
let content = std::fs::read(&download.output_path).map_err(|err| {
Error::internal_io(
err.to_string(),
Some(format!(
"read downloaded remote artifact {}",
download.output_path.display()
)),
)
})?;
let filename = download
.output_path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(&artifact.id);
let size_bytes = download
.size_bytes
.or_else(|| i64::try_from(content.len()).ok());
return Ok(artifact_content_response(
run_id,
&artifact.id,
filename,
download.content_type.or_else(|| artifact.mime.clone()),
size_bytes,
download.sha256.or_else(|| artifact.sha256.clone()),
&content,
));
}
return Err(Error::validation_invalid_argument(
"artifact_id",
format!(
"artifact {} is {}, not a downloadable file",
artifact.id, artifact.artifact_type
),
Some(artifact.id),
None,
));
}
let path = std::path::PathBuf::from(&artifact.path);
let content = std::fs::read(&path).map_err(|err| {
Error::internal_io(
err.to_string(),
Some(format!("read recorded artifact {}", path.display())),
)
})?;
let filename = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(&artifact.id);
Ok(artifact_content_response(
run_id,
&artifact.id,
filename,
artifact.mime,
artifact.size_bytes,
artifact.sha256,
&content,
))
}
#[allow(clippy::too_many_arguments)]
fn artifact_content_response(
run_id: &str,
artifact_id: &str,
filename: &str,
mime: Option<String>,
size_bytes: Option<i64>,
sha256: Option<String>,
content: &[u8],
) -> Value {
json!({
"command": "api.runs.artifact.content",
"run_id": run_id,
"artifact_id": artifact_id,
"content_available": true,
"retrieval": inline_content_retrieval(),
"filename": filename,
"mime": mime,
"size_bytes": size_bytes,
"sha256": sha256,
"content_base64": base64::engine::general_purpose::STANDARD.encode(content),
})
}
fn artifact_store_content(
run_id: &str,
artifact_id: &str,
decoded_artifact_id: &str,
) -> Result<Value> {
let locator = crate::execution_contract::artifact_store_locator_from_runner_artifact_id(
decoded_artifact_id,
)
.ok_or_else(|| {
Error::validation_invalid_argument(
"artifact_id",
format!("artifact record not found: {artifact_id}"),
Some(artifact_id.to_string()),
None,
)
})?;
let path = safe_artifact_store_path(&locator)?;
let content = std::fs::read(&path).map_err(|err| {
Error::internal_io(
err.to_string(),
Some(format!("read artifact-store locator {}", path.display())),
)
})?;
let filename = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(artifact_id);
let size_bytes = i64::try_from(content.len()).ok();
let sha256 = crate::artifact_metadata::sha256_file(&path).ok();
Ok(json!({
"command": "api.runs.artifact.content",
"run_id": run_id,
"artifact_id": artifact_id,
"content_available": true,
"retrieval": inline_content_retrieval(),
"filename": filename,
"mime": crate::artifact_metadata::content_type_from_path(&path),
"size_bytes": size_bytes,
"sha256": sha256,
"content_base64": base64::engine::general_purpose::STANDARD.encode(content),
}))
}
fn inline_content_retrieval() -> Value {
json!({
"mode": "inline_base64",
"content_available": true,
"content_field": "content_base64",
"encoding": "base64",
})
}
fn safe_artifact_store_path(locator: &str) -> Result<std::path::PathBuf> {
let locator_path = std::path::PathBuf::from(locator);
if locator_path.is_absolute()
|| locator_path
.components()
.any(|component| matches!(component, std::path::Component::ParentDir))
{
return Err(Error::validation_invalid_argument(
"artifact_id",
"artifact-store locator must stay under the artifact root",
Some(locator.to_string()),
None,
));
}
Ok(paths::artifact_root()?.join(locator_path))
}
fn path_segments(path: &str) -> Vec<String> {
path.split('?')
.next()
.unwrap_or(path)
.trim_matches('/')
.split('/')
.filter(|segment| !segment.is_empty())
.map(str::to_string)
.collect()
}
fn list_runs(
path: &str,
kind_override: Option<&str>,
job_store: &JobStore,
) -> Result<Vec<RunSummary>> {
let store = ObservationStore::open_initialized()?;
reconcile_stale_running_runs_for_read(&store)?;
let filter = RunListFilter {
kind: kind_override
.map(str::to_string)
.or_else(|| query_value(path, "kind")),
component_id: query_value(path, "component").or_else(|| query_value(path, "component_id")),
status: query_value(path, "status"),
rig_id: query_value(path, "rig").or_else(|| query_value(path, "rig_id")),
limit: query_value(path, "limit")
.and_then(|value| value.parse::<i64>().ok())
.map(|limit| limit.clamp(1, MAX_RUN_PAGE_LIMIT)),
// A page ceiling with no way past it is a hard wall; an offset makes
// the rows beyond it reachable (#11177).
offset: query_value(path, "offset")
.and_then(|value| value.parse::<i64>().ok())
.map(|offset| offset.max(0)),
..RunListFilter::default()
};
let mut runs: Vec<RunSummary> = store
.list_runs(filter)?
.into_iter()
.map(run_summary)
.collect();
if kind_override.is_none() {
runs.extend(
active_runner_jobs_for_path(path, job_store)
.into_iter()
.filter_map(active_runner_job_run_summary_if_durable),
);
}
Ok(runs)
}
fn active_runner_jobs_for_path(path: &str, job_store: &JobStore) -> Vec<ActiveRunnerJobSummary> {
let status = query_value(path, "status");
let limit = query_value(path, "limit")
.and_then(|value| value.parse::<usize>().ok())
.map(|limit| limit.clamp(1, 1000));
let mut jobs: Vec<_> = job_store
.active_runner_jobs()
.into_iter()
.filter(|job| match status.as_deref() {
Some(status) => status == job.status.run_status_label(),
None => true,
})
.collect();
if let Some(limit) = limit {
jobs.truncate(limit);
}
jobs
}
fn active_runner_job_run_summary_if_durable(job: ActiveRunnerJobSummary) -> Option<RunSummary> {
let summary = api_jobs::active_runner_job_run_summary_if_durable(job)?;
Some(RunSummary {
id: summary.id,
kind: summary.kind,
status: summary.status,
started_at: summary.started_at,
finished_at: None,
component_id: None,
rig_id: None,
git_sha: None,
command: Some(summary.command),
cwd: summary.cwd,
status_note: Some(summary.status_note),
})
}
fn show_run(run_id: &str, job_store: &JobStore) -> Result<RunDetail> {
let store = ObservationStore::open_initialized()?;
reconcile_stale_running_runs_for_read(&store)?;
if let Some(run) = store.get_run(run_id)? {
if let Some(job) = active_runner_job_for_durable_run(job_store, run_id) {
if run.status != RunStatus::Running.as_str() || run_claims_other_runner_job(&run, &job)
{
return Ok(active_runner_job_run_detail(run_id, &job, Some(&run)));
}
}
return Ok(RunDetail {
summary: run_summary(run.clone()),
homeboy_version: run.homeboy_version,
metadata: run.metadata_json,
artifacts: store.list_artifacts(run_id)?,
});
}
if let Some(job) = active_runner_job_for_durable_run(job_store, run_id) {
return Ok(active_runner_job_run_detail(run_id, &job, None));
}
let run = require_run(&store, run_id)?;
Ok(RunDetail {
summary: run_summary(run.clone()),
homeboy_version: run.homeboy_version,
metadata: run.metadata_json,
artifacts: store.list_artifacts(run_id)?,
})
}
fn active_runner_job_for_durable_run(
job_store: &JobStore,
run_id: &str,
) -> Option<ActiveRunnerJobSummary> {
job_store
.active_runner_jobs()
.into_iter()
.find(|job| job.durable_run_id.as_deref() == Some(run_id))
}
fn active_runner_job_run_detail(
run_id: &str,
job: &ActiveRunnerJobSummary,
persisted_run: Option<&RunRecord>,
) -> RunDetail {
let projection_state = match persisted_run {
None => "missing_durable_run_record",
Some(run) if run.status != RunStatus::Running.as_str() => "stale_durable_run_record",
Some(_) => "foreign_durable_run_record",
};
let summary = active_runner_job_run_summary_if_durable(job.clone())
.expect("active runner job is selected by its durable run id");
RunDetail {
summary,
homeboy_version: None,
metadata: json!({
"runner_job_projection": {
"state": projection_state,
"durable_run_id": run_id,
"runner_id": job.runner_id,
"job_id": job.job_id,
"message": "The daemon job is active and authoritative; durable-run hydration is unavailable for this projection.",
}
}),
artifacts: Vec::new(),
}
}
fn run_claims_other_runner_job(run: &RunRecord, job: &ActiveRunnerJobSummary) -> bool {
["/lab/remote_job/id", "/lab/remote_job_id"]
.into_iter()
.filter_map(|pointer| run.metadata_json.pointer(pointer).and_then(Value::as_str))
.any(|recorded_job_id| recorded_job_id != job.job_id)
}
fn reconcile_stale_running_runs_for_read(store: &ObservationStore) -> Result<()> {
for run in store.list_runs(RunListFilter {
status: Some(RunStatus::Running.as_str().to_string()),
limit: Some(1000),
..RunListFilter::default()
})? {
let Some(reason) = api_stale_running_reason(&run) else {
continue;
};
let metadata = api_reconcile_metadata(&run, reason);
store.finish_run(&run.id, RunStatus::Stale, Some(metadata))?;
}
Ok(())
}
fn api_stale_running_reason(run: &RunRecord) -> Option<&'static str> {
if let Some(owner_pid) = run_owner_pid(run) {
return (!crate::process::pid_is_running(owner_pid)).then_some("owner_process_not_running");
}
api_ownerless_running_is_stale(run).then_some("owner_metadata_missing")
}
fn api_ownerless_running_is_stale(run: &RunRecord) -> bool {
chrono::DateTime::parse_from_rfc3339(&run.started_at)
.map(|started_at| {
chrono::Utc::now()
.signed_duration_since(started_at.with_timezone(&chrono::Utc))
.num_minutes()
>= OWNERLESS_RUNNING_STALE_THRESHOLD_MINUTES
})
.unwrap_or(false)
}
fn api_reconcile_metadata(run: &RunRecord, reason: &str) -> Value {
let mut metadata = run.metadata_json.clone();
let marker = json!({
"status": RunStatus::Stale.as_str(),
"reason": reason,
"owner_pid": run_owner_pid(run).map(|pid| Value::from(pid as u64)).unwrap_or(Value::Null),
"reconciled_at": chrono::Utc::now().to_rfc3339(),
"source": "http_api_read_reconcile",
});
if let Some(object) = metadata.as_object_mut() {
object.insert("homeboy_reconciled".to_string(), marker);
return metadata;
}
json!({
"homeboy_reconciled": marker,
"homeboy_original_metadata": metadata,
})
}
/// Exact-id run lookup for HTTP handlers.
///
/// Intentionally **not** routed through
/// [`crate::observation::runs_service::require_run`] (#6768). The facade adds
/// durable label aliasing plus a connected-runner probe that mirrors remote run
/// records into the local store — a network round trip and a write. This module
/// is a read-only, transport-free contract whose handlers must stay latency
/// bounded, so it resolves record ids only. Every other run read path (CLI
/// `runs`, `fuzz`, dossier, evidence) uses the facade.
fn require_run(store: &ObservationStore, run_id: &str) -> Result<RunRecord> {
store.get_run(run_id)?.ok_or_else(|| {
Error::validation_invalid_argument(
"run_id",
format!("run record not found: {run_id}"),
Some(run_id.to_string()),
None,
)
})
}
fn parse_job_id(job_id: &str) -> Result<Uuid> {
Uuid::parse_str(job_id).map_err(|error| {
Error::validation_invalid_argument(
"job_id",
format!("invalid job id: {job_id}: {error}"),
Some(job_id.to_string()),
None,
)
})
}
fn enqueue_analysis_job(
job_store: &JobStore,
kind: JobReadyRunKind,
body: Option<Value>,
analysis_runner: impl AnalysisJobRunner,
) -> Result<Value> {
let request = AnalysisJobRequest::from_body(kind, body)?;
let argv = request.argv();
let operation = format!("analysis.{}", job_ready_slug(kind));
let request_summary = request.summary();
let command_label = request.command_label();
let runner = job_store.run_background(operation, move |job| {
job.progress(json!({
"phase": "started",
"command": command_label,
"job_id": job.job_id(),
}))?;
let output = analysis_runner.run_analysis_job(argv)?;
job.progress(json!({
"phase": "finished",
"exit_code": output.exit_code,
}))?;
Ok(json!({
"command": command_label,
"exit_code": output.exit_code,
"output": output.output,
}))
});
let job = job_store.get(runner.job_id)?;
Ok(json!({
"command": format!("api.{}.enqueue", job_ready_slug(kind)),
"job": job,
"poll": {
"job": format!("/jobs/{}", runner.job_id),
"events": format!("/jobs/{}/events", runner.job_id),
},
"request": request_summary,
}))
}
#[derive(Debug, Clone)]
struct AnalysisJobRequest {
kind: JobReadyRunKind,
args: Vec<String>,
summary: Value,
}
impl AnalysisJobRequest {
fn from_body(kind: JobReadyRunKind, body: Option<Value>) -> Result<Self> {
let mut parser = AnalysisBodyParser::new(body)?;
let mut args = vec![job_ready_slug(kind).to_string()];
match kind {
JobReadyRunKind::Audit => {
parser.push_optional_string("component", &mut args)?;
parser.push_optional_flag_value("path", "--path", &mut args)?;
parser.push_bool_flag("json_summary", "--json-summary", &mut args)?;
parser.push_bool_flag("conventions", "--conventions", &mut args)?;
parser.push_string_array("only", "--only", &mut args)?;
parser.push_string_array("exclude", "--exclude", &mut args)?;
parser.push_optional_flag_value("changed_since", "--changed-since", &mut args)?;
parser.push_bool_flag("fixability", "--fixability", &mut args)?;
}
JobReadyRunKind::Lint => {
parser.push_optional_string("component", &mut args)?;
parser.push_optional_flag_value("path", "--path", &mut args)?;
parser.push_bool_flag("json_summary", "--json-summary", &mut args)?;
parser.push_bool_flag("summary", "--summary", &mut args)?;
parser.push_optional_flag_value("file", "--file", &mut args)?;
parser.push_optional_flag_value("glob", "--glob", &mut args)?;
parser.push_bool_flag("changed_only", "--changed-only", &mut args)?;
parser.push_optional_flag_value("changed_since", "--changed-since", &mut args)?;
parser.push_bool_flag("errors_only", "--errors-only", &mut args)?;
parser.push_optional_flag_value("sniffs", "--sniffs", &mut args)?;
parser.push_optional_flag_value("exclude_sniffs", "--exclude-sniffs", &mut args)?;
parser.push_optional_flag_value("category", "--category", &mut args)?;
parser.reject_present("fix", "POST /lint jobs do not expose mutating --fix")?;
}
JobReadyRunKind::Test => {
parser.push_optional_string("component", &mut args)?;
parser.push_optional_flag_value("path", "--path", &mut args)?;
parser.push_bool_flag("json_summary", "--json-summary", &mut args)?;