geolith-dataset-builder 0.5.0

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
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
//! An in-process `S3` server for the tests: `std` only, no network.
//!
//! Speaks the subset the client uses — `PUT`/`GET`/`HEAD`/`DELETE` of one
//! object, `POST ?uploads`, `PUT ?partNumber&uploadId`, `POST ?uploadId`,
//! `DELETE ?uploadId` and `GET ?list-type=2&prefix` — and records every
//! request so a test can assert that a refusal wrote nothing.
//!
//! It answers the way R2 does where that matters to the client: a single
//! `PUT` has the md5 of its bytes as `ETag`, a multipart object has the md5 of
//! the concatenated part md5s and `-<parts>` (so a client that reads an
//! `ETag` as an md5 fails here too), `x-amz-meta-*` headers are kept and
//! returned by `HEAD`, and `If-None-Match: *` on a `PUT` or a
//! `CompleteMultipartUpload` is refused with 412 when the key exists. Three
//! switches reproduce the failures a real bucket shows: a `HEAD` that is
//! forbidden (403), a `HEAD` that does not see an object that is there (a
//! lagging read), and a part whose `ETag` is not the md5 of its bytes.

use std::collections::BTreeMap;
use std::io::{BufReader, Read as _, Write as _};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;

use md5::{Digest as _, Md5};

use super::S3;
use super::sigv4::Credentials;

/// The bucket of a server started without one.
const DEFAULT_BUCKET: &str = "test-bucket";

/// The state every connection shares.
#[derive(Default)]
struct State {
    bucket: String,
    objects: BTreeMap<String, Vec<u8>>,
    etags: BTreeMap<String, String>,
    metas: BTreeMap<String, BTreeMap<String, String>>,
    upload_metas: BTreeMap<String, BTreeMap<String, String>>,
    deny_head: bool,
    hide_from_head: bool,
    corrupt_part_etags: bool,
    uploads: BTreeMap<String, BTreeMap<u32, Vec<u8>>>,
    requests: Vec<(String, String)>,
    parts_seen: usize,
    next_upload: u32,
}

/// A running fake server: its address, state and accept thread.
pub struct FakeS3 {
    address: String,
    state: Arc<Mutex<State>>,
    thread: Option<JoinHandle<()>>,
    stop: Arc<AtomicU32>,
}

impl FakeS3 {
    /// Start a server on a free port of `127.0.0.1`, holding the bucket
    /// [`DEFAULT_BUCKET`].
    #[must_use]
    pub fn start() -> Self {
        Self::start_with_bucket(DEFAULT_BUCKET)
    }

    /// Start a server on a free port of `127.0.0.1`, holding `bucket`.
    #[must_use]
    pub fn start_with_bucket(bucket: &str) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").expect("binding the fake S3");
        let address = listener
            .local_addr()
            .expect("the fake S3's address")
            .to_string();
        let state = Arc::new(Mutex::new(State {
            bucket: bucket.to_owned(),
            ..State::default()
        }));
        let stop = Arc::new(AtomicU32::new(0));
        let shared = Arc::clone(&state);
        let flag = Arc::clone(&stop);
        let thread = std::thread::spawn(move || {
            for stream in listener.incoming() {
                if flag.load(Ordering::SeqCst) != 0 {
                    break;
                }
                let Ok(stream) = stream else { continue };
                let shared = Arc::clone(&shared);
                std::thread::spawn(move || {
                    let _ = handle(stream, &shared);
                });
            }
        });
        Self {
            address,
            state,
            thread: Some(thread),
            stop,
        }
    }

    /// The `host:port` the server listens on.
    #[must_use]
    pub fn address(&self) -> &str {
        &self.address
    }

    /// A client of the server's bucket.
    #[must_use]
    pub fn client(&self) -> S3 {
        let bucket = self.state.lock().expect("the fake state").bucket.clone();
        S3::new(
            &format!("http://{}", self.address),
            "test-region",
            &bucket,
            Credentials {
                key_id: "AKIAIOSFODNN7EXAMPLE".to_owned(),
                secret: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_owned(),
            },
        )
        .expect("the fake endpoint is a URL")
    }

    /// The objects stored, by key.
    #[must_use]
    pub fn objects(&self) -> BTreeMap<String, Vec<u8>> {
        self.state.lock().expect("the fake state").objects.clone()
    }

    /// How many individual parts were uploaded.
    #[must_use]
    pub fn multipart_parts_seen(&self) -> usize {
        self.state.lock().expect("the fake state").parts_seen
    }

    /// Make every `HEAD` and ranged `GET` answer 403, as a token that may
    /// write but not read does.
    pub fn deny_head(&self, on: bool) {
        self.state.lock().expect("the fake state").deny_head = on;
    }

    /// Make `HEAD` answer 404 for objects that exist, as a read that lags a
    /// write does.
    pub fn hide_from_head(&self, on: bool) {
        self.state.lock().expect("the fake state").hide_from_head = on;
    }

    /// Make every uploaded part answer an `ETag` that is not its md5.
    pub fn corrupt_part_etags(&self, on: bool) {
        self.state
            .lock()
            .expect("the fake state")
            .corrupt_part_etags = on;
    }

    /// The `ETag` the bucket holds for `key`.
    #[must_use]
    pub fn etag(&self, key: &str) -> Option<String> {
        self.state
            .lock()
            .expect("the fake state")
            .etags
            .get(key)
            .cloned()
    }

    /// The `x-amz-meta-*` pairs of `key`, names without the prefix.
    #[must_use]
    pub fn meta(&self, key: &str) -> BTreeMap<String, String> {
        self.state
            .lock()
            .expect("the fake state")
            .metas
            .get(key)
            .cloned()
            .unwrap_or_default()
    }

    /// Put `bytes` at `key` as a third-party tool would have: no metadata,
    /// and the `ETag` of a multipart upload with parts of `part_size` bytes
    /// (a plain md5 when `part_size` is `None`).
    pub fn plant(&self, key: &str, bytes: &[u8], part_size: Option<usize>) {
        let mut state = self.state.lock().expect("the fake state");
        let etag = match part_size {
            Some(size) => multipart_etag(bytes.chunks(size).map(etag_raw)),
            None => etag(bytes),
        };
        state.objects.insert(key.to_owned(), bytes.to_vec());
        state.etags.insert(key.to_owned(), etag);
        state.metas.remove(key);
    }

    /// Every request seen, as `(method, target)`.
    #[must_use]
    pub fn requests(&self) -> Vec<(String, String)> {
        self.state.lock().expect("the fake state").requests.clone()
    }

    /// Every write seen, as `(method, target)`.
    #[must_use]
    pub fn writes(&self) -> Vec<(String, String)> {
        self.requests()
            .into_iter()
            .filter(|(method, _)| matches!(method.as_str(), "PUT" | "POST" | "DELETE"))
            .collect()
    }
}

impl Drop for FakeS3 {
    fn drop(&mut self) {
        self.stop.store(1, Ordering::SeqCst);
        // Unblock the accept loop.
        let _ = TcpStream::connect(&self.address);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

/// One parsed request.
struct Request {
    method: String,
    path: String,
    query: BTreeMap<String, String>,
    headers: BTreeMap<String, String>,
    body: Vec<u8>,
}

/// Serve one connection: read a request, answer it, close.
fn handle(stream: TcpStream, state: &Arc<Mutex<State>>) -> std::io::Result<()> {
    let mut reader = BufReader::new(stream.try_clone()?);
    let Some(request) = read_request(&mut reader)? else {
        return Ok(());
    };
    let mut state = state.lock().expect("the fake state");
    state
        .requests
        .push((request.method.clone(), request.path.clone()));
    let response = answer(&request, &mut state);
    drop(state);
    let mut stream = stream;
    stream.write_all(&response)?;
    stream.flush()
}

/// Parse one request; `None` at a clean end of stream.
fn read_request(reader: &mut BufReader<TcpStream>) -> std::io::Result<Option<Request>> {
    let mut head = Vec::new();
    let mut byte = [0_u8; 1];
    loop {
        match reader.read(&mut byte) {
            Ok(0) => return Ok(None),
            Ok(_) => head.push(byte[0]),
            Err(error) => return Err(error),
        }
        if head.ends_with(b"\r\n\r\n") {
            break;
        }
    }
    let text = String::from_utf8_lossy(&head).into_owned();
    let mut lines = text.lines();
    let Some(request_line) = lines.next() else {
        return Ok(None);
    };
    let mut parts = request_line.split_whitespace();
    let method = parts.next().unwrap_or_default().to_owned();
    let target = parts.next().unwrap_or_default().to_owned();
    let (path, query) = match target.split_once('?') {
        Some((path, query)) => (path.to_owned(), parse_query(query)),
        None => (target, BTreeMap::new()),
    };
    let mut headers = BTreeMap::new();
    for line in lines {
        let Some((name, value)) = line.split_once(':') else {
            continue;
        };
        headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_owned());
    }
    let mut body = Vec::new();
    if let Some(length) = headers
        .get("content-length")
        .and_then(|text| text.parse::<usize>().ok())
    {
        body.resize(length, 0);
        reader.read_exact(&mut body)?;
    }
    Ok(Some(Request {
        method,
        path,
        query,
        headers,
        body,
    }))
}

/// Parse a query string into its decoded-ish pairs (the tests use plain ones).
fn parse_query(query: &str) -> BTreeMap<String, String> {
    query
        .split('&')
        .filter(|pair| !pair.is_empty())
        .map(|pair| match pair.split_once('=') {
            Some((key, value)) => (percent_decode(key), percent_decode(value)),
            None => (percent_decode(pair), String::new()),
        })
        .collect()
}

/// The decoded form of a percent-encoded query piece.
fn percent_decode(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'%'
            && index + 2 < bytes.len()
            && let Ok(value) = u8::from_str_radix(&text[index + 1..index + 3], 16)
        {
            out.push(value);
            index += 3;
            continue;
        }
        out.push(bytes[index]);
        index += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// The response bytes for `request`.
fn answer(request: &Request, state: &mut State) -> Vec<u8> {
    let key = request
        .path
        .strip_prefix(&format!("/{}", state.bucket))
        .map(|rest| rest.trim_start_matches('/').to_owned())
        .unwrap_or_default();
    if request
        .headers
        .get("x-amz-content-sha256")
        .is_none_or(|value| value.is_empty())
    {
        return response(403, "Missing x-amz-content-sha256", &[]);
    }
    let denied = state.deny_head
        && (request.method == "HEAD"
            || (request.method == "GET" && request.headers.contains_key("range")));
    if denied {
        return response(403, "Forbidden", &[]);
    }
    let meta = request_meta(request);
    let if_none_match_star = request
        .headers
        .get("if-none-match")
        .is_some_and(|value| value == "*");
    match request.method.as_str() {
        "HEAD" => match state.objects.get(&key) {
            Some(_) if state.hide_from_head => response(404, "Not Found", &[]),
            Some(object) => {
                let etag = state
                    .etags
                    .get(&key)
                    .cloned()
                    .unwrap_or_else(|| etag(object));
                let meta = state.metas.get(&key).cloned().unwrap_or_default();
                head_response(object.len(), &etag, &meta)
            }
            None => response(404, "Not Found", &[]),
        },
        "GET" if key.is_empty() => list_response(&request.query, state),
        "GET" => match state.objects.get(&key) {
            Some(object) => match request
                .headers
                .get("range")
                .and_then(|range| parse_range(range))
            {
                Some((start, end)) => {
                    let end = end.min(object.len().saturating_sub(1));
                    if start > end {
                        return response(416, "Bad Range", &[]);
                    }
                    response(206, "Partial Content", &object[start..=end])
                }
                None => response(200, "OK", object),
            },
            None => response(404, "Not Found", &[]),
        },
        "PUT" if request.query.contains_key("partNumber") => {
            let number = request
                .query
                .get("partNumber")
                .and_then(|text| text.parse::<u32>().ok())
                .unwrap_or_default();
            let Some(upload_id) = request.query.get("uploadId") else {
                return response(400, "No uploadId", &[]);
            };
            let parts = state.uploads.entry(upload_id.clone()).or_default();
            parts.insert(number, request.body.clone());
            state.parts_seen += 1;
            let etag = if state.corrupt_part_etags {
                "0".repeat(32)
            } else {
                etag(&request.body)
            };
            response_with_etag(200, "OK", &[], &etag)
        }
        "PUT" => {
            if if_none_match_star && state.objects.contains_key(&key) {
                return response(412, "Precondition Failed", &[]);
            }
            let etag = etag(&request.body);
            state.objects.insert(key.clone(), request.body.clone());
            state.etags.insert(key.clone(), etag.clone());
            state.metas.insert(key, meta);
            response_with_etag(200, "OK", &[], &etag)
        }
        "POST" if request.query.contains_key("uploads") => {
            state.next_upload += 1;
            let upload_id = format!("upload-{}", state.next_upload);
            state.uploads.insert(upload_id.clone(), BTreeMap::new());
            state.upload_metas.insert(upload_id.clone(), meta);
            let body = format!(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><InitiateMultipartUploadResult><UploadId>{upload_id}</UploadId></InitiateMultipartUploadResult>"
            );
            response(200, "OK", body.as_bytes())
        }
        "POST" => {
            let Some(upload_id) = request.query.get("uploadId") else {
                return response(400, "No uploadId", &[]);
            };
            let Some(parts) = state.uploads.remove(upload_id) else {
                return response(404, "No such upload", &[]);
            };
            if if_none_match_star && state.objects.contains_key(&key) {
                state.uploads.insert(upload_id.clone(), parts);
                return response(412, "Precondition Failed", &[]);
            }
            let upload_meta = state.upload_metas.remove(upload_id).unwrap_or_default();
            let etag = multipart_etag(parts.values().map(|part| etag_raw(part)));
            let mut object = Vec::new();
            for (_, part) in parts {
                object.extend_from_slice(&part);
            }
            state.objects.insert(key.clone(), object);
            state.etags.insert(key.clone(), etag);
            state.metas.insert(key, upload_meta);
            response(200, "OK", b"<CompleteMultipartUploadResult/>")
        }
        "DELETE" => {
            if let Some(upload_id) = request.query.get("uploadId") {
                state.uploads.remove(upload_id);
            }
            response(204, "No Content", &[])
        }
        other => response(405, &format!("Method {other}"), &[]),
    }
}

/// The `x-amz-meta-*` pairs of a request, names without the prefix.
fn request_meta(request: &Request) -> BTreeMap<String, String> {
    request
        .headers
        .iter()
        .filter_map(|(name, value)| {
            name.strip_prefix("x-amz-meta-")
                .map(|name| (name.to_owned(), value.clone()))
        })
        .collect()
}

/// A `HEAD` answer for an object of `len` bytes, with its `ETag` and
/// metadata.
fn head_response(len: usize, etag: &str, meta: &BTreeMap<String, String>) -> Vec<u8> {
    let mut head = format!("HTTP/1.1 200 OK\r\nContent-Length: {len}\r\nETag: \"{etag}\"\r\n");
    for (name, value) in meta {
        head.push_str(&format!("x-amz-meta-{name}: {value}\r\n"));
    }
    head.push_str("Connection: close\r\n\r\n");
    head.into_bytes()
}

/// A listing of the objects under `prefix`.
fn list_response(query: &BTreeMap<String, String>, state: &State) -> Vec<u8> {
    let prefix = query.get("prefix").map(String::as_str).unwrap_or_default();
    let mut body = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListBucketResult>");
    for (key, object) in &state.objects {
        if key.starts_with(prefix) {
            body.push_str(&format!(
                "<Contents><Key>{key}</Key><Size>{}</Size></Contents>",
                object.len()
            ));
        }
    }
    body.push_str("</ListBucketResult>");
    response(200, "OK", body.as_bytes())
}

/// `bytes=start-end` or `bytes=start-`.
fn parse_range(value: &str) -> Option<(usize, usize)> {
    let rest = value.strip_prefix("bytes=")?.split(',').next()?;
    let (start, end) = rest.split_once('-')?;
    let start = start.parse::<usize>().ok()?;
    let end = if end.is_empty() {
        usize::MAX
    } else {
        end.parse::<usize>().ok()?
    };
    Some((start, end))
}

/// The `md5` of `bytes` as lower-case hex.
fn etag(bytes: &[u8]) -> String {
    use std::fmt::Write as _;
    let digest = Md5::digest(bytes);
    digest.iter().fold(String::new(), |mut out, byte| {
        let _ = write!(out, "{byte:02x}");
        out
    })
}

/// The raw md5 of `bytes`.
fn etag_raw(bytes: &[u8]) -> [u8; 16] {
    Md5::digest(bytes).into()
}

/// The `ETag` of a multipart object: the md5 of the concatenated part md5s,
/// then `-` and the number of parts.
fn multipart_etag(part_md5s: impl Iterator<Item = [u8; 16]>) -> String {
    use std::fmt::Write as _;
    let mut all = Vec::new();
    let mut count = 0_usize;
    for md5 in part_md5s {
        all.extend_from_slice(&md5);
        count += 1;
    }
    let mut out = etag(&all);
    let _ = write!(out, "-{count}");
    out
}

/// A response with `body` and a content type.
fn response(status: u16, reason: &str, body: &[u8]) -> Vec<u8> {
    let head = format!(
        "HTTP/1.1 {status} {reason}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
        body.len()
    );
    let mut out = head.into_bytes();
    out.extend_from_slice(body);
    out
}

/// A response carrying an `ETag`.
fn response_with_etag(status: u16, reason: &str, body: &[u8], etag: &str) -> Vec<u8> {
    let head = format!(
        "HTTP/1.1 {status} {reason}\r\nContent-Length: {}\r\nETag: \"{etag}\"\r\nConnection: close\r\n\r\n",
        body.len()
    );
    let mut out = head.into_bytes();
    out.extend_from_slice(body);
    out
}