Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

- On Unix, errors from Git and Jujutsu commands, including reading Git stub contents, now report `exit code: N` instead of `exit status: N`, matching Windows.
- If a blessed version's local files are corrupted, the fixes now mention every corrupted file that is removed or replaced. If both the `.json` and `.json.gitstub` files are corrupted, it is now represented as a single problem.
- When a blessed version fails validation, the check output now includes a `help:` line explaining that blessed documents can't be changed and that the fix is to add a new API version. For older blessed versions, it also explains how to skip particular validation rules, i.e. to only enforce them when `cx.is_latest() || cx.is_blessed() != Some(true)`.
- Updated git-stub-vcs to 0.1.1.

## [0.9.0] - 2026-10-30
Expand Down
35 changes: 28 additions & 7 deletions crates/dropshot-api-manager/src/apis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,6 @@ pub struct ManagedApi {
fn() -> Result<ApiDescription<StubContext>, ApiDescriptionBuildErrors>,

/// Extra validation to perform on the OpenAPI document, if any.
///
/// For versioned APIs, extra validation is performed on *all* versions,
/// including blessed ones. You may want to skip performing validation on
/// blessed versions, though, because they're immutable. To do so, use
/// [`ValidationContext::is_blessed`].
extra_validation: Option<Box<DynValidationFn>>,

/// If true, allow trivial changes (doc updates, type renames) for the
Expand Down Expand Up @@ -222,8 +217,19 @@ impl ManagedApi {
///
/// For versioned APIs, extra validation is performed on *all* versions,
/// including blessed ones. You may want to skip performing validation on
/// blessed versions, though, because they're immutable. To do so, use
/// [`ValidationContext::is_blessed`].
/// older blessed versions, though, because they're immutable, while still
/// performing validation on the latest blessed version (and recommending
/// that a new version be created instead). To do so, use the pattern:
///
/// ```
/// # use dropshot_api_manager_types::ValidationContext;
/// # use openapiv3::OpenAPI;
/// fn validate(doc: &OpenAPI, cx: ValidationContext<'_>) {
/// if cx.is_latest() || cx.is_blessed() != Some(true) {
/// // Perform validation.
/// }
/// }
/// ```
pub fn with_extra_validation<F>(mut self, f: F) -> Self
where
F: Fn(&OpenAPI, ValidationContext<'_>) + Send + Sync + 'static,
Expand Down Expand Up @@ -374,6 +380,21 @@ impl ManagedApis {
/// This function will be called for each API document. The
/// [`ValidationContext`] can be used to report errors, as well as extra
/// files for which the contents need to be compared with those on disk.
///
/// You may want to skip performing validation on older blessed versions
/// because they're immutable, while still performing validation on the
/// latest blessed version (and recommending that a new version be created
/// instead). To do so, use the pattern:
///
/// ```
/// # use dropshot_api_manager_types::ValidationContext;
/// # use openapiv3::OpenAPI;
/// fn validate(doc: &OpenAPI, cx: ValidationContext<'_>) {
/// if cx.is_latest() || cx.is_blessed() != Some(true) {
/// // Perform validation.
/// }
/// }
/// ```
pub fn with_validation<F>(mut self, validation: F) -> Self
where
F: Fn(&OpenAPI, ValidationContext<'_>) + Send + Sync + 'static,
Expand Down
24 changes: 24 additions & 0 deletions crates/dropshot-api-manager/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,10 @@ where
)?;
}

if let Some(help) = p.help() {
write_help(writer, &help, styles)?;
}

let Some(fix) = p.fix() else {
continue;
};
Expand Down Expand Up @@ -721,6 +725,26 @@ fn write_problem_header(
)
}

fn write_help(
writer: &mut dyn io::Write,
help: &str,
styles: &Styles,
) -> io::Result<()> {
let first_indent =
format!("{:>HEADER_WIDTH$}: ", "help".style(styles.header));
let more_indent = " ".repeat(HEADER_WIDTH + 2);
writeln!(
writer,
"{}",
textwrap::fill(
help,
textwrap::Options::new(term_width())
.initial_indent(&first_indent)
.subsequent_indent(&more_indent)
)
)
}

/// Write the `fix:` line(s) for a single fix, splitting multi-step fixes into
/// separate `will ...` lines that share the column structure of
/// [`write_problem_header`].
Expand Down
92 changes: 92 additions & 0 deletions crates/dropshot-api-manager/src/resolved.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,7 @@ pub enum VersionProblem<'a> {
GeneratedValidationError {
api_ident: ApiIdent,
version: semver::Version,
blessed_help: Option<BlessedValidationHelp>,
#[source]
source: anyhow::Error,
},
Expand Down Expand Up @@ -572,6 +573,41 @@ impl<'a> VersionProblem<'a> {
self.fix().is_some()
}

pub(crate) fn help(&self) -> Option<String> {
// This is an exhaustive match so new variants cause a compile error.
match self {
VersionProblem::GeneratedValidationError {
version,
blessed_help: Some(help),
..
} => Some(help.message(version)),
VersionProblem::GeneratedValidationError {
blessed_help: None,
..
}
| VersionProblem::BlessedVersionNeedsRestore { .. }
| VersionProblem::BlessedVersionRestoreBlocked { .. }
| VersionProblem::BlessedVersionExtraLocalDoc { .. }
| VersionProblem::BlessedVersionCompareError { .. }
| VersionProblem::BlessedVersionBroken { .. }
| VersionProblem::BlessedLatestVersionBytewiseMismatch { .. }
| VersionProblem::LockstepMissingLocal { .. }
| VersionProblem::LockstepStale { .. }
| VersionProblem::LocalVersionMissingLocal { .. }
| VersionProblem::LocalVersionExtra { .. }
| VersionProblem::LocalVersionStale { .. }
| VersionProblem::LocalVersionGitStub { .. }
| VersionProblem::GeneratedSourceMissing { .. }
| VersionProblem::ExtraFileStale { .. }
| VersionProblem::BlessedVersionShouldBeGitStub { .. }
| VersionProblem::GitStubShouldBeJson { .. }
| VersionProblem::BlessedVersionCorruptedExtra { .. }
| VersionProblem::DuplicateLocalFile { .. }
| VersionProblem::GitStubCommitStale { .. }
| VersionProblem::GitStubFirstCommitUnknown { .. } => None,
}
}

pub(crate) fn compatibility_issues(&self) -> &[ApiCompatIssue] {
// Exhaustive match to ensure new variants cause a compile error.
match self {
Expand Down Expand Up @@ -2353,9 +2389,16 @@ fn validate_generated(
generated,
) {
Err(source) => {
let blessed_help = match version.is_blessed {
None | Some(false) => None,
Some(true) => {
Some(BlessedValidationHelp::new(version.is_latest))
}
};
problems.push(VersionProblem::GeneratedValidationError {
api_ident: api.ident().clone(),
version: version.version.clone(),
blessed_help,
source,
});
}
Expand All @@ -2376,6 +2419,43 @@ fn validate_generated(
}
}

/// The help text shown when a blessed version fails validation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BlessedValidationHelp {
/// For the latest blessed version, add a new version.
AddVersion,
/// For an older blessed version, suggest adding a new version and skipping
/// validation on them in code.
AddVersionOrSkipOlderBlessed,
}

impl BlessedValidationHelp {
fn new(is_latest: bool) -> Self {
if is_latest {
BlessedValidationHelp::AddVersion
} else {
BlessedValidationHelp::AddVersionOrSkipOlderBlessed
}
}

fn message(self, version: &semver::Version) -> String {
let base = format!(
"version {version} is blessed, so its OpenAPI document can't be \
changed. To fix these errors, add a new API version that \
addresses them."
);
match self {
BlessedValidationHelp::AddVersion => base,
BlessedValidationHelp::AddVersionOrSkipOlderBlessed => format!(
"{base} If these validation rules are newer than version \
{version}, only enforce them on the latest version and on \
unblessed versions (see the documentation on \
`ManagedApis::with_validation` for more)."
),
}
}
}

/// Describes the first commit for the latest version.
///
/// Used to decide whether to suggest Git stub conversion for older versions.
Expand Down Expand Up @@ -2452,6 +2532,18 @@ mod tests {
use super::*;
use assert_matches::assert_matches;

#[test]
fn test_blessed_validation_help_selection() {
assert_eq!(
BlessedValidationHelp::new(true),
BlessedValidationHelp::AddVersion,
);
assert_eq!(
BlessedValidationHelp::new(false),
BlessedValidationHelp::AddVersionOrSkipOlderBlessed,
);
}

#[test]
fn test_displayable_vec() {
let v = DisplayableVec(Vec::<usize>::new());
Expand Down
16 changes: 16 additions & 0 deletions crates/integration-tests/src/fixtures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1827,6 +1827,22 @@ fn validate_with_extra_file(
}
}

pub fn report_error_for_every_version(
_doc: &openapiv3::OpenAPI,
mut cx: ValidationContext<'_>,
) {
cx.report_error(anyhow::anyhow!("synthetic validation error"));
}

pub fn report_error_for_latest_and_unblessed(
_doc: &openapiv3::OpenAPI,
mut cx: ValidationContext<'_>,
) {
if cx.is_latest() || cx.is_blessed() != Some(true) {
cx.report_error(anyhow::anyhow!("synthetic validation error"));
}
}

pub fn versioned_health_with_validation_api() -> ManagedApi {
ManagedApi::from(ManagedApiConfig {
ident: "versioned-health",
Expand Down
57 changes: 57 additions & 0 deletions crates/integration-tests/tests/integration/versioned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2353,3 +2353,60 @@ fn test_corrupted_blessed_json_restored() -> Result<()> {

Ok(())
}

fn bless_versioned_health(
env: &TestEnvironment,
versions: &[&str],
) -> Result<()> {
let mut paths = Vec::new();
for version in versions {
let path = env
.find_versioned_document_path("versioned-health", version)?
.with_context(|| format!("v{version} document should exist"))?;
paths.push(path);
}
let path_refs: Vec<_> = paths.iter().map(|p| p.as_path()).collect();
env.git_add(&path_refs)?;
env.git_commit(&format!("bless {}", versions.join(", ")))?;
Ok(())
}

#[test]
fn test_blessed_validation_failure_help_older_versions() -> Result<()> {
let env = TestEnvironment::new_git()?;
env.generate_documents(&versioned_health_apis()?)?;
bless_versioned_health(&env, &["1.0.0", "2.0.0"])?;

let apis = versioned_health_apis()?
.with_validation(report_error_for_every_version);
let (result, _summaries, rendered) =
check_apis_with_render(env.environment(), &apis)?;
assert_eq!(result, CheckResult::Failures);

crate::snapshot::assert_render_snapshot(
&env,
"blessed_validation_failure_older_versions.txt",
&rendered,
);
Ok(())
}

#[test]
fn test_blessed_validation_failure_help_latest_version() -> Result<()> {
let env = TestEnvironment::new_git()?;
env.generate_documents(&versioned_health_apis()?)?;
bless_versioned_health(&env, &["1.0.0", "2.0.0", "3.0.0"])?;

let apis = versioned_health_apis()?
.with_validation(report_error_for_latest_and_unblessed);
let (result, _summaries, rendered) =
check_apis_with_render(env.environment(), &apis)?;
assert_eq!(result, CheckResult::Failures);

crate::snapshot::assert_render_snapshot(
&env,
"blessed_validation_failure_latest_version.txt",
&rendered,
);
Ok(())
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-------
Generating OpenAPI documents from API definitions ...
Loading local OpenAPI documents from "<documents dir>" ...
Loading blessed OpenAPI documents from VCS revision "main" path "documents"
-------
Checking 3 OpenAPI documents...
Fresh versioned-health (versioned v1.0.0 (blessed)): Versioned Health API
Fresh versioned-health (versioned v2.0.0 (blessed)): Versioned Health API
Failure versioned-health (versioned v3.0.0 (blessed)): Versioned Health API
error: Generated OpenAPI document for API "versioned-health" version
3.0.0 is not valid: OpenAPI document validation failed:
synthetic validation error
help: version 3.0.0 is blessed, so its OpenAPI document can't be
changed. To fix these errors, add a new API version that addresses
them.
Fresh versioned-health "latest" symlink
-------
Failure 3 documents checked: 3 fresh, 0 stale, 1 failed, 0 other problems
(fix failures, then run test-openapi-manager generate to update)
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
-------
Generating OpenAPI documents from API definitions ...
Loading local OpenAPI documents from "<documents dir>" ...
Loading blessed OpenAPI documents from VCS revision "main" path "documents"
-------
Checking 3 OpenAPI documents...
Failure versioned-health (versioned v1.0.0 (blessed)): Versioned Health API
error: Generated OpenAPI document for API "versioned-health" version
1.0.0 is not valid: OpenAPI document validation failed:
synthetic validation error
help: version 1.0.0 is blessed, so its OpenAPI document can't be
changed. To fix these errors, add a new API version that addresses
them. If these validation rules are newer than version 1.0.0, only
enforce them on the latest version and on unblessed versions (see
the documentation on `ManagedApis::with_validation` for more).
Failure versioned-health (versioned v2.0.0 (blessed)): Versioned Health API
error: Generated OpenAPI document for API "versioned-health" version
2.0.0 is not valid: OpenAPI document validation failed:
synthetic validation error
help: version 2.0.0 is blessed, so its OpenAPI document can't be
changed. To fix these errors, add a new API version that addresses
them. If these validation rules are newer than version 2.0.0, only
enforce them on the latest version and on unblessed versions (see
the documentation on `ManagedApis::with_validation` for more).
Failure versioned-health (versioned v3.0.0 (added locally)): Versioned Health API
error: Generated OpenAPI document for API "versioned-health" version
3.0.0 is not valid: OpenAPI document validation failed:
synthetic validation error
Fresh versioned-health "latest" symlink
-------
Failure 3 documents checked: 1 fresh, 0 stale, 3 failed, 0 other problems
(fix failures, then run test-openapi-manager generate to update)
Loading