Skip to content
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

perf: Faster JSON validation #218

Merged
merged 6 commits into from
Oct 21, 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
18 changes: 17 additions & 1 deletion src/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ describe('json', () => {
const [error] = validate(undefined, JsonStruct);
assert(error !== undefined);
expect(error.message).toBe(
'Expected the value to satisfy a union of `literal | boolean | finite number | string | array | record`, but received: undefined',
'Expected a value of type `JSON`, but received: `undefined`',
);
});
});
Expand Down Expand Up @@ -418,6 +418,22 @@ describe('json', () => {
assertIsJsonRpcRequest(JSON_RPC_REQUEST_FIXTURES.invalid[0]),
).toThrow('Invalid JSON-RPC request: oops');
});

it('is fast for large inputs', () => {
const request = {
jsonrpc: '2.0',
id: 'foo',
method: 'wallet_invokeSnap',
params: {
snapId: 'npm:@metamask/manage-state-example-snap',
request: {
method: 'setState',
params: { items: new Array(9999999).fill(2) },
},
},
};
expect(() => assertIsJsonRpcRequest(request)).not.toThrow();
});
});

describe('isJsonRpcSuccess', () => {
Expand Down
69 changes: 48 additions & 21 deletions src/json.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import {
any,
array,
boolean,
coerce,
create,
define,
integer,
is,
lazy,
literal,
nullable,
number,
Expand Down Expand Up @@ -154,33 +152,62 @@ export function exactOptional<Type, Schema>(
}

/**
* A struct to check if the given value is finite number. Superstruct's
* `number()` struct does not check if the value is finite.
* Validate an unknown input to be valid JSON.
*
* @returns A struct to check if the given value is finite number.
* Useful for constructing JSON structs.
*
* @param json - An unknown value.
* @returns True if the value is valid JSON, otherwise false.
*/
const finiteNumber = () =>
define<number>('finite number', (value) => {
return is(value, number()) && Number.isFinite(value);
});
function validateJson(json: unknown): boolean {
if (json === null || typeof json === 'boolean' || typeof json === 'string') {
return true;
}

if (typeof json === 'number' && Number.isFinite(json)) {
return true;
}

if (typeof json === 'object') {
let every = true;
if (Array.isArray(json)) {
// Ignoring linting error since for-of is significantly slower than a normal for-loop
// and performance is important in this specific function.
// eslint-disable-next-line @typescript-eslint/prefer-for-of
FrederikBolding marked this conversation as resolved.
Show resolved Hide resolved
for (let i = 0; i < json.length; i++) {
if (!validateJson(json[i])) {
every = false;
break;
}
}
return every;
}

const entries = Object.entries(json);
// Ignoring linting errors since for-of is significantly slower than a normal for-loop
// and performance is important in this specific function.
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < entries.length; i++) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (typeof entries[i]![0] !== 'string' || !validateJson(entries[i]![1])) {
every = false;
break;
}
}
return every;
}

return false;
}

/**
* A struct to check if the given value is a valid JSON-serializable value.
*
* Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.
*/
// We cannot infer the type of the struct, because it is recursive.
export const UnsafeJsonStruct: Struct<Json> = union([
literal(null),
boolean(),
finiteNumber(),
string(),
array(lazy(() => UnsafeJsonStruct)),
record(
string(),
lazy(() => UnsafeJsonStruct),
),
]);
export const UnsafeJsonStruct: Struct<Json> = define('JSON', (json) =>
validateJson(json),
);

/**
* A struct to check if the given value is a valid JSON-serializable value.
Expand Down
Loading