Skip to content

Commit e794df0

Browse files
committed
Derive the configuration reference from Rust settings
1 parent d7e1c35 commit e794df0

9 files changed

Lines changed: 323 additions & 138 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ jobs:
6363
shared-key: rust-sqlpage-proj-test
6464
save-if: ${{ github.ref == 'refs/heads/main' }}
6565
- run: cargo fmt --all -- --check
66+
- run: cargo test --locked --features config-schema --test mod configuration_docs
6667
- run: cargo clippy --all-targets --all-features -- -D warnings
6768
# The database matrix below runs the same Rust test harnesses against
6869
# different DATABASE_URL values. Package the Linux test executables once

‎Cargo.lock‎

Lines changed: 25 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ tokio = { version = "1.24.1", features = ["macros", "rt", "process", "sync"] }
6262
tokio-stream = "0.1.9"
6363
anyhow = "1"
6464
serde = "1"
65+
schemars = { version = "1", optional = true }
6566
serde_json = { version = "1.0.82", features = [
6667
"preserve_order",
6768
"raw_value",
@@ -137,6 +138,7 @@ opentelemetry-semantic-conventions = { version = "0.33", features = ["semconv_ex
137138

138139
[features]
139140
default = []
141+
config-schema = ["dep:schemars"]
140142
odbc-static = ["odbc-sys", "odbc-sys/vendored-unix-odbc"]
141143
lambda-web = [
142144
"dep:actix-http",
@@ -151,3 +153,7 @@ actix-http = "3"
151153
tempfile = "3"
152154
tokio = { version = "1", features = ["rt", "time", "test-util"] }
153155

156+
[[example]]
157+
name = "export_config_schema"
158+
required-features = ["config-schema"]
159+

‎examples/export_config_schema.rs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
use schemars::generate::SchemaSettings;
2+
use sqlpage::app_config::AppConfig;
3+
use std::io::{self, Write};
4+
5+
fn main() -> anyhow::Result<()> {
6+
let settings =
7+
SchemaSettings::draft2020_12().with(|settings| settings.inline_subschemas = true);
8+
let schema = settings
9+
.into_generator()
10+
.into_root_schema_for::<AppConfig>();
11+
let mut stdout = io::stdout().lock();
12+
serde_json::to_writer_pretty(&mut stdout, &schema)?;
13+
writeln!(stdout)?;
14+
Ok(())
15+
}

‎src/app_config.rs‎

Lines changed: 161 additions & 108 deletions
Large diffs are not rendered by default.

‎src/app_config/schema.rs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
use super::{CERTIFICATE_CACHE_DIRECTORY, Duration};
2+
use crate::webserver::database::default_max_connections;
3+
use schemars::Schema;
4+
use serde_json::Value;
5+
use sqlx::any::AnyKind;
6+
7+
pub(super) fn working_directory() -> &'static str {
8+
"."
9+
}
10+
11+
pub(super) fn certificate_cache_directory() -> &'static str {
12+
CERTIFICATE_CACHE_DIRECTORY
13+
}
14+
15+
pub(super) fn timeout(duration: Duration) -> String {
16+
format!(
17+
"Disabled for SQLite, {} seconds for other databases.",
18+
duration.as_secs()
19+
)
20+
}
21+
22+
pub(super) fn pool_sizes() -> String {
23+
[
24+
("PostgreSQL", AnyKind::Postgres, false),
25+
("MySQL", AnyKind::MySql, false),
26+
("SQLite on disk", AnyKind::Sqlite, false),
27+
("SQLite in memory", AnyKind::Sqlite, true),
28+
("MSSQL", AnyKind::Mssql, false),
29+
("ODBC", AnyKind::Odbc, false),
30+
]
31+
.map(|(label, kind, memory)| format!("{label} {}", default_max_connections(kind, memory)))
32+
.join(", ")
33+
}
34+
35+
/// JSON Schema defaults represent a single value supplied when the property is omitted.
36+
/// Conditional defaults have a human-readable description, and optional settings can be unset.
37+
pub(super) fn remove_unset_defaults(schema: &mut Schema) {
38+
if let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) {
39+
for field in properties.values_mut().filter_map(Value::as_object_mut) {
40+
if field.contains_key("x-default-description")
41+
|| field.get("default") == Some(&Value::Null)
42+
{
43+
field.remove("default");
44+
}
45+
}
46+
}
47+
}

‎src/webserver/database/connect.rs‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -104,20 +104,17 @@ where
104104
}
105105

106106
fn max_connections(config: &AppConfig, kind: AnyKind) -> u32 {
107-
if let Some(max) = config.max_database_pool_connections {
108-
return max;
109-
}
110-
// Different databases have a different number of max concurrent connections allowed by default
107+
config
108+
.max_database_pool_connections
109+
.unwrap_or_else(|| default_max_connections(kind, config.database_url.contains(":memory:")))
110+
}
111+
112+
pub(crate) fn default_max_connections(kind: AnyKind, in_memory: bool) -> u32 {
111113
match kind {
112114
AnyKind::Postgres | AnyKind::Odbc => 50, // Default to PostgreSQL-like limits for Generic
113115
AnyKind::MySql => 75,
114-
AnyKind::Sqlite => {
115-
if config.database_url.contains(":memory:") {
116-
128
117-
} else {
118-
16
119-
}
120-
}
116+
AnyKind::Sqlite if in_memory => 128,
117+
AnyKind::Sqlite => 16,
121118
AnyKind::Mssql => 100,
122119
}
123120
}

‎src/webserver/database/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ mod sqlpage_functions;
1010
mod error_highlighting;
1111
mod sql_to_json;
1212

13+
#[cfg(feature = "config-schema")]
14+
pub(crate) use connect::default_max_connections;
1315
pub use sql::SqlFile;
1416
use sqlx::any::AnyKind;
1517
// SupportedDatabase is defined in this module

‎tests/configuration_docs/mod.rs‎

Lines changed: 58 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,71 @@
1+
#![cfg(feature = "config-schema")]
2+
3+
use schemars::schema_for;
14
use serde::Deserialize;
25
use serde::de::value::Error as DeError;
36
use serde::de::{Deserializer, Visitor};
7+
use serde_json::json;
48
use sqlpage::app_config::AppConfig;
59
use std::collections::BTreeSet;
610

711
#[test]
8-
fn configuration_md_documents_every_option() {
9-
let documented = documented_option_names();
10-
let implemented = app_config_option_names();
11-
12-
let undocumented: Vec<_> = implemented.difference(&documented).collect();
13-
let unimplemented: Vec<_> = documented.difference(&implemented).collect();
14-
15-
assert!(
16-
undocumented.is_empty() && unimplemented.is_empty(),
17-
"configuration.md and AppConfig disagree.\n\
18-
Missing from configuration.md: {undocumented:?}\n\
19-
Documented but not in AppConfig: {unimplemented:?}"
12+
fn every_public_setting_has_a_description() {
13+
let schema = schema_for!(AppConfig);
14+
let properties = schema.get("properties").unwrap().as_object().unwrap();
15+
assert_eq!(
16+
properties.keys().cloned().collect::<BTreeSet<_>>(),
17+
app_config_option_names()
2018
);
19+
for (name, property) in properties {
20+
assert!(
21+
property["description"]
22+
.as_str()
23+
.is_some_and(|text| !text.trim().is_empty()),
24+
"{name} needs a Rust doc comment"
25+
);
26+
}
2127
}
2228

23-
fn documented_option_names() -> BTreeSet<String> {
24-
let table = std::fs::read_to_string("configuration.md").unwrap();
25-
table
26-
.lines()
27-
.filter_map(|line| line.strip_prefix("| `")?.split('`').next())
28-
.map(str::to_owned)
29-
.collect()
29+
#[test]
30+
fn schema_documents_input_types_and_effective_defaults() {
31+
let schema = schema_for!(AppConfig);
32+
let properties = schema.get("properties").unwrap();
33+
let timeout = &properties["database_connection_idle_timeout_seconds"];
34+
assert_eq!(timeout["type"], json!(["number", "null"]));
35+
assert!(
36+
timeout["x-default-description"]
37+
.as_str()
38+
.unwrap()
39+
.contains("SQLite")
40+
);
41+
assert!(timeout.get("default").is_none());
42+
assert_eq!(properties["site_prefix"]["default"], "/");
43+
assert_eq!(properties["smtp_tls_mode"]["default"], "starttls");
44+
assert_eq!(properties["web_root"]["default"], ".");
45+
assert_eq!(
46+
properties["configuration_directory"]["default"],
47+
"./sqlpage"
48+
);
49+
assert_eq!(properties["content_security_policy"]["type"], "string");
50+
assert!(
51+
properties["content_security_policy"]["default"]
52+
.as_str()
53+
.unwrap()
54+
.contains("{NONCE}")
55+
);
56+
assert!(
57+
properties["system_root_ca_certificates"]
58+
.get("default")
59+
.is_none()
60+
);
61+
assert!(properties["database_url"].get("default").is_none());
62+
assert_eq!(properties["oidc_public_paths"]["default"], json!([]));
63+
assert!(
64+
properties["oidc_additional_trusted_audiences"]
65+
.get("default")
66+
.is_none()
67+
);
68+
assert!(schema.get("required").is_none());
3069
}
3170

3271
fn app_config_option_names() -> BTreeSet<String> {

0 commit comments

Comments
 (0)