diff --git a/packages/concerto-core/src/index.ts b/packages/concerto-core/src/index.ts index 01d7ae0aee..79209d7719 100644 --- a/packages/concerto-core/src/index.ts +++ b/packages/concerto-core/src/index.ts @@ -39,6 +39,7 @@ import RelationshipDeclaration = require("./introspect/relationshipdeclaration") import Validator = require("./introspect/validator"); import NumberValidator = require("./introspect/numbervalidator"); import StringValidator = require("./introspect/stringvalidator"); +import CollectionSizeValidator = require("./introspect/collectionsizevalidator"); import Typed = require("./model/typed"); import Identifiable = require("./model/identifiable"); import Relationship = require("./model/relationship"); @@ -82,9 +83,10 @@ export { Field, EnumDeclaration, RelationshipDeclaration, - Validator, - NumberValidator, - StringValidator, + Validator, + NumberValidator, + StringValidator, + CollectionSizeValidator, Typed, Identifiable, Relationship, diff --git a/packages/concerto-core/src/introspect/collectionsizevalidator.ts b/packages/concerto-core/src/introspect/collectionsizevalidator.ts new file mode 100644 index 0000000000..e653ab35ee --- /dev/null +++ b/packages/concerto-core/src/introspect/collectionsizevalidator.ts @@ -0,0 +1,120 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const { isNull } = require('@accordproject/concerto-util').NullUtil; +const Validator = require('./validator'); + +/** + * A Validator to enforce that a collection (array or map) has a size within a specified range. + * @private + * @class + * @memberof module:concerto-core + */ +class CollectionSizeValidator extends Validator { + + /** + * Create a CollectionSizeValidator. + * @param {Object} field - the field or declarations this validator is attached to + * @param {Object} validator - The size validation object - [minSize, maxSize] (inclusive). + * + * @throws {IllegalModelException} + */ + constructor(field, validator) { + super(field, validator); + this.minSize = validator.minSize ?? null; + this.maxSize = validator.maxSize ?? null; + + if (isNull(this.minSize) && isNull(this.maxSize)) { + this.reportError(field.getName(), 'Invalid collection size, minSize and/or maxSize must be specified.'); + } else if (this.minSize < 0 || this.maxSize < 0) { + this.reportError(field.getName(), 'minSize and/or maxSize must be positive integers.'); + } else if (isNull(this.minSize) || isNull(this.maxSize)) { + // this is fine and means that we don't need to check whether minSize > maxSize + } else if (this.minSize > this.maxSize) { + this.reportError(field.getName(), 'minSize must be less than or equal to maxSize.'); + } + } + + /** + * Validate the property + * @param {string} identifier the identifier of the instance being validated + * @param {number} value the collection size to validate + * @throws {IllegalModelException} + * @private + */ + validate(identifier, value) { + if(!isNull(this.minSize) && value < this.minSize) { + this.reportError(identifier, `Collection must contain at least ${this.minSize} elements.`); + } + if(!isNull(this.maxSize) && value > this.maxSize) { + this.reportError(identifier, `Collection must contain no more than ${this.maxSize} elements.`); + } + } + + /** + * Returns the minSize for this validator, or null if not specified + * @returns {number} the min size or null + */ + getMinSize() { + return this.minSize; + } + + /** + * Returns the maxSize for this validator, or null if not specified + * @returns {number} the max size or null + */ + getMaxSize() { + return this.maxSize; + } + + /** + * Determine if the validator is compatible with another validator. For the + * validators to be compatible, all values accepted by this validator must + * be accepted by the other validator. + * @param {Validator} other the other validator. + * @returns {boolean} True if this validator is compatible with the other + * validator, false otherwise. + */ + compatibleWith(other) { + if (!(other instanceof CollectionSizeValidator)) { + return false; + } + + const thisMinSize = this.getMinSize(); + const otherMinSize = other.getMinSize(); + if (isNull(thisMinSize) && !isNull(otherMinSize)) { + return false; + } else if (!isNull(thisMinSize) && !isNull(otherMinSize)) { + if (thisMinSize < otherMinSize) { + return false; + } + } + + const thisMaxSize = this.getMaxSize(); + const otherMaxSize = other.getMaxSize(); + if (isNull(thisMaxSize) && !isNull(otherMaxSize)) { + return false; + } else if (!isNull(thisMaxSize) && !isNull(otherMaxSize)) { + if (thisMaxSize > otherMaxSize) { + return false; + } + } + + return true; + } +} + +export = CollectionSizeValidator; diff --git a/packages/concerto-core/src/introspect/property.ts b/packages/concerto-core/src/introspect/property.ts index d7959c38f9..06ab054284 100644 --- a/packages/concerto-core/src/introspect/property.ts +++ b/packages/concerto-core/src/introspect/property.ts @@ -19,6 +19,7 @@ const { MetaModelNamespace } = require('@accordproject/concerto-metamodel'); const ModelUtil = require('../modelutil'); const IllegalModelException = require('./illegalmodelexception'); const Decorated = require('./decorated'); +const CollectionSizeValidator = require('./collectionsizevalidator'); // Types needed for TypeScript generation. /* eslint-disable no-unused-vars */ @@ -121,6 +122,10 @@ class Property extends Decorated { this.array = true; } + this.sizeValidator = this.ast.sizeValidator + ? new CollectionSizeValidator(this, this.ast.sizeValidator) + : null; + if(this.ast.isOptional) { this.optional = true; } @@ -141,6 +146,25 @@ class Property extends Decorated { if(this.type) { classDecl.getModelFile().resolveType( 'property ' + this.getFullyQualifiedName(), this.type); } + + if(this.sizeValidator && !this.array) { + let isMapType = false; + if(this.type && !this.isPrimitive()) { + try { + const resolvedType = classDecl.getModelFile().getType(this.type); + isMapType = resolvedType.isMapDeclaration?.() === true; + } catch(e) { + // type resolution failed — will be caught by other validation + } + } + if(!isMapType) { + throw new IllegalModelException( + `size validator can only be applied to array or map properties: ${this.getFullyQualifiedName()}`, + classDecl.getModelFile(), + this.ast.location + ); + } + } } /** @@ -216,6 +240,14 @@ class Property extends Decorated { return this.array; } + /** + * Returns the collection size validator for this property, if one exists. + * @return {CollectionSizeValidator|null} the validator or null + */ + getSizeValidator() { + return this.sizeValidator; + } + /** * Returns true if the field is declared as an enumerated value diff --git a/packages/concerto-core/test/introspect/collectionsizevalidator.js b/packages/concerto-core/test/introspect/collectionsizevalidator.js new file mode 100644 index 0000000000..a7d90d5178 --- /dev/null +++ b/packages/concerto-core/test/introspect/collectionsizevalidator.js @@ -0,0 +1,170 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const chai = require('chai'); +chai.should(); + +const CollectionSizeValidator = require('../../src/introspect/collectionsizevalidator'); + +describe('CollectionSizeValidator', () => { + + const mockField = { + getName: () => 'testField', + getFullyQualifiedName: () => 'org.example.Thing.testField', + }; + + describe('#constructor', () => { + + it('should create with both minSize and maxSize', () => { + const v = new CollectionSizeValidator(mockField, { minSize: 1, maxSize: 10 }); + v.getMinSize().should.equal(1); + v.getMaxSize().should.equal(10); + }); + + it('should create with minSize only', () => { + const v = new CollectionSizeValidator(mockField, { minSize: 3 }); + v.getMinSize().should.equal(3); + chai.expect(v.getMaxSize()).to.be.null; + }); + + it('should create with maxSize only', () => { + const v = new CollectionSizeValidator(mockField, { maxSize: 5 }); + chai.expect(v.getMinSize()).to.be.null; + v.getMaxSize().should.equal(5); + }); + + it('should throw when neither minSize nor maxSize specified', () => { + (() => new CollectionSizeValidator(mockField, {})) + .should.throw(/minSize and\/or maxSize must be specified/); + }); + + it('should throw when minSize is negative', () => { + (() => new CollectionSizeValidator(mockField, { minSize: -1 })) + .should.throw(/positive integers/); + }); + + it('should throw when maxSize is negative', () => { + (() => new CollectionSizeValidator(mockField, { maxSize: -2 })) + .should.throw(/positive integers/); + }); + + it('should throw when minSize > maxSize', () => { + (() => new CollectionSizeValidator(mockField, { minSize: 5, maxSize: 2 })) + .should.throw(/minSize must be less than or equal to maxSize/); + }); + + it('should allow minSize equal to maxSize', () => { + const v = new CollectionSizeValidator(mockField, { minSize: 3, maxSize: 3 }); + v.getMinSize().should.equal(3); + v.getMaxSize().should.equal(3); + }); + + it('should allow minSize of zero', () => { + const v = new CollectionSizeValidator(mockField, { minSize: 0, maxSize: 5 }); + v.getMinSize().should.equal(0); + }); + }); + + describe('#validate', () => { + + it('should pass when value is within bounds', () => { + const v = new CollectionSizeValidator(mockField, { minSize: 1, maxSize: 5 }); + v.validate('id', 1); + v.validate('id', 3); + v.validate('id', 5); + }); + + it('should throw when value is below minSize', () => { + const v = new CollectionSizeValidator(mockField, { minSize: 2, maxSize: 5 }); + (() => v.validate('id', 1)).should.throw(/at least 2 elements/); + (() => v.validate('id', 0)).should.throw(/at least 2 elements/); + }); + + it('should throw when value exceeds maxSize', () => { + const v = new CollectionSizeValidator(mockField, { minSize: 1, maxSize: 3 }); + (() => v.validate('id', 4)).should.throw(/no more than 3 elements/); + }); + + it('should only enforce minSize when maxSize is null', () => { + const v = new CollectionSizeValidator(mockField, { minSize: 2 }); + v.validate('id', 100); + (() => v.validate('id', 1)).should.throw(/at least 2 elements/); + }); + + it('should only enforce maxSize when minSize is null', () => { + const v = new CollectionSizeValidator(mockField, { maxSize: 3 }); + v.validate('id', 0); + (() => v.validate('id', 4)).should.throw(/no more than 3 elements/); + }); + }); + + describe('#compatibleWith', () => { + + const validator = (opts) => new CollectionSizeValidator(mockField, opts); + + it('should return false for non-CollectionSizeValidator', () => { + validator({ minSize: 1 }).compatibleWith({}).should.equal(false); + }); + + it('should be compatible when other is more permissive (loosened)', () => { + validator({ minSize: 2, maxSize: 5 }) + .compatibleWith(validator({ minSize: 1, maxSize: 6 })) + .should.equal(true); + }); + + it('should be incompatible when other tightens minSize', () => { + validator({ minSize: 1, maxSize: 5 }) + .compatibleWith(validator({ minSize: 3, maxSize: 5 })) + .should.equal(false); + }); + + it('should be incompatible when other tightens maxSize', () => { + validator({ minSize: 1, maxSize: 5 }) + .compatibleWith(validator({ minSize: 1, maxSize: 3 })) + .should.equal(false); + }); + + it('should be incompatible when this has no min and other adds one', () => { + validator({ maxSize: 10 }) + .compatibleWith(validator({ minSize: 1, maxSize: 10 })) + .should.equal(false); + }); + + it('should be incompatible when this has no max and other adds one', () => { + validator({ minSize: 1 }) + .compatibleWith(validator({ minSize: 1, maxSize: 10 })) + .should.equal(false); + }); + + it('should be compatible when other removes max', () => { + validator({ minSize: 1, maxSize: 5 }) + .compatibleWith(validator({ minSize: 1 })) + .should.equal(true); + }); + + it('should be compatible when other removes min', () => { + validator({ minSize: 1, maxSize: 5 }) + .compatibleWith(validator({ maxSize: 5 })) + .should.equal(true); + }); + + it('should be compatible with identical validator', () => { + validator({ minSize: 2, maxSize: 8 }) + .compatibleWith(validator({ minSize: 2, maxSize: 8 })) + .should.equal(true); + }); + }); +}); diff --git a/packages/concerto-core/test/introspect/property.js b/packages/concerto-core/test/introspect/property.js index 683175b09d..9885dc6386 100644 --- a/packages/concerto-core/test/introspect/property.js +++ b/packages/concerto-core/test/introspect/property.js @@ -168,4 +168,88 @@ describe('Property - Test for property types using Import Aliasing', () => { }); + describe('#getSizeValidator', () => { + + it('should reject size on a non-array String property', () => { + (() => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nconcept A { o String name size=[1,5] }'); + }).should.throw(/size validator can only be applied to array or map/); + }); + + it('should reject size on a non-array Integer property', () => { + (() => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nconcept A { o Integer count size=[1,5] }'); + }).should.throw(/size validator can only be applied to array or map/); + }); + + it('should reject size on a non-array, non-map object property', () => { + (() => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nconcept B { o String x }\nconcept A { o B thing size=[1,5] }'); + }).should.throw(/size validator can only be applied to array or map/); + }); + + it('should reject negative minSize', () => { + (() => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nconcept A { o String[] tags size=[-1,5] }'); + }).should.throw(/positive integers/); + }); + + it('should reject negative maxSize', () => { + (() => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nconcept A { o String[] tags size=[1,-5] }'); + }).should.throw(/positive integers/); + }); + + it('should reject minSize greater than maxSize', () => { + (() => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nconcept A { o String[] tags size=[10,2] }'); + }).should.throw(/minSize must be less than or equal to maxSize/); + }); + + it('should allow size on an array property', () => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nconcept A { o String[] tags size=[1,10] }'); + const prop = mm.getType('t@1.0.0.A').getProperty('tags'); + prop.getSizeValidator().getMinSize().should.equal(1); + prop.getSizeValidator().getMaxSize().should.equal(10); + }); + + it('should allow size on a map-typed property', () => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nmap M { o String\n o String }\nconcept A { o M data size=[1,5] }'); + const prop = mm.getType('t@1.0.0.A').getProperty('data'); + prop.getSizeValidator().getMinSize().should.equal(1); + prop.getSizeValidator().getMaxSize().should.equal(5); + }); + + it('should allow size on a map-typed property imported from another namespace', () => { + const mm = new ModelManager(); + mm.addCTOModel('namespace maps@1.0.0\nmap PhoneBook { o String\n o String }'); + mm.addCTOModel('namespace t@1.0.0\nimport maps@1.0.0.PhoneBook\nconcept A { o PhoneBook contacts size=[1,10] }'); + const prop = mm.getType('t@1.0.0.A').getProperty('contacts'); + prop.getSizeValidator().getMinSize().should.equal(1); + }); + + it('should allow size on a relationship array', () => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nconcept P identified by id { o String id }\nconcept A { --> P[] refs size=[1,3] }'); + const prop = mm.getType('t@1.0.0.A').getProperty('refs'); + prop.getSizeValidator().getMinSize().should.equal(1); + }); + + it('should return null when no size validator', () => { + const mm = new ModelManager(); + mm.addCTOModel('namespace t@1.0.0\nconcept A { o String[] tags }'); + const prop = mm.getType('t@1.0.0.A').getProperty('tags'); + should.equal(prop.getSizeValidator(), null); + }); + + }); + });