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 tools/spectral/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A set of custom validation rules for the MongoDB Atlas Programmatic API, adherin

### Custom Rules

For a complete list of implemented rules, please refer to the [Ruleset Documentation](./ipa/rulesets/README.md).
For a complete list of implemented rules, please refer to the [Ruleset Documentation](./ipa/rulesets/README.md). The conditions that decide where rules apply are explained in the [Conditions glossary](./ipa/rulesets/CONDITIONS.md).

### External Documentation

Expand Down
4 changes: 3 additions & 1 deletion tools/spectral/ipa/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,10 @@ export default defineRule({
```

- `appliesTo` conditions are evaluated in order. If one does not hold, the rule does not apply and the check does not run. Combine conditions with `allOf`, `anyOf` and `not`.
- A condition that throws fails the whole lint run, so a condition must not throw on a component it was not meant for. Put the conditions it relies on before it in `appliesTo`: evaluation stops at the first one that does not hold.
- A condition that throws fails the whole lint run, so a condition must not throw on a component it was not meant for. Put the conditions it relies on before it in `appliesTo`: evaluation stops at the first one that does not hold. A `check` that throws is reported according to `onInternalError`, below.
- `check` receives a `RuleContext` with the `input`, `options`, `path`, and values derived from them such as `resourcePath` and `resourcePathItems`, computed once per call. It returns the validation errors, as a rule function does today.
- Adoptions, violations and exceptions are collected for you from what `check` returns, reading `x-xgen-IPA-exception` from the input (or from `exceptionTarget`). `onInternalError` (`'violation'`, `'return'`, `'throw'`) sets what happens if `check` throws, and `beforeCheck` runs outside that try for a failure that must stop the lint run.
- Give a condition a `label`, and an example a `note`, to have it described in the generated docs: `npm run gen-ipa-docs` renders an "Applies to" section for each `defineRule` rule in [`rulesets/README.md`](./rulesets/README.md) and the glossary [`rulesets/CONDITIONS.md`](./rulesets/CONDITIONS.md), so don't describe where a rule applies in its YAML description.
- Reuse an existing condition where possible. If a rule needs a different definition of the same concept, add a condition with `variantOf` and a `divergence` note rather than changing the shared one.

### Resource & Singleton Evaluation
Expand Down
84 changes: 63 additions & 21 deletions tools/spectral/ipa/__tests__/utils/defineRule.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { describe, expect, it } from '@jest/globals';
import { beforeEach, describe, expect, it } from '@jest/globals';
import collector, { EntryType } from '../../metrics/collector';
import { defineRule } from '../../rulesets/functions/utils/defineRule';
import { defineCondition } from '../../rulesets/functions/utils/conditions/registry';

Expand All @@ -11,13 +12,26 @@ const spectralContext = {
rule: { name: 'test-rule' },
};

function collected() {
return Object.fromEntries(Object.entries(collector.entries).map(([type, list]) => [type, list.length]));
}

describe('tools/spectral/ipa/rulesets/functions/utils/defineRule.js', () => {
beforeEach(() => {
collector.entries = { [EntryType.VIOLATION]: [], [EntryType.ADOPTION]: [], [EntryType.EXCEPTION]: [] };
});

it('attaches the conditions as meta', () => {
const rule = defineRule({ appliesTo: [holds], check: () => [] });
expect(rule.meta).toEqual({ appliesTo: [holds], document: 'resolved' });
expect(rule.meta).toEqual({
appliesTo: [holds],
checkUses: [],
document: 'resolved',
onInternalError: 'violation',
});
});

it('does not run the check when a condition fails', () => {
it('does not run the check or collect when a condition fails', () => {
let checked = false;
const rule = defineRule({
appliesTo: [holds, fails],
Expand All @@ -28,41 +42,69 @@ describe('tools/spectral/ipa/rulesets/functions/utils/defineRule.js', () => {
});
expect(rule({}, null, spectralContext)).toBeUndefined();
expect(checked).toBe(false);
expect(collected()).toEqual({ violations: 0, adoptions: 0, exceptions: 0 });
});

it('returns the errors of the check when the rule applies', () => {
const rule = defineRule({ appliesTo: [holds], check: ({ path }) => [{ path, message: 'bad' }] });
expect(rule({}, null, spectralContext)).toEqual([{ path: spectralContext.path, message: 'bad' }]);
it('collects an adoption when the check returns no errors', () => {
const rule = defineRule({ appliesTo: [holds], check: () => [] });
expect(rule({}, null, spectralContext)).toBeUndefined();
expect(collected()).toEqual({ violations: 0, adoptions: 1, exceptions: 0 });
});

it('gives the check the context and options', () => {
it('collects an exception from the exception target', () => {
const rule = defineRule({
check: ({ options, resourcePath, path }) => [{ path, message: `${options.a} ${resourcePath}` }],
check: ({ path }) => [{ path, message: 'bad' }],
exceptionTarget: () => ({ 'x-xgen-IPA-exception': { 'test-rule': 'reason' } }),
});
expect(rule({}, { a: 'x' }, spectralContext)).toEqual([{ path: spectralContext.path, message: 'x /resource' }]);
expect(rule({}, null, spectralContext)).toBeUndefined();
expect(collected()).toEqual({ violations: 0, adoptions: 0, exceptions: 1 });
});

it('reads the unresolved document when asked to', () => {
it('gives the check the context and options', () => {
const rule = defineRule({
document: 'unresolved',
check: ({ oas, path }) => [{ path, message: String(oas.paths['/resource']) }],
check: ({ options, resourcePath, path }) => [{ path, message: `${options.a} ${resourcePath}` }],
});
expect(rule({}, null, spectralContext)[0].message).toBe('undefined');
expect(rule({}, { a: 'x' }, spectralContext)).toEqual([{ path: spectralContext.path, message: 'x /resource' }]);
});

it('lets an exception in a condition fail the lint run', () => {
const throws = defineCondition({
id: 'defineRuleTest.throws',
fn: () => {
throw new Error('condition');
},
});
expect(() => defineRule({ appliesTo: [throws], check: () => [] })({}, null, spectralContext)).toThrow('condition');
it('runs beforeCheck only when the rule applies, and lets its exceptions propagate', () => {
const beforeCheck = () => {
throw new Error('before');
};
expect(() => defineRule({ appliesTo: [holds], beforeCheck, check: () => [] })({}, null, spectralContext)).toThrow(
'before'
);
expect(() =>
defineRule({ appliesTo: [fails], beforeCheck, check: () => [] })({}, null, spectralContext)
).not.toThrow();
});

it('names the function after the rule, so a crash outside the check says which rule', () => {
const rule = defineRule({ check: () => [] });
rule({}, null, spectralContext);
expect(rule.name).toBe('test-rule');
});

describe('when the check throws', () => {
const throwing = () => {
throw new Error('boom');
};

it("reports and collects a violation in 'violation' mode", () => {
const rule = defineRule({ check: throwing });
expect(rule({}, null, spectralContext)[0].message).toContain('test-rule Internal Rule Error: Error: boom');
expect(collected()).toEqual({ violations: 1, adoptions: 0, exceptions: 0 });
});

it("reports without collecting in 'return' mode", () => {
const rule = defineRule({ check: throwing, onInternalError: 'return' });
expect(rule({}, null, spectralContext)[0].message).toContain('Internal Rule Error');
expect(collected()).toEqual({ violations: 0, adoptions: 0, exceptions: 0 });
});

it("propagates in 'throw' mode", () => {
const rule = defineRule({ check: throwing, onInternalError: 'throw' });
expect(() => rule({}, null, spectralContext)).toThrow('boom');
});
});
});
5 changes: 5 additions & 0 deletions tools/spectral/ipa/rulesets/CONDITIONS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<!--- NOTE: This file is generated, please see /scripts/generateRulesetReadme.js --->

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Any reason why we need this as separate md file. Can we append to existing docs?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I considered rulesets/README.md, but kept it separate. That README is already ~1,800 lines, and the glossary is reference material that readers reach from an "Applies to" link rather than by reading top to bottom. On my local branch, with 71 of ~117 rules migrated, it is ~520 lines (34 conditions), which would be about a quarter of the README. CONTRIBUTING.md is for rule authors, and this file is generated from the code. To make it findable, tools/spectral/README.md now links to it next to the ruleset docs. Happy to fold it into the rules README if you would still prefer that.


# IPA Validation Conditions

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's add fixes description what business purpose this chapter serves before generated content

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added an intro before the generated content, and a "Why generate the docs" section to the PR description on what the generated docs are for.


A condition is a named, tested yes/no question about the part of the spec a rule is looking at, such as "is a singleton resource" or "is a 2xx response". Rules built with `defineRule` list the conditions they apply to, and the "Applies to" sections in the [rules README](./README.md) link here. Each entry says what the condition is evaluated on, gives examples that match and do not match (checked by the tests), and lists the rules that use it. To change where several rules apply, change the condition once. Conditions are defined in [rulesets/functions/utils/conditions](https://github.com/mongodb/openapi/tree/main/tools/spectral/ipa/rulesets/functions/utils/conditions); to add one, see [CONTRIBUTING.md](https://github.com/mongodb/openapi/blob/main/tools/spectral/ipa/CONTRIBUTING.md). Only conditions used by at least one rule are listed.
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
* @property {'leaf'|'allOf'|'anyOf'|'not'} op
* @property {(ctx: RuleContext) => unknown} [fn] predicate for leaf conditions; reads the rule context
* @property {Array<Condition>} [children] operands for allOf/anyOf/not
* @property {string} [label] short phrase completing "Applies when ...", rendered in the rule docs
* @property {string} [subject] what the condition is evaluated on, e.g. 'path', 'resource', 'operation'
* @property {string} [definition] plain-English definition, rendered in the glossary
* @property {{match: Array<Object>, noMatch: Array<Object>}} [examples] rule context fixtures, run by the tests
* @property {{match: Array<Object>, noMatch: Array<Object>}} [examples] rule context fixtures, run by the tests; each may
* have a `note` saying what makes it (not) match, shown in the glossary when that is not visible in its path
* @property {string} [variantOf] id of the condition this one is a divergent variant of
* @property {string} [divergence] how this variant differs from variantOf, and where it is used
* @property {boolean} [readsRuleOptions] the result depends on the rule's functionOptions, so it has no rule-independent count
Expand Down
73 changes: 64 additions & 9 deletions tools/spectral/ipa/rulesets/functions/utils/defineRule.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @ts-check
import { evaluateAndCollectAdoptionStatus, handleInternalError } from './collectionUtils.js';
import { createRuleContext } from './ruleContext.js';

/**
Expand All @@ -7,30 +8,62 @@ import { createRuleContext } from './ruleContext.js';
* @typedef {Array<{path?: Array<string>, message: string}>} RuleErrors
*/

/**
* How a rule reports an exception thrown by its check. The modes preserve how rules behaved before defineRule; they
* are not a recommendation. Conditions are never covered: an exception there always fails the lint run.
* - 'violation': the internal error is reported, and collected as a violation (or exception, if the component has one)
* - 'return': the internal error is reported, and nothing is collected
* - 'throw': the exception propagates and Spectral fails the lint run
* @typedef {'violation'|'return'|'throw'} InternalErrorMode
*/

/**
* Builds a Spectral rule function from where the rule applies and what it checks.
*
* Without it, every rule function reads its context from Spectral, decides where it applies with early `return`s that
* each rule words its own way, and only then runs its check. A rule using defineRule declares the named conditions it
* applies under, defined once and shared by every rule that needs them, and the check only does the check:
* each rule words its own way, runs its check in a copied try/catch, and records the result itself. A rule using
* defineRule declares the named conditions it applies under, defined once and shared by every rule that needs them,
* and the check only does the check:
*
* export default defineRule({
* appliesTo: [isSingleton, not(isReadOnly)],
* check: ({ input, path }) => (hasPutMethod(input) || hasPatchMethod(input) ? [] : [{ path, message: ERROR_MESSAGE }]),
* });
*
* Where a rule applies is then readable at a glance, a change to a shared definition is made in one place, and all
* skipping happens here, so tooling can tell which condition skipped a component.
* Where a rule applies is then readable at a glance, a change to a shared definition is made in one place, and every
* rule records adoptions, violations, exceptions and internal errors the same way. All skipping happens here, so tooling
* can tell which condition skipped a component.
*
* The conditions are attached to the function as `meta`, for generated docs and reports: `appliesTo`, and `checkUses` for
* conditions the check evaluates itself (e.g. to pick an error message), which have no effect on whether the rule applies.
*
* @param {Object} spec
* @param {Array<Condition>} [spec.appliesTo] conditions that must all hold, evaluated in order; the first that fails skips the
* rule, so a later condition may assume the earlier ones held. They run outside any try: a condition that throws fails the
* lint run, so a condition must not throw on a component it was not meant for
* @param {(ctx: RuleContext) => RuleErrors} spec.check returns the errors Spectral reports, an empty array if the component adheres
* @param {(ctx: RuleContext) => RuleErrors} spec.check returns the errors Spectral reports, an empty array if the component
* adheres. If it throws, `onInternalError` decides what happens
* @param {(ctx: RuleContext) => void} [spec.beforeCheck] runs once the rule applies, outside any try like the conditions, so
* an exception fails the lint run instead of being reported as an internal error
* @param {Array<Condition>} [spec.checkUses] conditions evaluated inside check, listed for docs and reports only. They may
* be evaluated on another component than the rule's own, e.g. the base resource of a custom method
* @param {(ctx: RuleContext) => Object} [spec.exceptionTarget] the object that carries the exception, defaults to the input
* @param {import('./ruleContext.js').DocumentKind} [spec.document] the document the context reads, defaults to 'resolved'
* @returns {Function & {meta: {appliesTo: Array<Condition>, document: string}}}
* @param {InternalErrorMode} [spec.onInternalError] what happens when check throws, defaults to 'violation'
* @returns {Function & {meta: {appliesTo: Array<Condition>, checkUses: Array<Condition>, document: string, onInternalError: InternalErrorMode}}}
*/
export function defineRule({ appliesTo = [], check, document = 'resolved' }) {
export function defineRule({
appliesTo = [],
check,
beforeCheck,
checkUses = [],
exceptionTarget = (ctx) => ctx.input,
document = 'resolved',
onInternalError = 'violation',
}) {
const collect = (ctx, errors) =>
evaluateAndCollectAdoptionStatus(errors, ctx.ruleName, exceptionTarget(ctx), ctx.path);

const ruleFunction = (input, options, spectralContext) => {
const ctx = createRuleContext(input, options, spectralContext, document);
// Spectral names the function in the error when it throws, and every rule here would otherwise be 'ruleFunction'
Expand All @@ -43,8 +76,30 @@ export function defineRule({ appliesTo = [], check, document = 'resolved' }) {
}
}

return check(ctx);
beforeCheck?.(ctx);

switch (onInternalError) {
case 'violation': {
let errors;
try {
errors = check(ctx);
} catch (e) {
errors = handleInternalError(ctx.ruleName, ctx.path, e);
}
return collect(ctx, errors);
}
case 'return':
try {
return collect(ctx, check(ctx));
} catch (e) {
return handleInternalError(ctx.ruleName, ctx.path, e);
}
case 'throw':
return collect(ctx, check(ctx));
default:
throw new Error(`Unknown onInternalError mode: ${onInternalError}`);
}
};

return Object.assign(ruleFunction, { meta: { appliesTo, document } });
return Object.assign(ruleFunction, { meta: { appliesTo, checkUses, document, onInternalError } });
}
Loading
Loading