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

BUG: Avoid stackoverflows and memory issues in zod while processing large strings #3880

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
48 changes: 48 additions & 0 deletions src/helpers/parseUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,54 @@ export interface ParseContext {
readonly parsedType: ZodParsedType;
}

/**
* Processes a large input string in chunks and validates each chunk using a custom processor.
* Optimized for speed and memory efficiency with configurable chunk and batch sizes.
*
* @param {string} input - The input string to be processed in chunks.
* @param {number} chunkSize - The size of each chunk in characters.
* @param {number} batchSize - The number of chunks to process in one batch.
* @param {(chunk: string) => boolean} processor - A function to validate each chunk. Should return `true` if valid, `false` otherwise.
* @returns {boolean} - Returns `true` if all chunks pass validation, otherwise `false`.
*
* @example
* const isValid = processInChunks(
* largeString,
* 2048, // chunk size
* 4, // batch size
* (chunk) => /^[A-Za-z0-9+/]+={0,2}$/.test(chunk)
* );
* console.log(isValid); // true or false
*/
export function processInChunks(
input: string,
chunkSize: number,
batchSize: number,
processor: (chunk: string) => boolean
): boolean {
// Handle single chunk case and length of 0
if (input.length <= chunkSize) return processor(input);

const totalChunks = Math.ceil(input.length / chunkSize);

// Process chunks in batches
for (let i = 0; i < totalChunks; i += batchSize) {
const batchLimit = Math.min(i + batchSize, totalChunks);

for (let j = i; j < batchLimit; j++) {
const startIndex = j * chunkSize;
const chunk = input.slice(startIndex, startIndex + chunkSize);

// Stop processing on the first failure
if (!processor(chunk)) {
return false;
}
}
}

return true;
}

export type ParseInput = {
data: any;
path: (string | number)[];
Expand Down
3 changes: 2 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
ParseReturnType,
ParseStatus,
SyncParseReturnType,
processInChunks,
} from "./helpers/parseUtil";
import { partialUtil } from "./helpers/partialUtil";
import { Primitive } from "./helpers/typeAliases";
Expand Down Expand Up @@ -934,7 +935,7 @@ export class ZodString extends ZodType<string, ZodStringDef, string> {
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
if(!processInChunks(input.data, 2048, 4, (chunk)=>base64Regex(chunk))) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
Expand Down