Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/openapi3"
---

Report a new `missing-server-variable-default` warning when a server variable that has an `enum` has no default and the document is emitted for OpenAPI 3.1.0 or later, since those versions require the default to be one of the `enum` values. The emitted `default` stays an empty string.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
This diagnostic is issued when a variable in the `@server` decorator has a fixed set of values (an enum, a union of string literals or a string literal) but no default, and the document is emitted for OpenAPI 3.1.0 or later.
Those versions require the `default` of a server variable to be one of its `enum` values. The emitter does not pick one for you, so the variable keeps an empty `default` and the document is not valid.

To fix this issue, set a default on the server parameter.

### Example

```typespec
@server("https://{region}.example.com", "Regional endpoint", {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the diagnostic, I don't like choosing a default for the user. If we were to do so, the first variant makes sense, but the possibility of changing an invalid spec into a valid but incorrect spec isn't appealing.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, thanks. I dropped the default selection, so a variable without a default keeps default: "" as before, and missing-server-variable-default is now reported only when emitting OpenAPI 3.1.0 or later, where the default must be one of the enum values (d20dd31). That also removes the special case for the versions enum. Happy to turn the warning on for 3.0 as well if you would rather have it there.

region: "westus" | "eastus", // No default
})
```

Set a default:

```typespec
@server("https://{region}.example.com", "Regional endpoint", {
region?: "westus" | "eastus" = "eastus",
})
```
7 changes: 7 additions & 0 deletions packages/openapi3/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,13 @@ export const $lib = createTypeSpecLibrary({
default: paramMessage`Server variable '${"propName"}' must be assignable to 'string'. It must either be a string, enum of string or union of strings.`,
},
},
"missing-server-variable-default": {
severity: "warning",
docs: fileRef.fromPackageRoot("src/diagnostics/missing-server-variable-default.md"),
messages: {
default: paramMessage`Server variable '${"propName"}' has no default, but OpenAPI ${"openapiVersion"} requires its default to be one of its enum values. Set a default on the parameter.`,
},
},
"invalid-format": {
severity: "warning",
messages: {
Expand Down
25 changes: 25 additions & 0 deletions packages/openapi3/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,11 @@ function createOAPIEmitter(
// De-dupe the per-endpoint tags that will be added into the #/tags
let tagsUsedInOperations: Set<string>;

// Server parameters already warned about for a missing default, keyed by their declaration.
// Servers are resolved once per document and each version of a versioned service gets its own
// copy of the parameter, so without this the same warning would be reported for every version.
const serverVariablesWarnedForDefault = new Set<ModelProperty["node"] | ModelProperty>();

const typeNameOptions: TypeNameOptions = {
// shorten type names by removing TypeSpec and service namespace
namespaceFilter(ns) {
Expand Down Expand Up @@ -547,6 +552,21 @@ function createOAPIEmitter(
return isValid;
}

function reportMissingServerVariableDefault(prop: ModelProperty) {
const key = prop.node ?? prop;
if (serverVariablesWarnedForDefault.has(key)) {
return;
}
serverVariablesWarnedForDefault.add(key);
diagnostics.add(
createDiagnostic({
code: "missing-server-variable-default",
format: { propName: prop.name, openapiVersion: specVersion },
target: prop,
}),
);
}

function resolveServers(servers: HttpServer[]): OpenAPI3Server[] {
return servers.map((server) => {
const variables: Record<string, OpenAPI3ServerVariable> = {};
Expand All @@ -569,6 +589,11 @@ function createOAPIEmitter(
} else if (prop.type.kind === "String") {
variable.enum = [prop.type.value];
}
// OpenAPI 3.1 and later require `default` to be one of the `enum` values (3.0 only says
// it should be). Picking one could choose the wrong value, so ask the author to set it.
if (!prop.defaultValue && variable.enum?.length && specVersion !== "3.0.0") {
reportMissingServerVariableDefault(prop);
}
attachExtensions(program, prop, variable);
variables[name] = variable;
}
Expand Down
99 changes: 93 additions & 6 deletions packages/openapi3/test/servers.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
import { expectDiagnostics } from "@typespec/compiler/testing";
import { deepStrictEqual } from "assert";
import { it } from "vitest";
import { emitOpenApiWithDiagnostics, TesterWithVersioning } from "./test-host.js";
import { supportedVersions, worksFor } from "./works-for.js";

worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVersion }) => {
// OpenAPI 3.0 only says that a server variable default should be one of its enum values.
const missingDefaultWarnings = (name: string) =>
specVersion === "3.0.0"
? []
: [
{
code: "@typespec/openapi3/missing-server-variable-default",
severity: "warning" as const,
message: `Server variable '${name}' has no default, but OpenAPI ${specVersion} requires its default to be one of its enum values. Set a default on the parameter.`,
},
];

it("set a basic server(url)", async () => {
const res = await openApiFor(
`
Expand Down Expand Up @@ -73,7 +86,7 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
});

it("accepts an enum whose numeric members are all encoded as strings", async () => {
const res = await openApiFor(
const [res, diagnostics] = await emitOpenApiWithDiagnostics(
`
@service(#{title: "My service"})
@server("https://{region}.example.com", "Regional account endpoint", {region: Region})
Expand All @@ -86,8 +99,10 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
eastUs: 2,
}
`,
{ "openapi-versions": [specVersion] },
);
deepStrictEqual(res.servers[0].variables.region.enum, ["westus", "eastus"]);
expectDiagnostics(diagnostics, missingDefaultWarnings("region"));
deepStrictEqual(res.servers?.[0].variables?.region?.enum, ["westus", "eastus"]);
});

it("emit diagnostic when a numeric enum member is left unencoded", async () => {
Expand Down Expand Up @@ -212,7 +227,7 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
});

it("set a server with enum properties", async () => {
const res = await openApiFor(
const [res, diagnostics] = await emitOpenApiWithDiagnostics(
`
enum Region { westus, eastus }
@service(#{title: "My service"})
Expand All @@ -221,7 +236,9 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
})
namespace MyService {}
`,
{ "openapi-versions": [specVersion] },
);
expectDiagnostics(diagnostics, missingDefaultWarnings("region"));
deepStrictEqual(res.servers, [
{
description: "Regional account endpoint",
Expand All @@ -233,8 +250,24 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
]);
});

it("set a server with string literal", async () => {
it("set a server with enum properties with a default", async () => {
const res = await openApiFor(
`
enum Region { westus, eastus }
@service(#{title: "My service"})
@server("https://{region}.example.com", "Regional account endpoint", {
region?: Region = Region.eastus,
})
namespace MyService {}
`,
);
deepStrictEqual(res.servers[0].variables, {
region: { default: "eastus", enum: ["westus", "eastus"] },
});
});

it("set a server with string literal", async () => {
const [res, diagnostics] = await emitOpenApiWithDiagnostics(
`
enum Region { }
@service(#{title: "My service"})
Expand All @@ -243,7 +276,9 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
})
namespace MyService {}
`,
{ "openapi-versions": [specVersion] },
);
expectDiagnostics(diagnostics, missingDefaultWarnings("region"));
deepStrictEqual(res.servers, [
{
description: "Regional account endpoint",
Expand All @@ -256,7 +291,7 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
});

it("set a server with unions type", async () => {
const res = await openApiFor(
const [res, diagnostics] = await emitOpenApiWithDiagnostics(
`
enum Region { }
@service(#{title: "My service"})
Expand All @@ -265,7 +300,9 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
})
namespace MyService {}
`,
{ "openapi-versions": [specVersion] },
);
expectDiagnostics(diagnostics, missingDefaultWarnings("region"));
deepStrictEqual(res.servers, [
{
description: "Regional account endpoint",
Expand All @@ -276,6 +313,56 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
},
]);
});

it("set a server with unions type with a default", async () => {
const res = await openApiFor(
`
@service(#{title: "My service"})
@server("https://{region}.example.com", "Regional account endpoint", {
region?: "westus" | "eastus" = "eastus",
})
namespace MyService {}
`,
);
deepStrictEqual(res.servers[0].variables, {
region: { default: "eastus", enum: ["westus", "eastus"] },
});
});

it("warns once for a server variable without a default in a versioned service", async () => {
const [{ outputs }, diagnostics] = await TesterWithVersioning.compileAndDiagnose(
`
@versioned(Versions)
@service(#{title: "My service"})
@server("{endpoint}/{apiVersion}", "Versioned endpoint", {
endpoint: url,
apiVersion: Versions,
})
namespace MyService {
enum Versions { v1: "2024-01-01", v2: "2025-01-01" }
}
`,
{
compilerOptions: {
options: {
"@typespec/openapi3": {
"openapi-versions": [specVersion],
"output-file": "{version}.openapi.json",
},
},
},
},
);
expectDiagnostics(diagnostics, missingDefaultWarnings("apiVersion"));
for (const version of ["2024-01-01", "2025-01-01"]) {
const document = JSON.parse(outputs[`${version}.openapi.json`]);
deepStrictEqual(document.servers[0].variables, {
endpoint: { default: "" },
apiVersion: { default: "", enum: ["2024-01-01", "2025-01-01"] },
});
}
});

it("set multiple servers", async () => {
const res = await openApiFor(
`
Expand Down