footing 0.6.4

Feature-gated foundations for Rust backend services
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
use axum::{
    Json, Router,
    http::StatusCode,
    response::IntoResponse,
    routing::{get, post},
};
use serde_json::json;

use super::*;
use crate::{http::ApiProblem, observability::MetricLabels};

#[test]
#[cfg(feature = "postgres")]
fn postgres_database_name_replacement_preserves_dot_names_and_overrides_dbname() {
    for name in [".", "..", "test/db ?#%", "app"] {
        for base in [
            "postgres://user:pass@localhost/base?sslmode=require#fragment",
            "postgres://user:pass@localhost/base?dbname=old&sslmode=require&dbname=older#fragment",
        ] {
            let replaced = postgres::database_url_with_name(base, name).unwrap();
            assert_eq!(
                crate::db::postgres::database_name(&replaced).as_deref(),
                Some(name)
            );
            let url = url::Url::parse(&replaced).unwrap();
            assert_eq!(url.username(), "user");
            assert_eq!(url.password(), Some("pass"));
            assert_eq!(url.host_str(), Some("localhost"));
            assert_eq!(url.fragment(), Some("fragment"));
            assert!(
                url.query_pairs()
                    .any(|(key, value)| key == "sslmode" && value == "require")
            );
            assert!(url.query_pairs().filter(|(key, _)| key == "dbname").count() <= 1);
        }
    }
}

#[test]
#[cfg(feature = "postgres")]
fn postgres_database_name_replacement_preserves_url_components() {
    for base in [
        "postgres://user:pass@localhost/base?sslmode=verify-full",
        "postgresql://user:pass@[::1]:5432/base?sslrootcert=/etc/ssl/root.crt#fragment",
        "postgres://localhost?application_name=test",
        "postgres://user:p%2Fass@localhost/base",
    ] {
        let original = url::Url::parse(base).unwrap();
        let replaced = postgres::database_url_with_name(base, "test/db ?#%").unwrap();
        let replaced = url::Url::parse(&replaced).unwrap();
        assert_eq!(replaced.query(), original.query());
        assert_eq!(replaced.fragment(), original.fragment());
        assert_eq!(replaced.username(), original.username());
        assert_eq!(replaced.password(), original.password());
        assert_eq!(replaced.host_str(), original.host_str());
        assert_eq!(replaced.port(), original.port());
        assert_eq!(replaced.path(), "/test%2Fdb%20%3F%23%25");
    }
}

#[test]
#[cfg(feature = "postgres")]
fn postgres_database_name_replacement_isolates_opaque_urls() {
    use std::str::FromStr;

    for base in [
        "postgres:production",
        "postgresql:production?application_name=test#fragment",
        "postgres:production?dbname=first&sslmode=require&dbname=second",
    ] {
        crate::db::postgres::PostgresBootstrapSettings::new(base)
            .build()
            .expect("SQLx-supported opaque URLs are valid Footing inputs");
        for name in ["isolated_test", ".", "..", "test/db ?#%", "quoted\"name"] {
            let replaced = postgres::database_url_with_name(base, name).unwrap();
            assert_eq!(
                crate::db::postgres::database_name(&replaced).as_deref(),
                Some(name)
            );
            let options = sqlx::postgres::PgConnectOptions::from_str(&replaced).unwrap();
            assert_eq!(options.get_database(), Some(name));
            let original = url::Url::parse(base).unwrap();
            let rewritten = url::Url::parse(&replaced).unwrap();
            assert_eq!(original.fragment(), rewritten.fragment());
            assert_eq!(
                rewritten
                    .query_pairs()
                    .filter(|(key, _)| key == "dbname")
                    .count(),
                1
            );
            for option in original.query_pairs().filter(|(key, _)| key != "dbname") {
                assert!(rewritten.query_pairs().any(|value| value == option));
            }
        }
    }
}

#[test]
#[cfg(feature = "postgres")]
fn postgres_database_name_replacement_rejects_invalid_inputs() {
    for base in [
        "not-a-url",
        "https://localhost/production",
        "sqlite::memory:",
        "postgres://[",
        "postgres://localhost/production?application_name=test%00database%00production",
        "postgres://localhost/production?options[search_path%00database]=public",
        "postgres://user%00application_name%00test@localhost/production",
        "postgres://localhost/production?application_name=test%0\n0database%0\t0production",
    ] {
        assert!(matches!(
            postgres::database_url_with_name(base, "isolated_test"),
            Err(TestkitError::InvalidPostgresUrl)
        ));
    }
    for name in [
        "",
        "  ",
        "name\0suffix",
        "name\nsuffix",
        &"a".repeat(64),
        &"库".repeat(22),
    ] {
        assert!(matches!(
            postgres::database_url_with_name("postgres://localhost/production", name),
            Err(TestkitError::InvalidDatabaseName)
        ));
    }
}

#[test]
fn test_metrics_records_samples() {
    let metrics = TestMetrics::new();
    metrics
        .recorder()
        .increment_counter("jobs_total", 1, MetricLabels::default())
        .expect("metric should record");

    let snapshot = metrics.snapshot().expect("snapshot should build");
    assert_eq!(snapshot.samples().len(), 1);
    assert_eq!(snapshot.samples()[0].name(), "jobs_total");
    metrics.assert_counter("jobs_total", MetricLabels::default(), 1);
    metrics.assert_counter_at_least("jobs_total", MetricLabels::default(), 1);
    metrics.assert_no_metric("missing_total", MetricLabels::default());
}

#[tokio::test]
async fn test_http_app_runs_requests() {
    let app = TestHttpApp::new(Router::new().route("/health", get(|| async { "ok" })));

    let response = app.get("/health").await;

    assert_eq!(response.status(), StatusCode::OK);
}

#[test]
fn test_http_request_builder_sets_standard_headers() {
    let request = TestHttpRequestBuilder::get("/secure")
        .header("x-custom", "custom-value")
        .header(
            axum::http::header::ACCEPT,
            axum::http::HeaderValue::from_static("application/json"),
        )
        .bearer("token")
        .request_id("req_test")
        .traceparent(traceparent().into_string())
        .build();

    assert_eq!(
        request
            .headers()
            .get(axum::http::header::AUTHORIZATION)
            .and_then(|value| value.to_str().ok()),
        Some("Bearer token")
    );
    assert_eq!(
        request
            .headers()
            .get("x-request-id")
            .and_then(|value| value.to_str().ok()),
        Some("req_test")
    );
    assert!(request.headers().get("traceparent").is_some());
    assert_eq!(request.headers()["x-custom"], "custom-value");
    assert_eq!(
        request.headers()[axum::http::header::ACCEPT],
        "application/json"
    );
}

#[test]
fn invalid_test_headers_fail_request_building() {
    use std::error::Error;

    for request in [
        TestHttpRequestBuilder::get("/")
            .bearer("invalid\r\nheader")
            .request_id("valid"),
        TestHttpRequestBuilder::get("/").header("invalid header name", "value"),
    ] {
        let error = request.try_build().unwrap_err();
        assert!(matches!(error, TestkitError::RequestBuild(_)));
        assert!(error.source().unwrap().is::<axum::http::Error>());
    }
}

#[tokio::test]
async fn try_response_problem_returns_status_mismatch() {
    let response = axum::http::Response::builder()
        .status(StatusCode::OK)
        .header(axum::http::header::CONTENT_TYPE, "application/problem+json")
        .body(axum::body::Body::from(
            serde_json::to_string(
                &ApiProblem::bad_request(
                    crate::http::ProblemCode::try_new("invalid_request").unwrap(),
                    "invalid request",
                )
                .into_body(),
            )
            .unwrap(),
        ))
        .unwrap();
    assert!(matches!(
        try_response_problem(response).await,
        Err(TestkitError::ResponseStatusMismatch {
            http_status: 200,
            problem_status: 400,
        })
    ));
}

#[tokio::test]
async fn try_response_problem_accepts_media_type_case_and_parameters() {
    for value in [
        "application/problem+json",
        "Application/Problem+JSON",
        "application/problem+json; charset=utf-8",
        "application/problem+json; charset=\"UTF-8\"; profile=\"test; profile\"",
        " \tapplication/problem+json \t",
    ] {
        let mut response = ApiProblem::bad_request(
            crate::http::ProblemCode::from_static("invalid_request"),
            "invalid request",
        )
        .into_response();
        response
            .headers_mut()
            .insert(axum::http::header::CONTENT_TYPE, value.parse().unwrap());
        let problem = try_response_problem(response).await.unwrap();
        assert_eq!(problem.status(), 400);
        assert_eq!(problem.code(), "invalid_request");
    }
}

#[tokio::test]
async fn try_response_problem_rejects_missing_or_invalid_content_type() {
    for value in [
        None,
        Some("application/json"),
        Some("text/problem+json"),
        Some("application/problem+xml"),
        Some("application/problem+json-extra"),
        Some("application/problem+json, application/problem+json"),
        Some("application/problem+json; charset=\"unterminated"),
        Some("application/problem+json; invalid parameter=value"),
        Some(""),
    ] {
        let mut response = ApiProblem::bad_request(
            crate::http::ProblemCode::from_static("invalid_request"),
            "invalid request",
        )
        .into_response();
        response
            .headers_mut()
            .remove(axum::http::header::CONTENT_TYPE);
        if let Some(value) = value {
            response
                .headers_mut()
                .insert(axum::http::header::CONTENT_TYPE, value.parse().unwrap());
        }
        assert!(
            matches!(
                try_response_problem(response).await,
                Err(TestkitError::ResponseContentType)
            ),
            "unexpected acceptance of Content-Type {value:?}"
        );
    }
}

#[tokio::test]
async fn try_response_problem_rejects_non_ascii_and_duplicate_content_types() {
    let mut response = ApiProblem::bad_request(
        crate::http::ProblemCode::from_static("invalid_request"),
        "invalid request",
    )
    .into_response();
    response.headers_mut().insert(
        axum::http::header::CONTENT_TYPE,
        axum::http::HeaderValue::from_bytes(b"application/problem+json; charset=\xff").unwrap(),
    );
    assert!(matches!(
        try_response_problem(response).await,
        Err(TestkitError::ResponseContentType)
    ));

    for second in ["application/problem+json", "application/json"] {
        let mut response = ApiProblem::bad_request(
            crate::http::ProblemCode::from_static("invalid_request"),
            "invalid request",
        )
        .into_response();
        response
            .headers_mut()
            .append(axum::http::header::CONTENT_TYPE, second.parse().unwrap());
        assert!(matches!(
            try_response_problem(response).await,
            Err(TestkitError::ResponseContentType)
        ));
    }
}

#[tokio::test]
#[should_panic(
    expected = "problem response must have exactly one application/problem+json Content-Type"
)]
async fn assert_response_problem_rejects_wrong_content_type() {
    let mut response = ApiProblem::bad_request(
        crate::http::ProblemCode::from_static("invalid_request"),
        "invalid request",
    )
    .into_response();
    response.headers_mut().insert(
        axum::http::header::CONTENT_TYPE,
        axum::http::HeaderValue::from_static("application/json"),
    );
    assert_response_problem(response, StatusCode::BAD_REQUEST, "invalid_request").await;
}

#[tokio::test]
async fn test_http_app_decodes_json_responses() {
    let app = TestHttpApp::new(Router::new().route(
        "/echo",
        post(|Json(value): Json<serde_json::Value>| async move { Json(value) }),
    ));

    let response = app.post_json("/echo", &json!({ "ok": true })).await;
    let body: serde_json::Value = assert_response_json(response, StatusCode::OK).await;

    assert_eq!(body, json!({ "ok": true }));
}

#[tokio::test]
async fn response_problem_assertion_preserves_details() {
    let code = crate::http::ProblemCode::try_new("invalid_input")
        .expect("test problem code should be valid");
    let response = ApiProblem::bad_request(code, "bad input")
        .with_request_id(&test_request_id("req_test"))
        .into_response();

    let problem = assert_response_problem(response, StatusCode::BAD_REQUEST, "invalid_input").await;
    assert_eq!(problem.detail(), "bad input");
    assert_eq!(problem.request_id(), Some("req_test"));
}

#[test]
fn settings_validation_assertion_checks_issue_paths() {
    let mut issues = crate::settings::SettingsIssues::new();
    issues.push("server.http.timeout", "must be greater than zero");
    issues.push("server.http.timeout", "must be below the shutdown timeout");
    issues.push("server.http.port", "must fit in u16");
    let error = crate::settings::SettingsValidationError::new(issues);

    let _error = assert_settings_error(&error)
        .issue_count(3)
        .has_path("server.http.timeout")
        .path_message_contains("server.http.timeout", "greater")
        .path_message_contains("server.http.timeout", "below")
        .into_inner();

    for (path, message) in [
        ("server.http.timeout", "u16"),
        ("server.http.timeout", "missing message"),
        ("server.http.unknown", "greater"),
    ] {
        assert!(
            std::panic::catch_unwind(|| {
                let _ = assert_settings_error(&error).path_message_contains(path, message);
            })
            .is_err()
        );
    }
}

#[tokio::test]
async fn testkit_outbox_persists_fixture_outcomes_and_dead_letters() {
    use std::time::Duration;

    use crate::worker::{BatchWorkerJob, OutboxItemState};

    let retry = OutboxItemState::retry("temporary failure", Duration::from_secs(9));

    let store = worker::TestOutboxStore::with_items([
        worker::TestOutboxItem::succeeded("ok"),
        worker::TestOutboxItem::failed("one", "terminal failure").with_attempts(100),
        worker::TestOutboxItem::skipped("skipped", "not needed"),
        worker::TestOutboxItem::failed("two", "other failure").with_attempts(100),
        worker::TestOutboxItem::new("retry", worker::TestOutboxAction::Return(retry.clone())),
        worker::TestOutboxItem::handler_error("error", "handler failure"),
        worker::TestOutboxItem::slow("slow", Duration::ZERO),
    ]);
    let job = crate::worker::OutboxJob::new(
        "test outbox",
        store.clone(),
        worker::TestOutboxHandler,
        crate::worker::OutboxWorkerSettings::default()
            .with_batch_size(10)
            .build()
            .expect("test outbox settings should be valid"),
    );

    let summary = job
        .run_batch(crate::worker::WorkerContext::default())
        .await
        .expect("outbox should run");

    assert_eq!(summary.succeeded(), 2);
    assert_eq!(summary.skipped(), 1);
    assert_eq!(summary.failed(), 2);
    assert_eq!(summary.dead_lettered(), 2);
    assert_eq!(summary.retrying(), 2);
    let states = store.states();
    assert_eq!(states.len(), 7);
    assert_eq!(states[4], ("retry".to_owned(), retry));
    assert!(matches!(
        &states[5].1,
        OutboxItemState::Retry { reason, .. } if reason == "outbox_handler_failed"
    ));
    assert_eq!(
        store.dead_letters(),
        vec![
            ("one".to_owned(), "terminal failure".to_owned()),
            ("two".to_owned(), "other failure".to_owned()),
        ]
    );
}

#[tokio::test]
async fn testkit_outbox_claims_only_available_items_up_to_the_limit() {
    use crate::worker::{OutboxClaim, OutboxStore, WorkerContext};
    use std::time::Duration;

    let first = worker::TestOutboxItem::succeeded("first");
    let second = worker::TestOutboxItem::succeeded("second");
    let store = worker::TestOutboxStore::with_items([first.clone(), second.clone()]);
    for (limit, expected) in [
        (0, vec![]),
        (1, vec![first]),
        (u32::MAX, vec![second]),
        (u32::MAX, vec![]),
    ] {
        assert_eq!(
            store
                .claim_due(
                    OutboxClaim::new(limit, Duration::from_secs(1)),
                    WorkerContext::default()
                )
                .await
                .unwrap(),
            expected,
        );
    }
}