mockforge-registry-server 0.3.124

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
//! 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>>,
}

/// 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)
    }
}