Skip to content

bin kind size limits #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 9, 2024
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
3 changes: 2 additions & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
"noCommaOperator": "off",
"useSingleVarDeclarator": "off",
"noUnusedTemplateLiteral": "off",
"useDefaultParameterLast": "off"
"useDefaultParameterLast": "off",
"useEnumInitializers": "off"
},
"suspicious": {
"noExplicitAny": "off",
Expand Down
113 changes: 110 additions & 3 deletions src/codegen/validator/__tests__/codegen.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {b} from '@jsonjoy.com/util/lib/buffers/b';
import {ValidationError} from '../../../constants';
import {type OrSchema, s, type Schema} from '../../../schema';
import {TypeSystem} from '../../../system';
Expand Down Expand Up @@ -125,7 +126,7 @@ describe('"str" type', () => {
exec(type, null, {code: 'STR', errno: ValidationError.STR, message: 'Not a string.', path: []});
});

test('validates minLength', () => {
test('validates "min"', () => {
const type = s.String({min: 3});
exec(type, 'asdf', null);
exec(type, '', {
Expand All @@ -142,7 +143,7 @@ describe('"str" type', () => {
});
});

test('validates maxLength', () => {
test('validates "max"', () => {
const type = s.String({max: 5});
exec(type, '', null);
exec(type, 'asdf', null);
Expand All @@ -161,7 +162,7 @@ describe('"str" type', () => {
});
});

test('validates minLength and maxLength', () => {
test('validates "min" and "max"', () => {
const type = s.String({min: 3, max: 5});
exec(type, 'aaa', null);
exec(type, 'bbbb', null);
Expand All @@ -186,6 +187,112 @@ describe('"str" type', () => {
});
});

test('validates "min" and "max" of equal size', () => {
const type = s.String({min: 4, max: 4});
exec(type, 'aaa', {
code: 'STR_LEN',
errno: ValidationError.STR_LEN,
message: 'Invalid string length.',
path: [],
});
exec(type, 'bbbb', null);
exec(type, 'vvvvv', {
code: 'STR_LEN',
errno: ValidationError.STR_LEN,
message: 'Invalid string length.',
path: [],
});
exec(type, '', {
code: 'STR_LEN',
errno: ValidationError.STR_LEN,
message: 'Invalid string length.',
path: [],
});
exec(type, 'asdfdf', {
code: 'STR_LEN',
errno: ValidationError.STR_LEN,
message: 'Invalid string length.',
path: [],
});
exec(type, 'aasdf sdfdf', {
code: 'STR_LEN',
errno: ValidationError.STR_LEN,
message: 'Invalid string length.',
path: [],
});
});
});

describe('"bin" type', () => {
test('validates a binary blob', () => {
const type = s.bin;
exec(type, b(), null);
exec(type, b(1, 2, 3), null);
exec(type, 123, {code: 'BIN', errno: ValidationError.BIN, message: 'Not a binary.', path: []});
exec(type, null, {code: 'BIN', errno: ValidationError.BIN, message: 'Not a binary.', path: []});
});

test('validates "min"', () => {
const type = s.Binary(s.any, {min: 3});
exec(type, b(1, 2, 3, 4), null);
exec(type, b(), {
code: 'BIN_LEN',
errno: ValidationError.BIN_LEN,
message: 'Invalid binary length.',
path: [],
});
exec(type, b(1, 2), {
code: 'BIN_LEN',
errno: ValidationError.BIN_LEN,
message: 'Invalid binary length.',
path: [],
});
});

test('validates "max"', () => {
const type = s.Binary(s.any, {max: 5});
exec(type, b(), null);
exec(type, b(1, 2, 3, 4), null);
exec(type, b(1, 2, 3, 4, 5), null);
exec(type, b(1, 2, 3, 4, 5, 6), {
code: 'BIN_LEN',
errno: ValidationError.BIN_LEN,
message: 'Invalid binary length.',
path: [],
});
exec(type, b(1, 2, 3, 4, 5, 6, 7, 8, 9), {
code: 'BIN_LEN',
errno: ValidationError.BIN_LEN,
message: 'Invalid binary length.',
path: [],
});
});

test('validates "min" and "max"', () => {
const type = s.Binary(s.any, {min: 3, max: 5});
exec(type, b(1, 2, 3), null);
exec(type, b(1, 2, 3, 4), null);
exec(type, b(1, 2, 3, 4, 5), null);
exec(type, b(), {
code: 'BIN_LEN',
errno: ValidationError.BIN_LEN,
message: 'Invalid binary length.',
path: [],
});
exec(type, b(1, 2, 3, 4, 5, 6), {
code: 'BIN_LEN',
errno: ValidationError.BIN_LEN,
message: 'Invalid binary length.',
path: [],
});
exec(type, b(1, 2, 3, 4, 5, 6, 7, 8, 9), {
code: 'BIN_LEN',
errno: ValidationError.BIN_LEN,
message: 'Invalid binary length.',
path: [],
});
});

test('validates minLength and maxLength of equal size', () => {
const type = s.String({min: 4, max: 4});
exec(type, 'aaa', {
Expand Down
53 changes: 30 additions & 23 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,34 @@
/** Validation error codes. */
/**
* Validation error codes.
*
* ATTENTION: Only add new error codes at the end of the list !!!
* =========
*/
export enum ValidationError {
STR = 0,
NUM = 1,
BOOL = 2,
ARR = 3,
TUP = 4,
OBJ = 5,
MAP = 6,
KEY = 7,
KEYS = 8,
BIN = 9,
OR = 10,
REF = 11,
ENUM = 12,
CONST = 13,
VALIDATION = 14,
INT = 15,
UINT = 16,
STR_LEN = 17,
ARR_LEN = 18,
GT = 19,
GTE = 20,
LT = 21,
LTE = 22,
NUM,
BOOL,
ARR,
TUP,
OBJ,
MAP,
KEY,
KEYS,
BIN,
OR,
REF,
ENUM,
CONST,
VALIDATION,
INT,
UINT,
STR_LEN,
ARR_LEN,
GT,
GTE,
LT,
LTE,
BIN_LEN,
}

/** Human-readable error messages by error code. */
Expand All @@ -45,6 +51,7 @@ export const ValidationErrorMessage = {
[ValidationError.INT]: 'Not an integer.',
[ValidationError.UINT]: 'Not an unsigned integer.',
[ValidationError.STR_LEN]: 'Invalid string length.',
[ValidationError.BIN_LEN]: 'Invalid binary length.',
[ValidationError.ARR_LEN]: 'Invalid array length.',
[ValidationError.GT]: 'Value is too small.',
[ValidationError.GTE]: 'Value is too small.',
Expand Down
3 changes: 2 additions & 1 deletion src/schema/SchemaBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ export class SchemaBuilder {
return {kind: 'str', ...(a || {})};
}

public Binary<T extends Schema>(type: T, options: Optional<BinarySchema> = {}): BinarySchema {
// public Binary<T extends Schema>(options: Optional<BinarySchema<T>> & Pick<BinarySchema<T>, 'type'>): BinarySchema<T>;
public Binary<T extends Schema>(type: T, options: Optional<Omit<BinarySchema, 'type'>> = {}): BinarySchema<T> {
return {
kind: 'bin',
type,
Expand Down
8 changes: 8 additions & 0 deletions src/schema/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,18 @@ export interface StringSchema extends TType<string>, WithValidator {
*/
export interface BinarySchema<T extends TType = any> extends TType, WithValidator {
kind: 'bin';

/** Type of value encoded in the binary data. */
type: T;

/** Codec used for encoding the binary data. */
format?: 'json' | 'cbor' | 'msgpack' | 'resp3' | 'ion' | 'bson' | 'ubjson' | 'bencode';

/** Minimum size in octets. */
min?: number;

/** Maximum size in octets. */
max?: number;
}

/**
Expand Down
37 changes: 34 additions & 3 deletions src/type/classes/BinaryType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {printTree} from 'tree-dump/lib/printTree';
import * as schema from '../../schema';
import {RandomJson} from '@jsonjoy.com/util/lib/json-random';
import {stringifyBinary} from '@jsonjoy.com/json-pack/lib/json-binary';
import {validateTType} from '../../schema/validate';
import {validateMinMax, validateTType} from '../../schema/validate';
import type {ValidatorCodegenContext} from '../../codegen/validator/ValidatorCodegenContext';
import type {ValidationPath} from '../../codegen/validator/types';
import {ValidationError} from '../../constants';
Expand All @@ -23,6 +23,17 @@ import type {json_string} from '@jsonjoy.com/util/lib/json-brand';
import type * as ts from '../../typescript/types';
import type {TypeExportContext} from '../../system/TypeExportContext';

const formats = new Set<schema.BinarySchema['format']>([
'bencode',
'bson',
'cbor',
'ion',
'json',
'msgpack',
'resp3',
'ubjson',
]);

export class BinaryType<T extends Type> extends AbstractType<schema.BinarySchema> {
protected schema: schema.BinarySchema;

Expand Down Expand Up @@ -54,7 +65,13 @@ export class BinaryType<T extends Type> extends AbstractType<schema.BinarySchema
}

public validateSchema(): void {
validateTType(this.getSchema(), 'bin');
const schema = this.getSchema();
validateTType(schema, 'bin');
const {min, max, format} = schema;
validateMinMax(min, max);
if (format !== undefined) {
if (!formats.has(format)) throw new Error('FORMAT');
}
this.type.validateSchema();
}

Expand All @@ -63,8 +80,22 @@ export class BinaryType<T extends Type> extends AbstractType<schema.BinarySchema
const err = ctx.err(ValidationError.BIN, path);
ctx.js(
// prettier-ignore
/* js */ `if(!(${r} instanceof Uint8Array)${hasBuffer ? /* js */ ` && !Buffer.isBuffer(${r})` : ''}) return ${err};`,
`if(!(${r} instanceof Uint8Array)${hasBuffer ? ` && !Buffer.isBuffer(${r})` : ''}) return ${err};`,
);
const {min, max} = this.schema;
if (typeof min === 'number' && min === max) {
const err = ctx.err(ValidationError.BIN_LEN, path);
ctx.js(`if(${r}.length !== ${min}) return ${err};`);
} else {
if (typeof min === 'number') {
const err = ctx.err(ValidationError.BIN_LEN, path);
ctx.js(`if(${r}.length < ${min}) return ${err};`);
}
if (typeof max === 'number') {
const err = ctx.err(ValidationError.BIN_LEN, path);
ctx.js(`if(${r}.length > ${max}) return ${err};`);
}
}
ctx.emitCustomValidators(this, path, r);
}

Expand Down