mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
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
#![allow(dead_code)]

use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::JoinHandle;

static TEMP_FILE_SEQ: AtomicU64 = AtomicU64::new(0);

/// RAII temporary file in `std::env::temp_dir()` removed automatically on drop.
pub struct TempFile {
    path: PathBuf,
}

impl TempFile {
    /// Creates a unique temporary file prefixed with `prefix` containing `bytes`.
    pub fn new(prefix: &str, bytes: &[u8]) -> Self {
        let seq = TEMP_FILE_SEQ.fetch_add(1, Ordering::Relaxed);
        let path = std::env::temp_dir().join(format!("{prefix}_{}_{seq}.tmp", std::process::id()));
        std::fs::write(&path, bytes).expect("failed to write temporary test file");
        Self { path }
    }

    /// Returns the filesystem path to this temporary file.
    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for TempFile {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

/// A recorded HTTP request received by [`MockServer`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecordedRequest {
    pub method: String,
    pub path: String,
    pub headers: HashMap<String, String>,
    pub body: Vec<u8>,
}

impl RecordedRequest {
    /// Returns the request body decoded as UTF-8 lossily.
    pub fn body_text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }

    /// Parses the request body as JSON.
    pub fn json_body<T: serde::de::DeserializeOwned>(&self) -> serde_json::Result<T> {
        serde_json::from_slice(&self.body)
    }

    /// Looks up a header case-insensitively.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .get(&name.to_ascii_lowercase())
            .map(String::as_str)
    }
}

/// A synthetic HTTP response returned by [`MockServer`].
#[derive(Clone, Debug)]
pub struct MockResponse {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

impl MockResponse {
    /// Creates a JSON response.
    pub fn json<T: serde::Serialize>(status: u16, value: &T) -> Self {
        let body = serde_json::to_vec(value).expect("mock JSON serialization failed");
        Self {
            status,
            headers: vec![("Content-Type".to_string(), "application/json".to_string())],
            body,
        }
    }

    /// Creates a plain text response.
    pub fn text(status: u16, body: impl Into<String>) -> Self {
        Self {
            status,
            headers: vec![(
                "Content-Type".to_string(),
                "text/plain; charset=utf-8".to_string(),
            )],
            body: body.into().into_bytes(),
        }
    }

    /// Creates a binary response with the given `Content-Type`.
    pub fn bytes(status: u16, content_type: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
        Self {
            status,
            headers: vec![("Content-Type".to_string(), content_type.into())],
            body: body.into(),
        }
    }

    /// Creates an empty response with the given status code.
    pub fn empty(status: u16) -> Self {
        Self {
            status,
            headers: Vec::new(),
            body: Vec::new(),
        }
    }

    /// Appends a response header.
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }
}

type RouteHandler = Arc<dyn Fn(&RecordedRequest) -> MockResponse + Send + Sync>;

#[derive(Default)]
struct MockState {
    recorded: Vec<RecordedRequest>,
    queued: VecDeque<MockResponse>,
    routes: Vec<(Option<String>, String, RouteHandler)>,
    prefix_routes: Vec<(Option<String>, String, RouteHandler)>,
}

/// Deterministic in-process HTTP/1.1 mock server for offline integration testing.
pub struct MockServer {
    addr: SocketAddr,
    state: Arc<Mutex<MockState>>,
    handle: JoinHandle<()>,
}

impl MockServer {
    /// Starts a new [`MockServer`] bound to `127.0.0.1:0`.
    pub async fn start() -> Self {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("failed to bind mock server");
        let addr = listener.local_addr().expect("failed to get local addr");
        let state = Arc::new(Mutex::new(MockState::default()));
        let state_clone = Arc::clone(&state);

        let handle = tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                let state_per_conn = Arc::clone(&state_clone);
                tokio::spawn(async move {
                    let _ = handle_connection(stream, state_per_conn).await;
                });
            }
        });

        Self {
            addr,
            state,
            handle,
        }
    }

    /// Returns the base HTTP URL (without trailing slash) for this mock server.
    pub fn base_url(&self) -> String {
        format!("http://{}", self.addr)
    }

    /// Queues a single FIFO response (checked after route handlers).
    pub fn enqueue(&self, response: MockResponse) {
        self.state.lock().unwrap().queued.push_back(response);
    }

    /// Registers an exact `(method, path_and_query)` route handler.
    pub fn on_route<F>(
        &self,
        method: impl Into<Option<String>>,
        path: impl Into<String>,
        handler: F,
    ) where
        F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.state
            .lock()
            .unwrap()
            .routes
            .push((method.into(), path.into(), Arc::new(handler)));
    }

    /// Registers a prefix route handler matching `req.path.starts_with(prefix)`.
    pub fn on_prefix<F>(
        &self,
        method: impl Into<Option<String>>,
        prefix: impl Into<String>,
        handler: F,
    ) where
        F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.state.lock().unwrap().prefix_routes.push((
            method.into(),
            prefix.into(),
            Arc::new(handler),
        ));
    }

    /// Registers an exact `GET` route handler.
    pub fn on_get<F>(&self, path: impl Into<String>, handler: F)
    where
        F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.on_route("GET".to_string(), path, handler);
    }

    /// Registers an exact `POST` route handler.
    pub fn on_post<F>(&self, path: impl Into<String>, handler: F)
    where
        F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.on_route("POST".to_string(), path, handler);
    }

    /// Registers an exact `PUT` route handler.
    pub fn on_put<F>(&self, path: impl Into<String>, handler: F)
    where
        F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.on_route("PUT".to_string(), path, handler);
    }

    /// Registers an exact `PATCH` route handler.
    pub fn on_patch<F>(&self, path: impl Into<String>, handler: F)
    where
        F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.on_route("PATCH".to_string(), path, handler);
    }

    /// Registers an exact `DELETE` route handler.
    pub fn on_delete<F>(&self, path: impl Into<String>, handler: F)
    where
        F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.on_route("DELETE".to_string(), path, handler);
    }

    /// Registers a prefix `GET` route handler.
    pub fn on_get_prefix<F>(&self, prefix: impl Into<String>, handler: F)
    where
        F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
    {
        self.on_prefix("GET".to_string(), prefix, handler);
    }

    /// Returns a snapshot of all recorded requests.
    pub fn recorded_requests(&self) -> Vec<RecordedRequest> {
        self.state.lock().unwrap().recorded.clone()
    }
}

impl Drop for MockServer {
    fn drop(&mut self) {
        self.handle.abort();
    }
}

async fn handle_connection(
    mut stream: TcpStream,
    state: Arc<Mutex<MockState>>,
) -> std::io::Result<()> {
    let mut buf = Vec::with_capacity(4096);
    let mut chunk = [0_u8; 2048];
    let header_end;

    loop {
        let n = stream.read(&mut chunk).await?;
        if n == 0 {
            return Ok(());
        }
        buf.extend_from_slice(&chunk[..n]);
        if let Some(pos) = find_header_end(&buf) {
            header_end = pos;
            break;
        }
    }

    let header_bytes = &buf[..header_end];
    let header_text = String::from_utf8_lossy(header_bytes);
    let mut lines = header_text.split("\r\n");
    let request_line = lines.next().unwrap_or_default();
    let mut parts = request_line.split_whitespace();
    let method = parts.next().unwrap_or("GET").to_string();
    let path = parts.next().unwrap_or("/").to_string();

    let mut headers = HashMap::new();
    let mut content_length: usize = 0;
    for line in lines {
        if let Some((k, v)) = line.split_once(':') {
            let key = k.trim().to_ascii_lowercase();
            let val = v.trim().to_string();
            if key == "content-length" {
                content_length = val.parse::<usize>().unwrap_or(0);
            }
            headers.insert(key, val);
        }
    }

    let body_start = header_end + 4;
    while buf.len() < body_start + content_length {
        let n = stream.read(&mut chunk).await?;
        if n == 0 {
            break;
        }
        buf.extend_from_slice(&chunk[..n]);
    }

    let body_end = (body_start + content_length).min(buf.len());
    let body = buf[body_start..body_end].to_vec();

    let recorded = RecordedRequest {
        method,
        path,
        headers,
        body,
    };

    let response = dispatch(&state, &recorded);
    write_response(&mut stream, &response).await
}

fn dispatch(state: &Arc<Mutex<MockState>>, req: &RecordedRequest) -> MockResponse {
    let handler_opt = {
        let mut guard = state.lock().unwrap();
        guard.recorded.push(req.clone());

        let exact = guard
            .routes
            .iter()
            .rev()
            .find(|(m, p, _)| {
                m.as_ref()
                    .is_none_or(|m| m.eq_ignore_ascii_case(&req.method))
                    && *p == req.path
            })
            .map(|(_, _, h)| Arc::clone(h));

        if exact.is_some() {
            exact
        } else {
            let prefix = guard
                .prefix_routes
                .iter()
                .rev()
                .find(|(m, p, _)| {
                    m.as_ref()
                        .is_none_or(|m| m.eq_ignore_ascii_case(&req.method))
                        && req.path.starts_with(p.as_str())
                })
                .map(|(_, _, h)| Arc::clone(h));

            if prefix.is_some() {
                prefix
            } else if let Some(resp) = guard.queued.pop_front() {
                return resp;
            } else {
                None
            }
        }
    };

    match handler_opt {
        Some(handler) => handler(req),
        None => MockResponse::text(
            404,
            format!("no mock route for {} {}", req.method, req.path),
        ),
    }
}

async fn write_response(stream: &mut TcpStream, resp: &MockResponse) -> std::io::Result<()> {
    let reason = status_reason(resp.status);

    let mut head = format!(
        "HTTP/1.1 {} {}\r\nContent-Length: {}\r\nConnection: close\r\n",
        resp.status,
        reason,
        resp.body.len()
    );
    for (k, v) in &resp.headers {
        let _ = write!(head, "{k}: {v}\r\n");
    }
    head.push_str("\r\n");

    stream.write_all(head.as_bytes()).await?;
    if !resp.body.is_empty() {
        stream.write_all(&resp.body).await?;
    }
    stream.flush().await
}

fn status_reason(code: u16) -> &'static str {
    match code {
        200 => "OK",
        201 => "Created",
        204 => "No Content",
        301 => "Moved Permanently",
        302 => "Found",
        307 => "Temporary Redirect",
        308 => "Permanent Redirect",
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not Found",
        429 => "Too Many Requests",
        500 => "Internal Server Error",
        502 => "Bad Gateway",
        503 => "Service Unavailable",
        _ => "OK",
    }
}

fn find_header_end(buf: &[u8]) -> Option<usize> {
    buf.windows(4).position(|w| w == b"\r\n\r\n")
}