Problem/Motivation

Performance analysis of this module with Claude Fable noted the following:

JsonSchemaValidator::validateJsonSchema() constructs a new Validator() per call, so Opis's SchemaLoader memoization never helps — every validation re-reads the schema file from disk, re-decodes it, re-compiles it into Opis schema objects, and re-resolves $ref chains to other schema files.

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

ptmkenny created an issue. See original summary.

ptmkenny’s picture

Fable plan to fix:

 1. Lazily cache one Validator instance on the service

 The service is a container singleton (json_schema_validator.services.yml), so a property survives the request — and the
 whole process in Drush/queue/cron contexts.

 - Add two private properties: private ?Validator $validator = NULL; and private ?array $registeredPrefix = NULL; (the
 [base_url, directory_path] pair backing the cached instance).
 - Add a private getValidator(string $schema_base_url, string $schema_directory_path): Validator that builds the
 validator, asserts the resolver (Assert::isInstanceOf(..., AssertClass::SchemaResolver->value) — existing pattern at
 line 82), registers the prefix once, and stores both properties. Rebuild only when the prefix pair differs from
 $registeredPrefix (guards kernel tests / mid-process config changes).
 - In validateJsonSchema(): keep the per-call validation_on config read (so toggling validation stays immediate; config
 reads are statically cached), keep the two Assert::stringNotEmpty config checks, then call getValidator() instead of
 constructing inline.

 Effect: the schema file read + compile happens once per schema per process instead of once per validation call.

 2. Remove the dead re-encode on the success path

 Delete lines 91–92:

 $encoded_json = json_encode($decoded_json);
 Assert::stringNotEmpty($encoded_json, "Failed to encode JSON schema $schema!");

 The result is assigned to a local and discarded before return TRUE; — a full payload serialization per successful
 validation for nothing.

ptmkenny’s picture

Title: Performance: Use Opis SchemaLoader memoization » Performance: Cache validator to enable downstream SchemaLoader memoization

  • ptmkenny committed 23d3cb05 on 1.0.x
    feat: #3600627 Performance: Cache validator to enable downstream...
ptmkenny’s picture

Status: Active » Fixed

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.