mockforge-registry-server 0.3.129

Plugin registry server for MockForge
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
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
//! Fly.io API integration for deploying mock services

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

/// Fly.io API client for managing deployments
pub struct FlyioClient {
    api_token: String,
    base_url: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlyioApp {
    pub id: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub hostname: Option<String>,
    #[serde(default)]
    pub organization: Option<FlyioOrganization>,
    #[serde(default)]
    pub status: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlyioOrganization {
    pub id: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub slug: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlyioMachine {
    pub id: String,
    pub name: String,
    pub state: String,
    pub region: String,
    pub image_ref: Option<FlyioImageRef>,
    pub config: FlyioMachineConfig,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlyioImageRef {
    pub registry: String,
    pub repository: String,
    pub tag: String,
    pub digest: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlyioMachineConfig {
    pub image: String,
    pub env: HashMap<String, String>,
    pub services: Vec<FlyioService>,
    pub checks: Option<HashMap<String, FlyioCheck>>,
    /// VM resource sizing. `None` means accept Fly's API default
    /// (currently `shared-cpu-1x:256MB`); existing deployments and
    /// non-plugin-enabled machines stay on that default. Cloud
    /// plugins requires explicit sizing — see
    /// `docs/plugins/security/cloud-runtime-sidecar-spike.md` for
    /// the measured-on-Fly numbers and tier table.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guest: Option<FlyioGuest>,
}

/// VM sizing block sent to Fly Machines API as `config.guest`.
/// Mirrors the API's expected JSON shape:
/// <https://fly.io/docs/machines/api/machines-resource/#machine-config-object-properties>
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlyioGuest {
    /// `"shared"` or `"performance"`.
    pub cpu_kind: String,
    pub cpus: u32,
    pub memory_mb: u32,
}

impl FlyioGuest {
    /// `shared-cpu-1x:256MB` — Fly's default for the registry today.
    /// Used when no plugins are attached so existing hosted-mocks
    /// keep their current footprint.
    pub fn shared_256() -> Self {
        Self {
            cpu_kind: "shared".into(),
            cpus: 1,
            memory_mb: 256,
        }
    }

    /// `shared-cpu-1x:512MB` — Pro tier with cloud plugins. Real-Fly
    /// measurement on the spike showed mockforge + sidecar idle at
    /// ~166 MB / 256 MB (65%), with only 71 MB headroom; bumping to
    /// 512 MB gives 316 MB headroom — comfortable for ≤5 plugins
    /// at typical sizes.
    pub fn shared_512() -> Self {
        Self {
            cpu_kind: "shared".into(),
            cpus: 1,
            memory_mb: 512,
        }
    }

    /// `shared-cpu-1x:1024MB` — Team tier with cloud plugins
    /// (≤25 plugins per mock).
    pub fn shared_1024() -> Self {
        Self {
            cpu_kind: "shared".into(),
            cpus: 1,
            memory_mb: 1024,
        }
    }

    /// `shared-cpu-2x:2048MB` — Enterprise tier with metered
    /// pass-through. Two cores so heavy plugin workloads don't
    /// starve mockforge's request path.
    pub fn shared_2x_2048() -> Self {
        Self {
            cpu_kind: "shared".into(),
            cpus: 2,
            memory_mb: 2048,
        }
    }

    /// Pick the right Fly machine size for a hosted-mock deployment
    /// based on org plan + whether cloud plugins are attached.
    ///
    /// Without plugins, every tier stays on the existing 256 MB
    /// default — no behavior change for legacy deployments.
    ///
    /// With plugins, the floor bumps according to the
    /// real-microVM measurements in
    /// `docs/plugins/security/cloud-runtime-sidecar-spike.md`:
    /// idle on 256 MB sits at ~166 MB / 65% utilization with only
    /// ~71 MB headroom. That's not enough for the plugin runtime to
    /// grow into without OOM-killing mockforge. 512 MB gives 316 MB
    /// headroom which fits ≤5 plugins comfortably; Team's larger
    /// plugin count needs 1024 MB.
    pub fn for_hosted_mock(plan: &str, plugins_enabled: bool) -> Self {
        if !plugins_enabled {
            return Self::shared_256();
        }
        match plan.to_lowercase().as_str() {
            "free" => Self::shared_256(), // Plugins not available on Free.
            "pro" => Self::shared_512(),
            "team" => Self::shared_1024(),
            // Unknown / future plans (e.g. "enterprise") get the
            // largest currently-available shape. The handler should
            // refuse plugin attachment for unknown plans before
            // ever reaching this; defaulting big is fail-safe.
            _ => Self::shared_2x_2048(),
        }
    }
}

/// Registry authentication for pulling private Docker images
#[derive(Debug, Serialize, Deserialize)]
pub struct FlyioRegistryAuth {
    pub server: String,
    pub username: String,
    pub password: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlyioService {
    pub protocol: String,
    pub internal_port: u16,
    pub ports: Vec<FlyioPort>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlyioPort {
    pub port: u16,
    pub handlers: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlyioCheck {
    #[serde(rename = "type")]
    pub check_type: String,
    pub port: u16,
    pub grace_period: String,
    pub interval: String,
    pub method: String,
    pub timeout: String,
    pub tls_skip_verify: bool,
    pub path: Option<String>,
}

impl FlyioClient {
    pub fn new(api_token: String) -> Self {
        Self {
            api_token,
            base_url: "https://api.machines.dev".to_string(),
        }
    }

    /// Get the API token (used for Fly.io registry auth)
    pub fn api_token(&self) -> &str {
        &self.api_token
    }

    /// Create a new Fly.io app
    pub async fn create_app(&self, app_name: &str, org_slug: &str) -> Result<FlyioApp> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps", self.base_url);

        let payload = serde_json::json!({
            "app_name": app_name,
            "org_slug": org_slug,
        });

        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await
            .context("Failed to create Fly.io app")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());

            // Handle "Name has already been taken" (422) — the app exists, fetch it instead
            if status.as_u16() == 422 && error_text.contains("already been taken") {
                tracing::info!("Fly.io app '{}' already exists, fetching existing app", app_name);
                return self.get_app(app_name).await;
            }

            anyhow::bail!("Failed to create Fly.io app: {} - {}", status, error_text);
        }

        let app: FlyioApp = response.json().await.context("Failed to parse Fly.io app response")?;

        Ok(app)
    }

    /// Create a machine (instance) for the app
    pub async fn create_machine(
        &self,
        app_name: &str,
        config: FlyioMachineConfig,
        region: &str,
        registry_auth: Option<FlyioRegistryAuth>,
    ) -> Result<FlyioMachine> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps/{}/machines", self.base_url, app_name);

        let mut payload = serde_json::json!({
            "config": config,
            "region": region,
        });
        if let Some(auth) = registry_auth {
            payload["config"]["image_registry_auth"] =
                serde_json::to_value(auth).context("Failed to serialize registry auth")?;
        }

        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await
            .context("Failed to create Fly.io machine")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!("Failed to create Fly.io machine: {} - {}", status, error_text);
        }

        let machine: FlyioMachine =
            response.json().await.context("Failed to parse Fly.io machine response")?;

        Ok(machine)
    }

    /// Update a machine's configuration (image, env vars, etc.)
    pub async fn update_machine(
        &self,
        app_name: &str,
        machine_id: &str,
        config: FlyioMachineConfig,
        registry_auth: Option<FlyioRegistryAuth>,
    ) -> Result<FlyioMachine> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps/{}/machines/{}", self.base_url, app_name, machine_id);

        let mut payload = serde_json::json!({
            "config": config,
        });
        if let Some(auth) = registry_auth {
            payload["config"]["image_registry_auth"] =
                serde_json::to_value(auth).context("Failed to serialize registry auth")?;
        }

        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await
            .context("Failed to update Fly.io machine")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!("Failed to update Fly.io machine: {} - {}", status, error_text);
        }

        let machine: FlyioMachine =
            response.json().await.context("Failed to parse Fly.io machine response")?;

        Ok(machine)
    }

    /// Get machine status
    pub async fn get_machine(&self, app_name: &str, machine_id: &str) -> Result<FlyioMachine> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps/{}/machines/{}", self.base_url, app_name, machine_id);

        let response = client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .send()
            .await
            .context("Failed to get Fly.io machine")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!("Failed to get Fly.io machine: {} - {}", status, error_text);
        }

        let machine: FlyioMachine =
            response.json().await.context("Failed to parse Fly.io machine response")?;

        Ok(machine)
    }

    /// Stop a running machine (graceful shutdown, keeps the machine around
    /// so it can be restarted later without recreating its config).
    pub async fn stop_machine(&self, app_name: &str, machine_id: &str) -> Result<()> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps/{}/machines/{}/stop", self.base_url, app_name, machine_id);

        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({}))
            .send()
            .await
            .context("Failed to stop Fly.io machine")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!("Failed to stop Fly.io machine: {} - {}", status, error_text);
        }

        Ok(())
    }

    /// Start a stopped machine.
    pub async fn start_machine(&self, app_name: &str, machine_id: &str) -> Result<()> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps/{}/machines/{}/start", self.base_url, app_name, machine_id);

        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .header("Content-Type", "application/json")
            .send()
            .await
            .context("Failed to start Fly.io machine")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!("Failed to start Fly.io machine: {} - {}", status, error_text);
        }

        Ok(())
    }

    /// Delete a machine
    pub async fn delete_machine(&self, app_name: &str, machine_id: &str) -> Result<()> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps/{}/machines/{}", self.base_url, app_name, machine_id);

        let response = client
            .delete(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .send()
            .await
            .context("Failed to delete Fly.io machine")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!("Failed to delete Fly.io machine: {} - {}", status, error_text);
        }

        Ok(())
    }

    /// Delete a Fly.io app
    pub async fn delete_app(&self, app_name: &str) -> Result<()> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps/{}", self.base_url, app_name);

        let response = client
            .delete(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .send()
            .await
            .context("Failed to delete Fly.io app")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!("Failed to delete Fly.io app: {} - {}", status, error_text);
        }

        Ok(())
    }

    /// Allocate a shared IPv4 and a dedicated IPv6 address for an app
    pub async fn allocate_ips(&self, app_name: &str) -> Result<()> {
        let client = reqwest::Client::new();
        let graphql_url = "https://api.fly.io/graphql";

        // Allocate shared IPv4
        let ipv4_query = serde_json::json!({
            "query": "mutation($input: AllocateIPAddressInput!) { allocateIpAddress(input: $input) { ipAddress { id address type } } }",
            "variables": {
                "input": {
                    "appId": app_name,
                    "type": "shared_v4"
                }
            }
        });

        let response = client
            .post(graphql_url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .json(&ipv4_query)
            .send()
            .await
            .context("Failed to allocate shared IPv4")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to allocate shared IPv4: {}", error_text);
        }

        // Allocate IPv6
        let ipv6_query = serde_json::json!({
            "query": "mutation($input: AllocateIPAddressInput!) { allocateIpAddress(input: $input) { ipAddress { id address type } } }",
            "variables": {
                "input": {
                    "appId": app_name,
                    "type": "v6"
                }
            }
        });

        let response = client
            .post(graphql_url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .json(&ipv6_query)
            .send()
            .await
            .context("Failed to allocate IPv6")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to allocate IPv6: {}", error_text);
        }

        Ok(())
    }

    /// Get app info
    pub async fn get_app(&self, app_name: &str) -> Result<FlyioApp> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps/{}", self.base_url, app_name);

        let response = client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .send()
            .await
            .context("Failed to get Fly.io app")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!("Failed to get Fly.io app: {} - {}", status, error_text);
        }

        let app: FlyioApp = response.json().await.context("Failed to parse Fly.io app response")?;

        Ok(app)
    }

    /// Add a custom domain certificate to an app
    ///
    /// This tells Fly.io to provision a Let's Encrypt TLS certificate for the
    /// given hostname and route traffic for that hostname to this app via SNI.
    pub async fn add_certificate(&self, app_name: &str, hostname: &str) -> Result<()> {
        let client = reqwest::Client::new();
        let graphql_url = "https://api.fly.io/graphql";

        let query = serde_json::json!({
            "query": "mutation($appId: ID!, $hostname: String!) { addCertificate(appId: $appId, hostname: $hostname) { certificate { id hostname } } }",
            "variables": {
                "appId": app_name,
                "hostname": hostname
            }
        });

        let response = client
            .post(graphql_url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .json(&query)
            .send()
            .await
            .context("Failed to add certificate")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to add certificate for {}: {}", hostname, error_text);
        }

        // Check for GraphQL-level errors
        let body: serde_json::Value =
            response.json().await.context("Failed to parse certificate response")?;
        if let Some(errors) = body.get("errors") {
            // "already exists" is fine — idempotent
            let err_str = errors.to_string();
            if !err_str.contains("already exists") {
                anyhow::bail!("Failed to add certificate for {}: {}", hostname, err_str);
            }
        }

        Ok(())
    }

    /// Remove a custom domain certificate from an app
    pub async fn delete_certificate(&self, app_name: &str, hostname: &str) -> Result<()> {
        let client = reqwest::Client::new();
        let graphql_url = "https://api.fly.io/graphql";

        let query = serde_json::json!({
            "query": "mutation($appId: ID!, $hostname: String!) { deleteCertificate(appId: $appId, hostname: $hostname) { app { name } } }",
            "variables": {
                "appId": app_name,
                "hostname": hostname
            }
        });

        let response = client
            .post(graphql_url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .json(&query)
            .send()
            .await
            .context("Failed to delete certificate")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to delete certificate for {}: {}", hostname, error_text);
        }

        Ok(())
    }

    /// List machines for an app
    pub async fn list_machines(&self, app_name: &str) -> Result<Vec<FlyioMachine>> {
        let client = reqwest::Client::new();
        let url = format!("{}/v1/apps/{}/machines", self.base_url, app_name);

        let response = client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.api_token))
            .send()
            .await
            .context("Failed to list Fly.io machines")?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!("Failed to list Fly.io machines: {} - {}", status, error_text);
        }

        let machines: Vec<FlyioMachine> =
            response.json().await.context("Failed to parse Fly.io machines response")?;

        Ok(machines)
    }
}

#[cfg(test)]
mod guest_tests {
    use super::*;

    #[test]
    fn for_hosted_mock_no_plugins_uses_legacy_256() {
        // Existing hosted-mocks without cloud plugins must keep
        // their current 256 MB footprint — no surprise pricing
        // bumps for legacy deployments.
        for plan in ["free", "pro", "team", "enterprise", "weird-future-plan"] {
            let g = FlyioGuest::for_hosted_mock(plan, false);
            assert_eq!(g.memory_mb, 256, "plan {} without plugins must stay at 256MB", plan);
            assert_eq!(g.cpu_kind, "shared");
            assert_eq!(g.cpus, 1);
        }
    }

    #[test]
    fn for_hosted_mock_pro_with_plugins_bumps_to_512() {
        let g = FlyioGuest::for_hosted_mock("pro", true);
        assert_eq!(g.memory_mb, 512);
        assert_eq!(g.cpus, 1);
    }

    #[test]
    fn for_hosted_mock_team_with_plugins_bumps_to_1024() {
        let g = FlyioGuest::for_hosted_mock("team", true);
        assert_eq!(g.memory_mb, 1024);
        assert_eq!(g.cpus, 1);
    }

    #[test]
    fn for_hosted_mock_free_with_plugins_stays_256() {
        // Plugins aren't available on Free — handler rejects before
        // we get here — but if we do, don't accidentally upsize
        // a Free org's machine.
        let g = FlyioGuest::for_hosted_mock("free", true);
        assert_eq!(g.memory_mb, 256);
    }

    #[test]
    fn for_hosted_mock_unknown_plan_with_plugins_fails_safe_high() {
        // Unknown plans (e.g. future "enterprise") get the largest
        // shape rather than under-provisioning.
        let g = FlyioGuest::for_hosted_mock("enterprise", true);
        assert_eq!(g.memory_mb, 2048);
        assert_eq!(g.cpus, 2);
    }

    #[test]
    fn for_hosted_mock_plan_string_is_case_insensitive() {
        let g = FlyioGuest::for_hosted_mock("PRO", true);
        assert_eq!(g.memory_mb, 512);
        let g = FlyioGuest::for_hosted_mock("Team", true);
        assert_eq!(g.memory_mb, 1024);
    }

    #[test]
    fn machine_config_serialization_omits_guest_when_none() {
        // Existing call sites that pass `guest: None` (or use the
        // legacy struct without the field via Default) must produce
        // JSON without a `guest` key — so Fly's API default kicks in.
        let cfg = FlyioMachineConfig {
            image: "img".into(),
            env: HashMap::new(),
            services: vec![],
            checks: None,
            guest: None,
        };
        let json = serde_json::to_string(&cfg).unwrap();
        assert!(!json.contains("guest"), "guest=None must be omitted, got {}", json);
    }

    #[test]
    fn machine_config_serializes_guest_when_set() {
        let cfg = FlyioMachineConfig {
            image: "img".into(),
            env: HashMap::new(),
            services: vec![],
            checks: None,
            guest: Some(FlyioGuest::shared_512()),
        };
        let json = serde_json::to_string(&cfg).unwrap();
        assert!(json.contains("\"guest\""));
        assert!(json.contains("\"memory_mb\":512"));
        assert!(json.contains("\"cpu_kind\":\"shared\""));
    }
}