From 6f3b8d09629e45d780793755837776521baa6dd9 Mon Sep 17 00:00:00 2001 From: Mitchell Hentges Date: Wed, 21 Sep 2022 16:35:56 +0200 Subject: [PATCH] Defer schema validation to improve test performance Many modules export an `ajvCompiledJsonSchemaValidator(...)`, which incurs the `ajv` schema compilation at module-import-time. Many tests depend on these modules transitively, but don't exercise the compiled schema - so, this compilation time is wasted. On my machine, with an example test (airbrake/src/index.test.ts) I'm seeing the following numbers (n=10): Before: 6005.1ms After: 5807.8ms Benefit: 197.3ms (~3.3%) Weirdly, the NodeJS profiler was saying that schema compilation was taking ~2000ms, but that is likely due to the inaccuracy of the sampling. Signed-off-by: Mitchell Hentges --- .changeset/bright-rules-shout.md | 5 +++++ packages/catalog-model/src/kinds/util.ts | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 .changeset/bright-rules-shout.md diff --git a/.changeset/bright-rules-shout.md b/.changeset/bright-rules-shout.md new file mode 100644 index 0000000000..f7cdae3b4f --- /dev/null +++ b/.changeset/bright-rules-shout.md @@ -0,0 +1,5 @@ +--- +'@backstage/catalog-model': patch +--- + +Defer `ajv` compilation of schema validators to improve module-import performance diff --git a/packages/catalog-model/src/kinds/util.ts b/packages/catalog-model/src/kinds/util.ts index c77b77cb97..40c88b7066 100644 --- a/packages/catalog-model/src/kinds/util.ts +++ b/packages/catalog-model/src/kinds/util.ts @@ -22,9 +22,12 @@ import { KindValidator } from './types'; // exported kind validators have the `KindValidator` signature which is // different. So let's postpone that change until a later time. export function ajvCompiledJsonSchemaValidator(schema: unknown): KindValidator { - const validator = entityKindSchemaValidator(schema); + let validator: undefined | ((data: unknown) => any); return { async check(data) { + if (!validator) { + validator = entityKindSchemaValidator(schema); + } return validator(data) === data; }, };