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
2 changes: 1 addition & 1 deletion .changeset/empty-vocabulary-unsupported.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@

**Behaviour change: an `include` or `sort` family declared with an empty vocabulary now counts as unsupported, so a request that used to succeed can now answer 400.** This covers `include: { paths: [] }`, `include: true` on a resource with no relationships, and `sort: true` on a resource with no attributes. The `SchemaErrors` middleware now answers any `?include=` or `?sort=` on such an endpoint exactly as it answers one on an endpoint that never declared the family: a 400 naming the parameter in `source.parameter`, with the detail saying the endpoint does not support it. That includes an empty value (`?include=`, `?sort=`), which used to answer 200, and a bracketed member such as `include[x]`, which used to be ignored. A non-empty value used to answer 400 with the detail `Expected never` and `meta.includablePaths: []` / `meta.sortableFields: []`. It now gets that same unsupported-parameter 400, without the `meta` (#282). Because the middleware answers it before content negotiation, such a request that also carries an unacceptable `Accept` or an unsupported `Content-Type` now answers this 400 where it used to answer 406 or 415, as on an endpoint that never declared the family.

Only the endpoint's own decoded `include` / `sort` property counts, read through a union and through `Schema.suspend`. A hand-built query whose `include` is `Query.IncludeList`, or whose `sort` is a custom codec, publishes no vocabulary and keeps the family supported, and so does a union in which any member's vocabulary is non-empty. A vocabulary under another property name, such as a second `Query.Include` the query declares as `other`, never decides it.
Only the codec the `include` / `sort` query parameter itself decodes through counts: the query's property of that name, or the property its encoding renames to that wire name (`Schema.encodeKeys({ paths: "include" })`), read through a union and through `Schema.suspend`. A hand-built query whose `include` parameter decodes through `Query.IncludeList`, or whose `sort` parameter decodes through a custom codec, publishes no vocabulary and keeps the family supported, and so does a union in which any member's vocabulary is non-empty. A vocabulary under another parameter, such as a second `Query.Include` the query declares as `other`, never decides it.

Where such a value still reaches the codec, its rejection now says why: an `allowedQueryParameters` entry that admits the family, or a direct decode with `Query.Include`, `Query.Sort` or `Query.schema`. The detail is `This endpoint supports no include paths.` or `This endpoint supports no sortable fields.` in place of `Expected never`.
77 changes: 72 additions & 5 deletions src/Middleware.query.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vite-plus/test";
import { Effect, Layer, Schema, Tracer } from "effect";
import { Effect, Layer, Schema, SchemaTransformation, Tracer } from "effect";
import { HttpRouter } from "effect/http";
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/http-api";
import * as Endpoint from "./Endpoint.js";
Expand Down Expand Up @@ -767,10 +767,12 @@ describe("spec families an endpoint does not support (#261)", () => {

describe("which declared `include` / `sort` an endpoint supports (#282)", () => {
// The support check reads the vocabulary the `include` / `sort` codecs
// publish, on the decoded property of that name only. A family counts as
// unsupported when every value its property could decode is drawn from an
// empty vocabulary; one that publishes no vocabulary (`Query.IncludeList`,
// a custom codec) or a non-empty one somewhere is supported.
// publish, only on the property the family's wire parameter decodes into
// (the one of that name, or one the encoding renames to it). A family
// counts as unsupported when every value its property could decode is
// drawn from an empty vocabulary; one that publishes no vocabulary
// (`Query.IncludeList`, a custom codec) or a non-empty one somewhere is
// supported.
const Person = Resource.make("people", { attributes: { name: Schema.NonEmptyString } });
const Post = Resource.make("posts", {
attributes: { title: Schema.NonEmptyString },
Expand All @@ -797,6 +799,11 @@ describe("which declared `include` / `sort` an endpoint supports (#282)", () =>
Query.schema(Tag, { include: { paths: [] } }),
Query.schema(Post, { include: true }),
]),
// The second member's wire has no `include`, so it reads no property.
"union-with-query-without-include": Schema.Union([
Query.schema(Tag, { include: { paths: [] } }),
Query.schema(Post, { fields: true }),
]),
"union-of-sorts": Schema.Struct({
sort: Schema.optionalKey(Schema.Union([Query.Sort([]), Query.Sort(["title"])])),
}),
Expand All @@ -823,6 +830,32 @@ describe("which declared `include` / `sort` an endpoint supports (#282)", () =>
"optional-include": Schema.Struct({ include: Schema.optional(Query.Include(Tag)) }),
// Only the family's own vocabulary counts.
"sort-codec-as-include": Schema.Struct({ include: Schema.optionalKey(Query.Sort([])) }),
// A record of empty vocabularies: every value it decodes draws on one.
"include-record": Schema.Struct({
include: Schema.optionalKey(Schema.Record(Schema.String, Query.Include(Tag))),
}),
// The wire's `include` decodes into a property of another name.
"renamed-include": Schema.Struct({ paths: Schema.optionalKey(Query.Include(Tag)) }).pipe(
Schema.encodeKeys({ paths: "include" }),
),
"renamed-include-beside-other": Schema.Struct({
paths: Schema.optionalKey(Query.Include(Tag)),
other: Schema.optionalKey(Query.Include(Post)),
}).pipe(Schema.encodeKeys({ paths: "include" })),
"renamed-open-include": Schema.Struct({
paths: Schema.optionalKey(Query.IncludeList),
other: Schema.optionalKey(Query.Include(Tag)),
}).pipe(Schema.encodeKeys({ paths: "include" })),
// A query decoded whole by a custom codec has no property to read.
"query-as-string": Schema.Struct({ include: Schema.optionalKey(Schema.String) }).pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transform<string, { readonly include?: string }>({
decode: (query) => query.include ?? "",
encode: (include) => ({ include }),
}),
),
),
} as const;
type Name = keyof typeof endpoints;
const endpoint = <const N extends Name>(name: N) =>
Expand All @@ -836,6 +869,7 @@ describe("which declared `include` / `sort` an endpoint supports (#282)", () =>
endpoint("custom-sort"),
endpoint("recursive-include"),
endpoint("union-of-queries"),
endpoint("union-with-query-without-include"),
endpoint("union-of-sorts"),
endpoint("union-with-open-include"),
endpoint("open-include-beside-empty"),
Expand All @@ -845,6 +879,11 @@ describe("which declared `include` / `sort` an endpoint supports (#282)", () =>
endpoint("suspended-include"),
endpoint("optional-include"),
endpoint("sort-codec-as-include"),
endpoint("include-record"),
endpoint("renamed-include"),
endpoint("renamed-include-beside-other"),
endpoint("renamed-open-include"),
endpoint("query-as-string"),
),
);
// Each handler answers the decoded `query` it received.
Expand All @@ -855,6 +894,7 @@ describe("which declared `include` / `sort` an endpoint supports (#282)", () =>
"custom-sort": echo,
"recursive-include": echo,
"union-of-queries": echo,
"union-with-query-without-include": echo,
"union-of-sorts": echo,
"union-with-open-include": echo,
"open-include-beside-empty": echo,
Expand All @@ -864,6 +904,11 @@ describe("which declared `include` / `sort` an endpoint supports (#282)", () =>
"suspended-include": echo,
"optional-include": echo,
"sort-codec-as-include": echo,
"include-record": echo,
"renamed-include": echo,
"renamed-include-beside-other": echo,
"renamed-open-include": echo,
"query-as-string": echo,
}),
);

Expand Down Expand Up @@ -936,6 +981,14 @@ describe("which declared `include` / `sort` an endpoint supports (#282)", () =>
},
],
["another family's empty vocabulary", "/sort-codec-as-include?include=", { include: [] }],
// The wire's `include` feeds the renamed `paths`, an open list; the
// empty vocabulary under `other` is another parameter's.
[
"a renamed `Query.IncludeList` beside an empty vocabulary under another name",
"/renamed-open-include?include=author",
{ paths: ["author"] },
],
["a query its own codec decodes whole", "/query-as-string?include=author", "author"],
] as const)("supports %s", async (_, url, query) => {
const response = await serve(url);
expect(response.status).toBe(200);
Expand All @@ -957,6 +1010,20 @@ describe("which declared `include` / `sort` an endpoint supports (#282)", () =>
["a suspended query, an empty value", "/suspended-query?include=", "include"],
["a suspended `include` codec", "/suspended-include?include=author", "include"],
["an optional `include`", "/optional-include?include=", "include"],
["a record of empty `include` codecs", "/include-record?include=", "include"],
// Owner decision on #282: the wire name decides, not the decoded one.
["an `include` renamed on the wire", "/renamed-include?include=author", "include"],
["an `include` renamed on the wire, an empty value", "/renamed-include?include=", "include"],
[
"an `include` renamed on the wire beside a non-empty one under another name",
"/renamed-include-beside-other?include=author",
"include",
],
[
"a union with a query that declares no `include`",
"/union-with-query-without-include?include=author",
"include",
],
] as const)("rejects an empty vocabulary as unsupported: %s", async (_, url, family) => {
const response = await serve(url);
expect(response.status).toBe(400);
Expand Down
16 changes: 9 additions & 7 deletions src/Middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -712,7 +712,8 @@ export const checkQueryParameters = (
// relationships, `sort: true` over no attributes. Such a family supports no
// value, so it counts as undeclared (owner decision on #282): every request
// that carries it gets the same 400 as on an endpoint that never declared it.
// Each family is read off its own decoded property only (`admitsNoValue`).
// Each family is read off the property its wire parameter decodes into, and
// no other (`admitsNoValue`).
const emptyVocabularies = (ast: SchemaAST.AST): ReadonlyArray<string> =>
Arr.filter(SUPPORT_FAMILY_NAMES, (family) => admitsNoValue(ast, family));

Expand Down Expand Up @@ -978,12 +979,13 @@ export const schemaErrorsLayer = (options?: QueryParameterOptions): Layer.Layer<
* collection, and on a single-resource endpoint (`GET /articles/1?sort=title`)
* the general §Implementation-Specific Query Parameters rule, since that
* endpoint does not know how to process `sort` as a query parameter from the
* specification. Only the schema's own decoded `include` / `sort` property
* decides whether its vocabulary is empty, read through a union or
* `Schema.suspend`: one whose codec publishes no vocabulary
* (`Query.IncludeList`, a custom codec), or a non-empty one in any member of
* a union, supports the family. An undeclared `fields[TYPE]`, `page[…]` or
* `filter[…]` is still ignored.
* specification. Only the property the schema decodes the `include` /
* `sort` parameter into decides whether its vocabulary is empty — the one of
* that name, or the one its encoding renames to it (`Schema.encodeKeys`) —
* read through a union or `Schema.suspend`: one whose codec publishes no
* vocabulary (`Query.IncludeList`, a custom codec), or a non-empty one in
* any member of a union, supports the family. An undeclared `fields[TYPE]`,
* `page[…]` or `filter[…]` is still ignored.
*
* A handler whose response fails to encode against its endpoint's own schema
* (`HttpApiSchemaError` kind `"Body"` or `"ResponseHeaders"`) is a server
Expand Down
2 changes: 1 addition & 1 deletion src/Query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ import {
Repeatable,
repeatable,
Sort as SortCodec,
vocabularyAnnotations,
} from "./internal/codecs.js";
import type { FieldCodecs } from "./internal/filter.js";
import {
Expand All @@ -73,6 +72,7 @@ import {
operatorCheck,
prepare,
} from "./internal/filter.js";
import { vocabularyAnnotations } from "./internal/vocabulary.js";
import type {
Any,
AttributeKeys,
Expand Down
21 changes: 2 additions & 19 deletions src/internal/codecs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
*
* @internal
*/
import { Array as Arr, Option, Record as Rec, Schema, SchemaTransformation } from "effect";
import { Option, Record as Rec, Schema, SchemaTransformation } from "effect";
import type { Term } from "../Sort.js";
import { define } from "./define.js";
import type { Vocabulary } from "./vocabulary.js";
import { vocabularyAnnotation } from "./vocabulary.js";
import { vocabularyAnnotations } from "./vocabulary.js";

/**
* A comma-separated list codec: `"a,b,c"` ↔ `["a", "b", "c"]`.
Expand Down Expand Up @@ -91,22 +90,6 @@ export const repeatable = <S extends Schema.Top>(
): Schema.decodeTo<S, Repeatable, never, never> =>
Repeatable.pipe(Schema.decodeTo(item)) as Schema.decodeTo<S, Repeatable, never, never>;

/**
* The annotations of a closed vocabulary's literal schema: its whole set as
* the family's vocabulary (`internal/vocabulary.ts`), which the 400 for a
* rejected value renders as error `meta` and the support check reads, and,
* when the set is empty, a `message` saying so — `Schema.Literals([])` is
* `never`, whose rejection would otherwise read "Expected never" (#282).
*/
export const vocabularyAnnotations = (
vocabulary: Vocabulary,
emptyMessage: string,
): Schema.Annotations.Annotations =>
Arr.match(vocabulary.values, {
onEmpty: () => ({ ...vocabularyAnnotation(vocabulary), message: emptyMessage }),
onNonEmpty: () => vocabularyAnnotation(vocabulary),
});

/**
* A sort term: an attribute name and a direction — the public `Sort.Term`.
*/
Expand Down
66 changes: 47 additions & 19 deletions src/internal/vocabulary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import type * as Schema from "effect/Schema";
import * as SchemaAST from "effect/SchemaAST";
import { declaredNames } from "./declaredQuery.js";

/** The annotation key. Namespaced so it can never collide with a consumer's. */
const VOCABULARY_ANNOTATION = "~@thomasfosterau/effect-jsonapi/vocabulary";
Expand Down Expand Up @@ -56,13 +57,27 @@ export type Vocabulary =
*/
export type Family = Vocabulary["family"];

// The annotation object `schema.annotate(...)` takes to publish a vocabulary.
const vocabularyAnnotation = (vocabulary: Vocabulary) =>
({ [VOCABULARY_ANNOTATION]: vocabulary }) satisfies Schema.Annotations.Annotations;

/**
* The annotation object `schema.annotate(...)` takes to publish a vocabulary.
* The annotations of a closed vocabulary's literal schema: its whole set as
* the family's vocabulary, which the 400 for a rejected value renders as
* error `meta` and the support check reads, and, when the set is empty, a
* `message` saying so — `Schema.Literals([])` is `never`, whose rejection
* would otherwise read "Expected never" (#282).
*
* @internal
*/
export const vocabularyAnnotation = (vocabulary: Vocabulary) =>
({ [VOCABULARY_ANNOTATION]: vocabulary }) satisfies Schema.Annotations.Annotations;
export const vocabularyAnnotations = (
vocabulary: Vocabulary,
emptyMessage: string,
): Schema.Annotations.Annotations =>
Arr.match(vocabulary.values, {
onEmpty: () => ({ ...vocabularyAnnotation(vocabulary), message: emptyMessage }),
onNonEmpty: () => vocabularyAnnotation(vocabulary),
});

const isVocabulary = (value: unknown): value is Vocabulary =>
Predicate.hasProperty(value, "family") && Predicate.hasProperty(value, "values");
Expand Down Expand Up @@ -122,25 +137,36 @@ const drawsOnlyFromEmpty = (ast: SchemaAST.AST, family: Family, visiting: Visiti
},
});

// The schemas a query decodes its property `name` with: the property of that
// name on a struct, on every member of a union, through a suspended schema.
const propertiesNamed = (
// The schemas a query decodes its wire parameter `name` with, each read on
// its decoded side. On a struct that is its property of that name, or, when
// it has none but its encoded side declares `name`, every property whose name
// that side does not declare: one of them is the property the struct's
// encoding renamed to `name` (`Schema.encodeKeys`), and the AST does not say
// which. Read on every member of a union and through a suspended schema.
const propertiesFor = (
ast: SchemaAST.AST,
name: string,
visiting: Visiting,
): ReadonlyArray<SchemaAST.AST> => {
if (SchemaAST.isObjects(ast)) {
return Arr.flatMap(ast.propertySignatures, (signature) =>
signature.name === name ? [signature.type] : [],
);
const decoded = (signatures: ReadonlyArray<SchemaAST.PropertySignature>) =>
Arr.map(signatures, (signature) => SchemaAST.toType(signature.type));
const named = Arr.filter(ast.propertySignatures, (signature) => signature.name === name);
if (Arr.isReadonlyArrayNonEmpty(named)) return decoded(named);
const wire = Option.getOrElse(declaredNames(ast), (): ReadonlyArray<string> => []);
return wire.includes(name)
? decoded(
Arr.filter(ast.propertySignatures, (signature) => !wire.includes(String(signature.name))),
)
: [];
}
if (SchemaAST.isUnion(ast)) {
return Arr.flatMap(ast.types, (member) => propertiesNamed(member, name, visiting));
return Arr.flatMap(ast.types, (member) => propertiesFor(member, name, visiting));
}
if (SchemaAST.isSuspend(ast)) {
return Option.match(enter(visiting, ast), {
onNone: () => [],
onSome: (next) => propertiesNamed(ast.thunk(), name, next),
onSome: (next) => propertiesFor(ast.thunk(), name, next),
});
}
return [];
Expand All @@ -149,18 +175,20 @@ const propertiesNamed = (
/**
* Whether a query schema declares `family` only with an empty vocabulary, so
* that no value of it can decode: `include: { paths: [] }`, `include: true`
* over no relationships, `sort: true` over no attributes. Reads the decoded
* property named after the family and nothing else, so a vocabulary under
* another name never counts. True only when every such property, in every
* member of a union query, draws its values from empty vocabularies alone; a
* property that publishes no vocabulary (`Query.IncludeList`, a custom codec)
* or a non-empty one anywhere admits a value, and so does an endpoint that
* declares no such property.
* over no relationships, `sort: true` over no attributes. Reads the property
* the family's wire parameter decodes into and nothing else, so a vocabulary
* under another parameter never counts: the property named after the family,
* or, where the query's encoding renames another property to the family's
* name, every property the wire does not name. True only when every such
* property, in every member of a union query, draws its values from empty
* vocabularies alone; a property that publishes no vocabulary
* (`Query.IncludeList`, a custom codec) or a non-empty one anywhere admits a
* value, and so does an endpoint whose decoded query has no such property.
*
* @internal
*/
export const admitsNoValue = (query: SchemaAST.AST, family: Family): boolean => {
const properties = propertiesNamed(SchemaAST.toType(query), family, []);
const properties = propertiesFor(query, family, []);
return (
Arr.isReadonlyArrayNonEmpty(properties) &&
Arr.every(properties, (property) => drawsOnlyFromEmpty(property, family, []))
Expand Down
Loading