mecha10-cli 4.2.15

Mecha10 CLI tool
Documentation
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
//! HTTP client for mecha10-api's build-jobs endpoint (LAB-5443), used by the CLI's
//! remote/dashboard build flow (LAB-5442, part of "build via mecha10 dashboard", LAB-2153).
//!
//! Covers the GitHub-based remote build path (LAB-5450, mecha10-api's
//! `integrations::github_app` module and `robot::build_jobs::handlers::
//! create_build_job_from_github`): `POST /api/github/install/start` (mint the GitHub App
//! install URL), `GET /api/github/connections` (check whether the caller already has a
//! connected repo), `POST /api/robots/{robot_id}/build-jobs/from-github` (dispatch a build
//! that clones the connected repo server-side - a JSON body, no multipart upload at all, since
//! there's no zip), and a `GET /api/robots/{robot_id}/build-jobs/{id}` poll endpoint. Auth is
//! the caller's own long-lived `mecha_...` API key as a bearer token on every call - no new
//! auth mechanism (`jobs::auth::AuthUser`'s `FromRequestParts` impl only looks at the
//! `Authorization: Bearer <token>` header, same as every other authenticated CLI command).

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

/// Build-job lifecycle state - matches mecha10-api's `BuildJobState` wire format exactly
/// (`#[serde(rename_all = "snake_case")]`, no `cancelled` variant - a build job, like an L6
/// dataset build, has no cancel route).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BuildJobState {
    Pending,
    Running,
    Succeeded,
    Failed,
}

/// `POST /api/robots/{robot_id}/build-jobs[/from-github]` response body - matches
/// mecha10-api's `CreateBuildJobResponse`. Only `id` is modeled: it's the only field the
/// caller reads (to report the created job's id and to start polling it); `state`/`message`
/// describe the freshly-created job's initial status, which the poll loop immediately
/// re-fetches anyway.
#[derive(Debug, Clone, Deserialize)]
pub struct CreateBuildJobResponse {
    pub id: String,
}

/// `GET /api/robots/{robot_id}/build-jobs/{id}` response body - matches mecha10-api's
/// `BuildJob`/`GetBuildJobResponse` shape. Only the fields the CLI's poll loop surfaces are
/// modeled here; `id`/`binary_id`/timestamps/etc. aren't needed for v0 (the poll loop already
/// has the job id from `create_build_job_from_github`, and just reports success/failure with
/// a progress line, not the resulting binary's registry id).
#[derive(Debug, Clone, Deserialize)]
pub struct BuildJob {
    pub state: BuildJobState,
    #[serde(default)]
    pub error_message: Option<String>,
    #[serde(default)]
    pub progress_message: Option<String>,
}

/// A connected GitHub App installation (`GET /api/github/connections` row) - matches
/// mecha10-api's `integrations::github_app::types::GithubConnectionSummary`. Only the fields
/// the CLI actually reads are modeled; `created_at`/`updated_at` aren't needed to decide
/// whether a usable connection exists or to dispatch a build from one.
#[derive(Debug, Clone, Deserialize)]
pub struct GithubConnection {
    pub id: String,
    /// `None` until a repo is selected (via the dashboard's `PUT /api/github/connections/{id}`
    /// - the CLI doesn't drive that step itself) - a connection with no repo selected isn't
    ///   usable for `create_build_job_from_github` yet.
    #[serde(default)]
    pub repo_full_name: Option<String>,
}

/// `GET /api/github/connections` response body - matches mecha10-api's
/// `ListGithubConnectionsResponse`.
#[derive(Debug, Clone, Deserialize)]
pub struct ListGithubConnectionsResponse {
    pub connections: Vec<GithubConnection>,
}

/// `POST /api/github/install/start` response body - matches mecha10-api's
/// `StartInstallResponse`. Just GitHub's own installation URL (with a signed `state` already
/// attached server-side) for the CLI to print for the user to open in a browser.
#[derive(Debug, Clone, Deserialize)]
pub struct StartInstallResponse {
    pub install_url: String,
}

/// Inputs to [`report_build_job_status`] - the call the build-worker itself makes (LAB-5440),
/// as opposed to every other function in this module which is called by the CLI running on a
/// developer's own machine. Auth is therefore a service token (mecha10-api's
/// `AppState::control_plane_service_key`, handed to the worker via the Kestra `token` input/
/// `MECHA10_API_KEY` env var), not the caller's own long-lived `mecha_...` API key.
pub struct ReportBuildJobStatusParams<'a> {
    pub control_plane_url: &'a str,
    pub robot_id: &'a str,
    pub job_id: &'a str,
    pub service_token: &'a str,
    pub state: BuildJobState,
    pub binary_id: Option<&'a str>,
    pub error_message: Option<&'a str>,
}

/// `POST /api/robots/{robot_id}/build-jobs/{job_id}/status`: the build-worker's own report of
/// its terminal outcome (LAB-5440/5443) - this is what actually moves a build-job row out of
/// `pending`/`running` into `succeeded`/`failed`, since nothing else observes the dispatched
/// Kestra container's exit. Bearer-auths with the control-plane service token, not a user's
/// API key - see [`ReportBuildJobStatusParams`].
pub async fn report_build_job_status(params: ReportBuildJobStatusParams<'_>) -> Result<()> {
    let ReportBuildJobStatusParams {
        control_plane_url,
        robot_id,
        job_id,
        service_token,
        state,
        binary_id,
        error_message,
    } = params;

    let mut body = serde_json::json!({ "state": state });
    if let Some(binary_id) = binary_id {
        body["binary_id"] = serde_json::Value::String(binary_id.to_string());
    }
    if let Some(error_message) = error_message {
        body["error_message"] = serde_json::Value::String(error_message.to_string());
    }

    let url = format!("{}/{}/status", build_jobs_url(control_plane_url, robot_id), job_id);

    let client = reqwest::Client::new();
    let response = client
        .post(url)
        .bearer_auth(service_token)
        .json(&body)
        .send()
        .await
        .context("Failed to send build-job status report")?;

    let status = response.status();
    let body = response
        .text()
        .await
        .context("Failed to read build-job status report response")?;

    if !status.is_success() {
        anyhow::bail!("Failed to report build job status (status {status}): {body}");
    }

    Ok(())
}

/// Inputs to [`create_build_job_from_github`] - there is nothing to upload (the dispatched
/// build container clones `connection_id`'s repo itself), so this just carries the build's
/// sidecar fields plus `connection_id` identifying which connected GitHub repo to build from.
pub struct CreateBuildJobFromGithubParams<'a> {
    pub control_plane_url: &'a str,
    pub robot_id: &'a str,
    pub connection_id: &'a str,
    pub target_platform: &'a str,
    pub target_arch: &'a str,
    pub config: Option<&'a str>,
    pub api_key: &'a str,
}

/// Shared URL builder for both the create and poll endpoints - one place that knows the
/// route shape (`/api/robots/{robot_id}/build-jobs[...]`), matching mecha10-api's
/// `robot::build_jobs::router()`.
fn build_jobs_url(control_plane_url: &str, robot_id: &str) -> String {
    format!(
        "{}/api/robots/{}/build-jobs",
        control_plane_url.trim_end_matches('/'),
        robot_id
    )
}

/// `GET /api/github/connections` URL - matches mecha10-api's `integrations::github_app`
/// router.
fn github_connections_url(control_plane_url: &str) -> String {
    format!("{}/api/github/connections", control_plane_url.trim_end_matches('/'))
}

/// `POST /api/github/install/start` URL.
fn github_install_start_url(control_plane_url: &str) -> String {
    format!("{}/api/github/install/start", control_plane_url.trim_end_matches('/'))
}

/// `GET /api/robots/{robot_id}/build-jobs/{id}`: fetch the current state of a build job -
/// the CLI's poll loop calls this on an interval until `state` is terminal.
pub async fn get_build_job(control_plane_url: &str, robot_id: &str, id: &str, api_key: &str) -> Result<BuildJob> {
    let url = format!("{}/{}", build_jobs_url(control_plane_url, robot_id), id);

    let client = reqwest::Client::new();
    let response = client
        .get(url)
        .bearer_auth(api_key)
        .send()
        .await
        .context("Failed to send build-job poll request")?;

    let status = response.status();
    let body = response
        .text()
        .await
        .context("Failed to read build-job poll response")?;

    if !status.is_success() {
        anyhow::bail!("Failed to poll build job (status {status}): {body}");
    }

    serde_json::from_str(&body).context("Failed to parse build-job poll response")
}

/// `GET /api/github/connections`: every GitHub App installation the caller has connected -
/// used by the remote/dashboard build flow to decide whether a build can go through the
/// GitHub-clone path (LAB-5450) without ever constructing or uploading a zip.
pub async fn list_github_connections(control_plane_url: &str, api_key: &str) -> Result<Vec<GithubConnection>> {
    let client = reqwest::Client::new();
    let response = client
        .get(github_connections_url(control_plane_url))
        .bearer_auth(api_key)
        .send()
        .await
        .context("Failed to send GitHub connections request")?;

    let status = response.status();
    let body = response
        .text()
        .await
        .context("Failed to read GitHub connections response")?;

    if !status.is_success() {
        anyhow::bail!("Failed to list GitHub connections (status {status}): {body}");
    }

    let parsed: ListGithubConnectionsResponse =
        serde_json::from_str(&body).context("Failed to parse GitHub connections response")?;
    Ok(parsed.connections)
}

/// `POST /api/github/install/start`: mint the GitHub App installation URL the CLI prints for
/// the user to open in a browser to connect a repo.
pub async fn start_github_install(control_plane_url: &str, api_key: &str) -> Result<StartInstallResponse> {
    let client = reqwest::Client::new();
    let response = client
        .post(github_install_start_url(control_plane_url))
        .bearer_auth(api_key)
        .send()
        .await
        .context("Failed to send GitHub install start request")?;

    let status = response.status();
    let body = response
        .text()
        .await
        .context("Failed to read GitHub install start response")?;

    if !status.is_success() {
        anyhow::bail!("Failed to start GitHub App install (status {status}): {body}");
    }

    serde_json::from_str(&body).context("Failed to parse GitHub install start response")
}

/// `POST /api/robots/{robot_id}/build-jobs/from-github`: dispatch a build job that clones
/// `connection_id`'s connected repo server-side (LAB-5450) - a JSON body, not multipart, since
/// there is no file part at all. Returns `CreateBuildJobResponse` and is followed by the same
/// poll loop/endpoint as every other build job.
pub async fn create_build_job_from_github(
    params: CreateBuildJobFromGithubParams<'_>,
) -> Result<CreateBuildJobResponse> {
    let CreateBuildJobFromGithubParams {
        control_plane_url,
        robot_id,
        connection_id,
        target_platform,
        target_arch,
        config,
        api_key,
    } = params;

    let mut body = serde_json::json!({
        "connection_id": connection_id,
        "target_platform": target_platform,
        "target_arch": target_arch,
    });
    if let Some(config) = config {
        body["config"] = serde_json::Value::String(config.to_string());
    }

    let client = reqwest::Client::new();
    let response = client
        .post(format!("{}/from-github", build_jobs_url(control_plane_url, robot_id)))
        .bearer_auth(api_key)
        .json(&body)
        .send()
        .await
        .context("Failed to send build-job-from-GitHub create request")?;

    let status = response.status();
    let body = response
        .text()
        .await
        .context("Failed to read build-job-from-GitHub create response")?;

    if !status.is_success() {
        anyhow::bail!("Failed to create build job from GitHub (status {status}): {body}");
    }

    serde_json::from_str(&body).context("Failed to parse build-job-from-GitHub create response")
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read, Write};

    #[test]
    fn build_job_state_serializes_to_snake_case_matching_the_server_contract() {
        assert_eq!(serde_json::to_string(&BuildJobState::Pending).unwrap(), "\"pending\"");
        assert_eq!(serde_json::to_string(&BuildJobState::Running).unwrap(), "\"running\"");
        assert_eq!(
            serde_json::to_string(&BuildJobState::Succeeded).unwrap(),
            "\"succeeded\""
        );
        assert_eq!(serde_json::to_string(&BuildJobState::Failed).unwrap(), "\"failed\"");
    }

    #[test]
    fn build_jobs_url_joins_control_plane_url_and_robot_id() {
        assert_eq!(
            build_jobs_url("https://api.mecha10.dev", "robot-1"),
            "https://api.mecha10.dev/api/robots/robot-1/build-jobs"
        );
    }

    #[test]
    fn build_jobs_url_trims_a_trailing_slash_on_the_control_plane_url() {
        assert_eq!(
            build_jobs_url("https://api.mecha10.dev/", "robot-1"),
            "https://api.mecha10.dev/api/robots/robot-1/build-jobs"
        );
    }

    /// Minimal fake HTTP server that always responds `response_body` with `status_line` to
    /// any request - same pattern as `handlers/build.rs`'s `FakeAssetsServer`, trimmed down
    /// since these tests don't need to inspect the request at all (the server-side multipart
    /// parsing is mecha10-api's responsibility, pinned by its own tests, not this repo's).
    fn start_fake_server(status_line: &'static str, response_body: String) -> String {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let mut stream = match stream {
                    Ok(s) => s,
                    Err(_) => continue,
                };
                // A single `read` can return before the client finishes writing the full
                // request - TCP gives no message-boundary guarantee, and under CI scheduling
                // jitter the write can be split across multiple segments. Read until the
                // stream goes quiet instead of assuming one `read` captures everything.
                let _ = stream.set_read_timeout(Some(std::time::Duration::from_millis(200)));
                let mut buf = [0u8; 65536];
                loop {
                    match stream.read(&mut buf) {
                        Ok(0) => break,
                        Ok(_) => continue,
                        Err(ref e)
                            if e.kind() == std::io::ErrorKind::WouldBlock
                                || e.kind() == std::io::ErrorKind::TimedOut =>
                        {
                            break
                        }
                        Err(_) => break,
                    }
                }
                let header = format!(
                    "{status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    response_body.len()
                );
                let _ = stream.write_all(header.as_bytes());
                let _ = stream.write_all(response_body.as_bytes());
                let _ = stream.flush();
            }
        });

        format!("http://{}", addr)
    }

    #[tokio::test]
    async fn get_build_job_returns_the_parsed_response_on_success() {
        let body = serde_json::json!({
            "id": "job-1",
            "state": "running",
            "error_message": null,
            "progress_message": "compiling"
        })
        .to_string();
        let url = start_fake_server("HTTP/1.1 200 OK", body);

        let result = get_build_job(&url, "robot-1", "job-1", "mecha_test_key").await.unwrap();

        assert_eq!(result.state, BuildJobState::Running);
        assert_eq!(result.progress_message, Some("compiling".to_string()));
    }

    #[tokio::test]
    async fn get_build_job_surfaces_the_servers_error_on_failure() {
        let url = start_fake_server(
            "HTTP/1.1 404 Not Found",
            serde_json::json!({"error": "build job job-1 not found"}).to_string(),
        );

        let err = get_build_job(&url, "robot-1", "job-1", "mecha_test_key")
            .await
            .unwrap_err();

        assert!(err.to_string().contains("not found"));
    }

    #[test]
    fn github_connections_url_joins_control_plane_url() {
        assert_eq!(
            github_connections_url("https://api.mecha10.dev"),
            "https://api.mecha10.dev/api/github/connections"
        );
        assert_eq!(
            github_connections_url("https://api.mecha10.dev/"),
            "https://api.mecha10.dev/api/github/connections"
        );
    }

    #[test]
    fn github_install_start_url_joins_control_plane_url() {
        assert_eq!(
            github_install_start_url("https://api.mecha10.dev"),
            "https://api.mecha10.dev/api/github/install/start"
        );
    }

    #[tokio::test]
    async fn list_github_connections_returns_the_parsed_connections_on_success() {
        let body = serde_json::json!({
            "connections": [
                {
                    "id": "conn-1",
                    "installation_id": 42,
                    "account_login": "mecha-industries",
                    "repo_full_name": "mecha-industries/mecha10",
                    "created_at": "2024-01-01T00:00:00Z",
                    "updated_at": "2024-01-01T00:00:00Z"
                },
                {
                    "id": "conn-2",
                    "installation_id": 43,
                    "account_login": "someone-else",
                    "repo_full_name": null,
                    "created_at": "2024-01-01T00:00:00Z",
                    "updated_at": "2024-01-01T00:00:00Z"
                }
            ],
            "total": 2
        })
        .to_string();
        let url = start_fake_server("HTTP/1.1 200 OK", body);

        let connections = list_github_connections(&url, "mecha_test_key").await.unwrap();

        assert_eq!(connections.len(), 2);
        assert_eq!(connections[0].id, "conn-1");
        assert_eq!(
            connections[0].repo_full_name,
            Some("mecha-industries/mecha10".to_string())
        );
        assert_eq!(connections[1].repo_full_name, None);
    }

    #[tokio::test]
    async fn list_github_connections_surfaces_the_servers_error_on_failure() {
        let url = start_fake_server(
            "HTTP/1.1 401 Unauthorized",
            serde_json::json!({"error": "invalid API key"}).to_string(),
        );

        let err = list_github_connections(&url, "mecha_bad_key").await.unwrap_err();

        assert!(err.to_string().contains("invalid API key"));
    }

    #[tokio::test]
    async fn start_github_install_returns_the_install_url_on_success() {
        let body = serde_json::json!({"install_url": "https://github.com/apps/mecha10/installations/new?state=abc"})
            .to_string();
        let url = start_fake_server("HTTP/1.1 200 OK", body);

        let result = start_github_install(&url, "mecha_test_key").await.unwrap();

        assert_eq!(
            result.install_url,
            "https://github.com/apps/mecha10/installations/new?state=abc"
        );
    }

    #[tokio::test]
    async fn start_github_install_surfaces_the_servers_error_on_failure() {
        let url = start_fake_server(
            "HTTP/1.1 500 Internal Server Error",
            serde_json::json!({"error": "GitHub App is not configured"}).to_string(),
        );

        let err = start_github_install(&url, "mecha_test_key").await.unwrap_err();

        assert!(err.to_string().contains("not configured"));
    }

    #[tokio::test]
    async fn create_build_job_from_github_returns_the_parsed_response_on_success() {
        let body = serde_json::json!({
            "id": "job-1",
            "robot_id": "robot-1",
            "state": "pending",
            "kestra_execution_id": null,
            "message": "Build job queued"
        })
        .to_string();
        let url = start_fake_server("HTTP/1.1 200 OK", body);

        let result = create_build_job_from_github(CreateBuildJobFromGithubParams {
            control_plane_url: &url,
            robot_id: "robot-1",
            connection_id: "conn-1",
            target_platform: "linux",
            target_arch: "aarch64",
            config: None,
            api_key: "mecha_test_key",
        })
        .await
        .unwrap();

        assert_eq!(result.id, "job-1");
    }

    #[tokio::test]
    async fn create_build_job_from_github_surfaces_the_servers_error_on_failure() {
        let url = start_fake_server(
            "HTTP/1.1 400 Bad Request",
            serde_json::json!({"error": "GitHub connection conn-1 has no repo selected yet"}).to_string(),
        );

        let err = create_build_job_from_github(CreateBuildJobFromGithubParams {
            control_plane_url: &url,
            robot_id: "robot-1",
            connection_id: "conn-1",
            target_platform: "linux",
            target_arch: "aarch64",
            config: None,
            api_key: "mecha_test_key",
        })
        .await
        .unwrap_err();

        assert!(err.to_string().contains("no repo selected"));
    }

    #[tokio::test]
    async fn report_build_job_status_succeeds_on_a_success_response() {
        let url = start_fake_server("HTTP/1.1 200 OK", serde_json::json!({"ok": true}).to_string());

        report_build_job_status(ReportBuildJobStatusParams {
            control_plane_url: &url,
            robot_id: "robot-1",
            job_id: "job-1",
            service_token: "service-token",
            state: BuildJobState::Succeeded,
            binary_id: Some("binary-1"),
            error_message: None,
        })
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn report_build_job_status_surfaces_the_servers_error_on_failure() {
        let url = start_fake_server(
            "HTTP/1.1 401 Unauthorized",
            serde_json::json!({"error": "invalid service token"}).to_string(),
        );

        let err = report_build_job_status(ReportBuildJobStatusParams {
            control_plane_url: &url,
            robot_id: "robot-1",
            job_id: "job-1",
            service_token: "bad-token",
            state: BuildJobState::Failed,
            binary_id: None,
            error_message: Some("build failed: cargo exited with status 101"),
        })
        .await
        .unwrap_err();

        assert!(err.to_string().contains("invalid service token"));
    }

    #[test]
    fn report_build_job_status_url_matches_the_build_jobs_route_plus_status_suffix() {
        // Pure string-shape check (no network): `.../build-jobs/{job_id}/status`.
        let expected = format!("{}/job-1/status", build_jobs_url("https://api.mecha10.dev", "robot-1"));
        assert_eq!(
            expected,
            "https://api.mecha10.dev/api/robots/robot-1/build-jobs/job-1/status"
        );
    }
}