studio-worker 0.4.7

Pull-based image-generation worker for the minis.gg studio.
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
//! Thin reqwest wrapper around the studio API.
//!
//! Every call goes through [`ApiClient::check`], which:
//!
//! - emits a structured `tracing` event on success (`debug`) and
//!   failure (`warn`) so operators can see what the worker is talking
//!   to without having to enable wire-level logging in reqwest
//!   (`complete` also logs the upload byte size before the request so
//!   the attempted payload size is visible even when it never finishes),
//!   and
//! - turns non-2xx responses into an `anyhow` error tagged with the
//!   operation name so the existing log shipper messages stay legible.
use crate::types::*;
use anyhow::{anyhow, Context, Result};
use reqwest::blocking::{Client, Response};
use std::time::{Duration, Instant};
use tracing::{debug, warn};

/// Base path under which the worker endpoints are mounted.
const API_PREFIX: &str = "/graphics/api";

/// Tracing target used for every event emitted by the HTTP client.
/// Keeping it stable lets operators filter with
/// `RUST_LOG=studio_worker::http=debug` without touching the rest of
/// the agent's logs.
const TRACE_TARGET: &str = "studio_worker::http";

/// Typed non-2xx response error so callers can branch on the status
/// class (e.g. retry 5xx, never retry 4xx) without sniffing message
/// strings.  The rendered message keeps the legacy `<op> failed:
/// <status> — <body>` shape existing tests and log consumers expect.
#[derive(Debug, thiserror::Error)]
#[error("{op} failed: {status} — {body}")]
pub struct HttpStatusError {
    pub op: String,
    pub status: u16,
    pub body: String,
}

impl HttpStatusError {
    /// Server-side failures are worth retrying; 4xx contract errors
    /// are not.
    pub fn is_transient(&self) -> bool {
        self.status >= 500
    }
}

/// True when the upload failed for a reason a short retry can fix: a
/// 5xx from the studio or a transport-level error (connect refused,
/// timeout, broken pipe).  4xx contract errors return false.
pub fn is_transient_upload_error(e: &anyhow::Error) -> bool {
    if let Some(status) = e.downcast_ref::<HttpStatusError>() {
        return status.is_transient();
    }
    e.downcast_ref::<reqwest::Error>().is_some()
}

pub struct ApiClient {
    pub base_url: String,
    pub client: Client,
}

/// Process-wide blocking client, shared by every `ApiClient`.
/// `reqwest::blocking::Client` is an `Arc` around a connection pool;
/// rebuilding it per call (the old behaviour) re-did TLS setup and
/// threw the pool away between requests.
fn shared_client() -> Result<Client> {
    static CLIENT: std::sync::OnceLock<Client> = std::sync::OnceLock::new();
    if let Some(client) = CLIENT.get() {
        return Ok(client.clone());
    }
    let built = Client::builder()
        .timeout(Duration::from_secs(60))
        .build()
        .context("building reqwest client")?;
    // A concurrent first call may have won the publish; either client
    // is fine — take whichever landed.
    Ok(CLIENT.get_or_init(|| built).clone())
}

impl ApiClient {
    pub fn new(base_url: String) -> Result<Self> {
        Ok(Self {
            base_url: normalize_base_url(&base_url)?,
            client: shared_client()?,
        })
    }

    fn url(&self, path: &str) -> String {
        format!("{}{}{}", self.base_url, API_PREFIX, path)
    }

    /// Inspect a response, log it, and convert non-2xx into an
    /// `anyhow` error.  `op` is the human-readable operation name used
    /// in the error message (kept stable for log-shipper consumers and
    /// existing tests).
    fn check(&self, op: &str, url: &str, started: Instant, response: Response) -> Result<Response> {
        let status = response.status();
        let elapsed_ms = started.elapsed().as_millis() as u64;
        if status.is_success() || status.as_u16() == 204 {
            debug!(
                target: TRACE_TARGET,
                op,
                endpoint = %url,
                status = status.as_u16(),
                elapsed_ms,
                "ok"
            );
            return Ok(response);
        }
        // Body read consumes the response; we only need it on the
        // failure path.
        let body = response.text().unwrap_or_default();
        warn!(
            target: TRACE_TARGET,
            op,
            endpoint = %url,
            status = status.as_u16(),
            elapsed_ms,
            body = %body,
            "{op} failed"
        );
        Err(HttpStatusError {
            op: op.to_string(),
            status: status.as_u16(),
            body,
        }
        .into())
    }

    // -----------------------------------------------------------------------
    // Auto-register (operator-approved) flow
    // -----------------------------------------------------------------------

    /// Create a Pending Workers row.  Unauthenticated on purpose —
    /// the studio rate-limits this endpoint by source IP and the
    /// operator manually approves before the worker can do anything.
    pub fn register_request(
        &self,
        payload: &AutoRegisterRequest,
    ) -> Result<AutoRegisterRequestResponse> {
        let url = self.url("/workers/register-request");
        let started = Instant::now();
        let response = self.client.post(&url).json(payload).send()?;
        let response = self.check("register-request", &url, started, response)?;
        Ok(response.json()?)
    }

    /// Poll the studio for the operator's decision on a previously
    /// submitted register-request.  Returns `Ok(None)` when the
    /// request id is unknown to the studio (likely cleaned up or
    /// never existed) so the orchestrator can drop the stale id and
    /// start a fresh one.  Auth is the raw `registration_secret`
    /// presented as a Bearer token.
    pub fn poll_register_status(
        &self,
        request_id: &str,
        registration_secret: &str,
    ) -> Result<Option<RegisterStatus>> {
        let url = self.url(&format!("/workers/register-requests/{request_id}"));
        let started = Instant::now();
        let response = self
            .client
            .get(&url)
            .bearer_auth(registration_secret)
            .send()?;
        if response.status().as_u16() == 404 {
            debug!(
                target: TRACE_TARGET,
                op = "register-poll",
                endpoint = %url,
                status = 404,
                elapsed_ms = started.elapsed().as_millis() as u64,
                "register request not found (stale id; orchestrator will recreate)"
            );
            return Ok(None);
        }
        let response = self.check("register-poll", &url, started, response)?;
        Ok(Some(response.json()?))
    }

    /// Complete a job with binary output (image / audio / video).
    ///
    /// This is the only worker-side HTTP route that survives the WS
    /// migration: R2 multipart doesn't fit cleanly into WS frames.
    /// Heartbeats, claim/accept/reject, completeJson, fail, and log
    /// shipping all flow over the WS session owned by
    /// `ws::session::spawn_ws_session`.
    pub fn complete(
        &self,
        worker_id: &str,
        token: &str,
        job_id: &str,
        ext: &str,
        prompt: &str,
        image: Vec<u8>,
    ) -> Result<()> {
        let mime = mime_for_ext(ext);
        let bytes = image.len() as u64;
        // Emitted before the (potentially slow or failing) upload so the
        // attempted payload size is always in the operator's logs, even
        // when the request itself never completes.
        debug!(
            target: TRACE_TARGET,
            op = "complete",
            job_id,
            ext,
            mime,
            bytes,
            "uploading job result"
        );
        let part = reqwest::blocking::multipart::Part::bytes(image)
            .file_name(format!("{job_id}.{ext}"))
            .mime_str(mime)?;
        let form = reqwest::blocking::multipart::Form::new()
            .text("prompt", prompt.to_string())
            .text("ext", ext.to_string())
            .part("image", part);
        let url = self.url(&format!("/workers/{worker_id}/jobs/{job_id}/complete"));
        let started = Instant::now();
        let response = self
            .client
            .post(&url)
            .bearer_auth(token)
            .multipart(form)
            .send()?;
        self.check("complete", &url, started, response)?;
        Ok(())
    }

    /// Like [`Self::complete`] but retries transient failures (5xx +
    /// transport errors) up to `retries` additional attempts, pausing
    /// `pause * attempt` between them.  4xx contract errors surface
    /// immediately.  Keeps a brief upload blip from costing a full GPU
    /// regeneration — a reported `Fail` makes the studio requeue and
    /// re-render the whole job.
    #[allow(clippy::too_many_arguments)]
    pub fn complete_with_retry(
        &self,
        worker_id: &str,
        token: &str,
        job_id: &str,
        ext: &str,
        prompt: &str,
        image: Vec<u8>,
        retries: u32,
        pause: Duration,
    ) -> Result<()> {
        let mut attempt: u32 = 0;
        loop {
            match self.complete(worker_id, token, job_id, ext, prompt, image.clone()) {
                Ok(()) => return Ok(()),
                Err(e) if attempt < retries && is_transient_upload_error(&e) => {
                    attempt += 1;
                    warn!(
                        target: TRACE_TARGET,
                        op = "complete",
                        job_id,
                        attempt,
                        max_attempts = retries + 1,
                        error = %e,
                        "transient upload failure; retrying"
                    );
                    std::thread::sleep(pause * attempt);
                }
                Err(e) => return Err(e),
            }
        }
    }
}

fn normalize_base_url(base_url: &str) -> Result<String> {
    let mut url =
        url::Url::parse(base_url).map_err(|e| anyhow!("invalid api_base_url {base_url:?}: {e}"))?;
    url.set_query(None);
    url.set_fragment(None);

    let trimmed_path = url.path().trim_end_matches('/').to_string();
    if trimmed_path.ends_with(API_PREFIX) {
        let without_prefix = trimmed_path[..trimmed_path.len() - API_PREFIX.len()].to_string();
        url.set_path(if without_prefix.is_empty() {
            "/"
        } else {
            &without_prefix
        });
    }

    Ok(url.as_str().trim_end_matches('/').to_string())
}

/// Map a binary output's file extension to the MIME type sent as the
/// multipart `complete` upload's `Content-Type`.  Single source of
/// truth: every engine that emits a `TaskResult` binary extension
/// (synthetic image → `png`/`webp`, sd-cpp → `webp`, tts → `wav`,
/// synthetic video → `webp`, the `video` feature → `gif`) routes
/// through here, so a new extension can't silently drift into
/// `application/octet-stream` and break the studio's stored
/// content-type.
pub fn mime_for_ext(ext: &str) -> &'static str {
    match ext {
        "png" => "image/png",
        "webp" => "image/webp",
        "gif" => "image/gif",
        "wav" => "audio/wav",
        "mp3" => "audio/mpeg",
        "mp4" => "video/mp4",
        _ => "application/octet-stream",
    }
}

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

    #[test]
    fn mime_for_ext_maps_known_image_audio_video_types() {
        assert_eq!(mime_for_ext("png"), "image/png");
        assert_eq!(mime_for_ext("webp"), "image/webp");
        assert_eq!(mime_for_ext("gif"), "image/gif");
        assert_eq!(mime_for_ext("wav"), "audio/wav");
        assert_eq!(mime_for_ext("mp3"), "audio/mpeg");
        assert_eq!(mime_for_ext("mp4"), "video/mp4");
    }

    #[test]
    fn mime_for_ext_falls_back_to_octet_stream_for_unknown() {
        assert_eq!(mime_for_ext("bin"), "application/octet-stream");
        assert_eq!(mime_for_ext(""), "application/octet-stream");
    }

    #[test]
    fn normalize_base_url_strips_existing_graphics_api_prefix() {
        let api = ApiClient::new("https://studio.example/graphics/api/".into()).unwrap();
        assert_eq!(
            api.url("/workers/register-request"),
            "https://studio.example/graphics/api/workers/register-request"
        );
    }

    #[test]
    fn normalize_base_url_preserves_outer_mount_path() {
        let api = ApiClient::new("https://studio.example/custom/graphics/api".into()).unwrap();
        assert_eq!(
            api.url("/workers/register-request"),
            "https://studio.example/custom/graphics/api/workers/register-request"
        );
    }

    #[test]
    fn is_transient_classifies_5xx_as_retryable_and_4xx_as_terminal() {
        // The retry gate: server-side failures are worth a short retry,
        // client-side contract errors are not.  This pins the boundary
        // the upload-retry loop branches on.
        let err = |status| HttpStatusError {
            op: "complete".into(),
            status,
            body: "x".into(),
        };
        assert!(err(500).is_transient());
        assert!(err(503).is_transient());
        assert!(!err(499).is_transient());
        assert!(!err(409).is_transient());
        assert!(!err(400).is_transient());
    }

    #[test]
    fn is_transient_upload_error_branches_on_error_kind() {
        // 5xx HTTP status → retry; 4xx → terminal.
        let server_err: anyhow::Error = HttpStatusError {
            op: "complete".into(),
            status: 502,
            body: "bad gateway".into(),
        }
        .into();
        assert!(is_transient_upload_error(&server_err));
        let client_err: anyhow::Error = HttpStatusError {
            op: "complete".into(),
            status: 409,
            body: "conflict".into(),
        }
        .into();
        assert!(!is_transient_upload_error(&client_err));

        // A transport-level reqwest error (connection refused) is the
        // branch the wiremock tests can't reach — no HTTP response ever
        // comes back — yet it's exactly the upload blip a retry fixes.
        let transport: anyhow::Error = Client::builder()
            .timeout(Duration::from_millis(200))
            .build()
            .unwrap()
            .post("http://127.0.0.1:1/unreachable")
            .body(Vec::<u8>::new())
            .send()
            .expect_err("connect to a dead port must fail")
            .into();
        assert!(
            is_transient_upload_error(&transport),
            "a transport-level failure must be retryable"
        );

        // An unrelated error (neither HTTP status nor transport) is not
        // an upload blip, so it must not trigger a retry.
        let unrelated = anyhow!("local disk full while staging the upload");
        assert!(!is_transient_upload_error(&unrelated));
    }

    #[test]
    fn mime_for_ext_covers_every_extension_engines_emit() {
        // Lock the contract: each binary extension an engine actually
        // emits must resolve to a real MIME type, never the
        // octet-stream fallback.  `gif` is the one the `video`
        // feature produces and that regressed before this guard.
        for ext in ["png", "webp", "gif", "wav"] {
            assert_ne!(
                mime_for_ext(ext),
                "application/octet-stream",
                "engine output extension {ext:?} must map to a real MIME type"
            );
        }
    }
}