From da5347580dc3853532927655dc9245793cc4acbc Mon Sep 17 00:00:00 2001 From: Danny Browning Date: Wed, 15 May 2024 11:32:35 -0600 Subject: [PATCH] fix: cache ajv schemas rather than ajv objects for schema validation (#3228) * fix: cache ajv schemas rather than ajv objects for schema validation * fix: remove lru cache and use ajv caching properly --- .../package.json | 1 - .../src/schema-utils.ts | 20 +++++++++---------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/packages/stream-model-instance-handler/package.json b/packages/stream-model-instance-handler/package.json index 995676b33f..87bc57e64b 100644 --- a/packages/stream-model-instance-handler/package.json +++ b/packages/stream-model-instance-handler/package.json @@ -46,7 +46,6 @@ "ajv": "^8.8.2", "ajv-formats": "^2.1.1", "fast-json-patch": "^3.1.0", - "least-recent": "^1.0.3", "lodash.clonedeep": "^4.5.0", "uint8arrays": "^5.0.1" }, diff --git a/packages/stream-model-instance-handler/src/schema-utils.ts b/packages/stream-model-instance-handler/src/schema-utils.ts index 378f89f3ca..db25426d05 100644 --- a/packages/stream-model-instance-handler/src/schema-utils.ts +++ b/packages/stream-model-instance-handler/src/schema-utils.ts @@ -1,8 +1,5 @@ import Ajv, { SchemaObject } from 'ajv/dist/2020.js' import addFormats from 'ajv-formats' -import { LRUCache } from 'least-recent' - -const AJV_CACHE_SIZE = 500 function buildAjv(): Ajv { const validator = new Ajv({ @@ -21,22 +18,23 @@ function buildAjv(): Ajv { * TODO: Move schema stream loading out of this. */ export class SchemaValidation { - readonly validators: LRUCache + readonly ajv: Ajv constructor() { - this.validators = new LRUCache(AJV_CACHE_SIZE) + this.ajv = buildAjv() } public validateSchema(content: Record, schema: SchemaObject, schemaId: string) { - let validator = this.validators.get(schemaId) - if (!validator) { - validator = buildAjv() - this.validators.set(schemaId, validator) + let existingSchema = this.ajv.getSchema(schemaId) + if (!existingSchema) { + this.ajv.addSchema(schema, schemaId) + //we've added the schema above, so ajv will have it + existingSchema = this.ajv.getSchema(schemaId)! } - const isValid = validator.validate(schema, content) + const isValid = existingSchema(content) if (!isValid) { - const errorMessages = validator.errorsText() + const errorMessages = this.ajv.errorsText(existingSchema.errors) throw new Error(`Validation Error: ${errorMessages}`) } }