From 86c849993738e58c1e5fbb68322ac01e028f6731 Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Sat, 5 Dec 2026 13:08:45 +0530 Subject: [PATCH 1/2] fix(import): refuse a JSONL line longer than 8 MiB Signed-off-by: Priyanshubhartistm --- .changeset/import-bound-jsonl-record-size.md | 5 + docs/OPERATIONS.md | 1 + src/services/event-import-service.ts | 75 +++++++++++-- .../services/event-import-service.spec.ts | 100 +++++++++++++++++- 4 files changed, 170 insertions(+), 11 deletions(-) create mode 100644 .changeset/import-bound-jsonl-record-size.md diff --git a/.changeset/import-bound-jsonl-record-size.md b/.changeset/import-bound-jsonl-record-size.md new file mode 100644 index 000000000..0d89e066a --- /dev/null +++ b/.changeset/import-bound-jsonl-record-size.md @@ -0,0 +1,5 @@ +--- +"nostream": patch +--- + +`nostream import` no longer reads a JSONL line of any length. The importer held a whole line in memory before parsing it, so a small gzip or xz file that decodes to one newline-free line of gigabytes could exhaust its memory. A line longer than 8 MiB, about twice the largest deletion request the importer accepts, now stops the import with an error that names the line, and the input and its decompressor are closed. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index 47f82b94a..d2ea397eb 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -87,6 +87,7 @@ The importer: - Processes the file line-by-line to keep memory usage bounded. - Streams JSON array items one by one to keep memory usage bounded. +- Stops the import with an error on a JSONL line longer than 8,388,608 characters (8 MiB), without reading the rest of it: a line is held whole before it is parsed, and a small compressed file can decode to a single line of any length. Lines before it are not affected, and the longest deletion request the importer accepts is about 4.8 million characters, so no valid input is refused. - Validates NIP-01 schema, event id hash, and Schnorr signature before insertion. - Refuses a deletion request (kind `5`) whose `e` tags name more than 65,533 distinct event ids: nothing it names is deleted, the request itself is not stored, and it counts under `Errors` with the reason `invalid: a deletion request may name at most 65533 events`. An id repeated in several `e` tags counts once, and `a` tags are not counted, as v3 does not act on them. The ids are deleted with one statement, and 65,533 is as many as PostgreSQL's 65,535 bind parameters leave room for, so this limit refuses no deletion request a v3 relay could have applied, live, from a peer or by an earlier import. - Writes each flush as two statements: one multi-row insert for regular events, then one upsert for replaceable ones. A kind `5` delete flushes first, so one batch can become several flushes. There is no transaction spanning them, and a statement that fails inserts nothing and counts its own events as skipped, which is why `Skipped` above can include events that were valid on their own. The insert runs first, so a failed upsert leaves that flush's regular events already written. diff --git a/src/services/event-import-service.ts b/src/services/event-import-service.ts index 04c971276..2c8dc5fae 100644 --- a/src/services/event-import-service.ts +++ b/src/services/event-import-service.ts @@ -1,5 +1,5 @@ import fs from 'fs' -import readline from 'readline' +import { StringDecoder } from 'string_decoder' const streamArrayModule = require('stream-json/streamers/stream-array.js') as { default: { withParserAsStream: () => NodeJS.ReadWriteStream } @@ -94,8 +94,63 @@ export interface EventImportLineError { reason: string } +/** + * The most characters one line of a JSONL file may have. A deletion request naming MAX_IMPORTED_DELETION_TARGETS events + * is about 4.8 million characters, so this leaves room for it. A line is held whole before it is parsed, and a small + * compressed file can decode to a single line of any length, so a longer one stops the import instead of being read. + */ +export const MAX_IMPORTED_RECORD_LENGTH = 8_388_608 + +const LINE_BREAK = /\r\n|\n|\r/ + +/** + * Reads the lines of a stream the way `readline` does, a line break being `\n`, `\r\n` or `\r`, but refuses a line longer + * than `maxLength` before it grows any further: at most `maxLength` characters and one chunk are held at a time. + */ +async function* readBoundedLines(input: NodeJS.ReadableStream, maxLength: number): AsyncGenerator { + const decoder = new StringDecoder('utf8') + let pending = '' + let lineNumber = 0 + + const refuse = (): never => { + throw new Error(`invalid: line ${lineNumber + 1} is longer than ${maxLength} characters`) + } + + for await (const chunk of input) { + pending += typeof chunk === 'string' ? chunk : decoder.write(chunk) + + // A \r at the end may be the first half of a \r\n that the next chunk completes. + const held = pending.endsWith('\r') ? '\r' : '' + const lines = (held ? pending.slice(0, -1) : pending).split(LINE_BREAK) + pending = (lines.pop() as string) + held + + for (const line of lines) { + if (line.length > maxLength) { + refuse() + } + lineNumber += 1 + yield line + } + + if (pending.length > maxLength) { + refuse() + } + } + + pending += decoder.end() + const last = pending.endsWith('\r') ? pending.slice(0, -1) : pending + if (last.length > maxLength) { + refuse() + } + if (last.length > 0) { + yield last + } +} + export interface EventImportOptions { batchSize?: number + /** Characters allowed in one line of a JSONL file. Defaults to MAX_IMPORTED_RECORD_LENGTH. */ + maxRecordLength?: number onLineError?: (lineError: EventImportLineError) => void onProgress?: (stats: EventImportStats) => void } @@ -223,7 +278,10 @@ export class EventImportService { input: NodeJS.ReadableStream, options: EventImportOptions = {}, ): Promise { - return this.importFromCandidates(this.readJsonlCandidatesFromStream(input), options) + return this.importFromCandidates( + this.readJsonlCandidatesFromStream(input, options.maxRecordLength ?? MAX_IMPORTED_RECORD_LENGTH), + options, + ) } public async importFromJsonl(filePath: string, options: EventImportOptions = {}): Promise { @@ -238,16 +296,14 @@ export class EventImportService { return this.importFromCandidates(this.readJsonArrayCandidates(filePath), options) } - private async *readJsonlCandidatesFromStream(input: NodeJS.ReadableStream): AsyncGenerator { - const lineReader = readline.createInterface({ - crlfDelay: Infinity, - input, - }) - + private async *readJsonlCandidatesFromStream( + input: NodeJS.ReadableStream, + maxRecordLength: number, + ): AsyncGenerator { let lineNumber = 0 try { - for await (const line of lineReader) { + for await (const line of readBoundedLines(input, maxRecordLength)) { lineNumber += 1 const trimmedLine = line.trim() @@ -268,7 +324,6 @@ export class EventImportService { } } } finally { - lineReader.close() if (isDestroyableStream(input)) { input.destroy() } diff --git a/test/unit/services/event-import-service.spec.ts b/test/unit/services/event-import-service.spec.ts index d6386a437..e8b30f03f 100644 --- a/test/unit/services/event-import-service.spec.ts +++ b/test/unit/services/event-import-service.spec.ts @@ -1,9 +1,11 @@ -import { expect } from 'chai' +import chai, { expect } from 'chai' +import chaiAsPromised from 'chai-as-promised' import fs from 'fs' import os from 'os' import { join } from 'path' import { Readable } from 'stream' +import zlib from 'zlib' import { Tag } from '../../../src/@types/base' import { Event } from '../../../src/@types/event' import { EventDeduplicationMetadataKey, EventKinds, EventTags } from '../../../src/constants/base' @@ -13,10 +15,13 @@ import { EventImportService, EventImportStats, MAX_IMPORTED_DELETION_TARGETS, + MAX_IMPORTED_RECORD_LENGTH, } from '../../../src/services/event-import-service' import { getPublicKey, identifyEvent, signEvent } from '../../../src/utils/event' import { getEvents } from '../data/events' +chai.use(chaiAsPromised) + describe('EventImportService', () => { const tmpDirs: string[] = [] @@ -713,4 +718,97 @@ describe('EventImportService', () => { expect(inserted.map(({ id }) => id)).to.deep.equal([note.id]) }) }) + + describe('the lines of a JSONL input', () => { + const importLines = async (chunks: (string | Buffer)[], options = {}) => { + const lineErrors: EventImportLineError[] = [] + const importer = new EventImportService(async (events) => events.length) + const stats = await importer.importFromReadable(Readable.from(chunks), { + ...options, + onLineError: (lineError) => lineErrors.push(lineError), + }) + return { stats, lineNumbers: lineErrors.map(({ lineNumber }) => lineNumber) } + } + + it('numbers the lines as before, empty ones and any line break included', async () => { + const { lineNumbers } = await importLines(['a\n\nb\r\nc\rd\r\n\r\ne']) + + expect(lineNumbers).to.deep.equal([1, 3, 4, 5, 7]) + }) + + it('reads a line break split between two chunks as one', async () => { + const { lineNumbers } = await importLines(['a\r', '\nb\r', '\n', 'c']) + + expect(lineNumbers).to.deep.equal([1, 2, 3]) + }) + + it('reads a last line with no line break, and a trailing line break as no line', async () => { + expect((await importLines(['a\nb'])).lineNumbers).to.deep.equal([1, 2]) + expect((await importLines(['a\nb\n'])).lineNumbers).to.deep.equal([1, 2]) + }) + + it('reads a character split between two chunks', async () => { + const [event] = getEvents() + const line = Buffer.from(`${JSON.stringify({ ...event, content: 'héllo wörld ✓' })}\n`) + const cut = line.indexOf(0xc3) + 1 + + const { stats } = await importLines([line.subarray(0, cut), line.subarray(cut)]) + + expect(stats.processed).to.equal(1) + expect(stats.errors).to.equal(1) + }) + + it('stops the import at a line that is too long, and says which', async () => { + const [event] = getEvents() + const first = JSON.stringify(event) + const importer = new EventImportService(async (events) => events.length) + + await expect( + importer.importFromReadable(Readable.from([`${first}\n`, `${'x'.repeat(first.length + 1)}\n`]), { + maxRecordLength: first.length, + }), + ).to.be.rejectedWith(`invalid: line 2 is longer than ${first.length} characters`) + }) + + it('accepts a line of exactly the limit', async () => { + const { stats } = await importLines(['x'.repeat(100), '\n'], { maxRecordLength: 100 }) + + expect(stats.processed).to.equal(1) + }) + + it('stops reading a line that never ends once it is past the limit, and destroys the input', async () => { + let chunksRead = 0 + const input = Readable.from( + (async function* () { + // 1,000 chunks end the stream, so a reader with no limit finishes instead of running on. + while (chunksRead < 1000) { + chunksRead += 1 + yield 'x'.repeat(1000) + } + })(), + ) + + const importer = new EventImportService(async (events) => events.length) + await expect(importer.importFromReadable(input, { maxRecordLength: 10_000 })).to.be.rejectedWith( + 'longer than 10000 characters', + ) + + expect(chunksRead).to.be.lessThan(40) + expect(input.destroyed).to.equal(true) + }) + + it('refuses a small gzip file that decodes to one line of many megabytes', async () => { + const bomb = zlib.gzipSync(Buffer.alloc(64 * 1024 * 1024, 'x')) + expect(bomb.length).to.be.lessThan(256 * 1024) + const decompressor = zlib.createGunzip() + Readable.from([bomb]).pipe(decompressor) + const importer = new EventImportService(async (events) => events.length) + + await expect(importer.importFromReadable(decompressor)).to.be.rejectedWith( + `longer than ${MAX_IMPORTED_RECORD_LENGTH} characters`, + ) + + expect(decompressor.destroyed).to.equal(true) + }) + }) }) From 32951fa8126b4542943aa262421157defd9c24bd Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Sat, 5 Dec 2026 16:43:03 +0530 Subject: [PATCH 2/2] fix(import): read lines in one pass and count the limit without line breaks Signed-off-by: Priyanshubhartistm --- .changeset/import-bound-jsonl-record-size.md | 2 +- docs/OPERATIONS.md | 2 +- src/services/event-import-service.ts | 68 +++++++++++++------ .../services/event-import-service.spec.ts | 65 +++++++++++++++--- 4 files changed, 108 insertions(+), 29 deletions(-) diff --git a/.changeset/import-bound-jsonl-record-size.md b/.changeset/import-bound-jsonl-record-size.md index 0d89e066a..22ab01a98 100644 --- a/.changeset/import-bound-jsonl-record-size.md +++ b/.changeset/import-bound-jsonl-record-size.md @@ -2,4 +2,4 @@ "nostream": patch --- -`nostream import` no longer reads a JSONL line of any length. The importer held a whole line in memory before parsing it, so a small gzip or xz file that decodes to one newline-free line of gigabytes could exhaust its memory. A line longer than 8 MiB, about twice the largest deletion request the importer accepts, now stops the import with an error that names the line, and the input and its decompressor are closed. +`nostream import` no longer reads a JSONL line of any length. The importer held a whole line in memory before parsing it, so a small gzip or xz file that decodes to one newline-free line of gigabytes could exhaust its memory. A line longer than 8 MiB, counted before it is trimmed, now stops the import with an error that names the line, and the input and its decompressor are closed. Lines are also read in a single pass, so a very long line is read much faster. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index d2ea397eb..d902f2b41 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -87,7 +87,7 @@ The importer: - Processes the file line-by-line to keep memory usage bounded. - Streams JSON array items one by one to keep memory usage bounded. -- Stops the import with an error on a JSONL line longer than 8,388,608 characters (8 MiB), without reading the rest of it: a line is held whole before it is parsed, and a small compressed file can decode to a single line of any length. Lines before it are not affected, and the longest deletion request the importer accepts is about 4.8 million characters, so no valid input is refused. +- Stops the import with an error on a JSONL line longer than 8,388,608 characters (8 MiB), counted without its line break and before the line is trimmed, and does not read the rest of it: a line is held whole before it is parsed, and a small compressed file can decode to a single line of any length. The error names the line. Only the batches already flushed stay inserted, so the events of the batch being filled are not, and importing the file again skips the duplicates. A deletion request naming the most events the importer accepts is about 4.8 million characters, well below the limit. - Validates NIP-01 schema, event id hash, and Schnorr signature before insertion. - Refuses a deletion request (kind `5`) whose `e` tags name more than 65,533 distinct event ids: nothing it names is deleted, the request itself is not stored, and it counts under `Errors` with the reason `invalid: a deletion request may name at most 65533 events`. An id repeated in several `e` tags counts once, and `a` tags are not counted, as v3 does not act on them. The ids are deleted with one statement, and 65,533 is as many as PostgreSQL's 65,535 bind parameters leave room for, so this limit refuses no deletion request a v3 relay could have applied, live, from a peer or by an earlier import. - Writes each flush as two statements: one multi-row insert for regular events, then one upsert for replaceable ones. A kind `5` delete flushes first, so one batch can become several flushes. There is no transaction spanning them, and a statement that fails inserts nothing and counts its own events as skipped, which is why `Skipped` above can include events that were valid on their own. The insert runs first, so a failed upsert leaves that flush's regular events already written. diff --git a/src/services/event-import-service.ts b/src/services/event-import-service.ts index 2c8dc5fae..ea4d3a8f7 100644 --- a/src/services/event-import-service.ts +++ b/src/services/event-import-service.ts @@ -101,49 +101,79 @@ export interface EventImportLineError { */ export const MAX_IMPORTED_RECORD_LENGTH = 8_388_608 -const LINE_BREAK = /\r\n|\n|\r/ +const LINE_BREAK = /[\r\n]/g /** * Reads the lines of a stream the way `readline` does, a line break being `\n`, `\r\n` or `\r`, but refuses a line longer - * than `maxLength` before it grows any further: at most `maxLength` characters and one chunk are held at a time. + * than `maxLength` before it grows any further: at most `maxLength` characters and one chunk are held at a time. The + * limit counts the characters of a line without its line break, before the importer trims it. Each chunk is scanned + * once, however long the line it continues. */ async function* readBoundedLines(input: NodeJS.ReadableStream, maxLength: number): AsyncGenerator { const decoder = new StringDecoder('utf8') - let pending = '' + // The parts of the line still being read, and their length. + let parts: string[] = [] + let partsLength = 0 + // A \r ends a line at once, and a \n that follows it, even in the next chunk, belongs to the same line break. + let skipLineFeed = false let lineNumber = 0 const refuse = (): never => { throw new Error(`invalid: line ${lineNumber + 1} is longer than ${maxLength} characters`) } - for await (const chunk of input) { - pending += typeof chunk === 'string' ? chunk : decoder.write(chunk) + function* read(text: string): Generator { + if (text.length === 0) { + return + } - // A \r at the end may be the first half of a \r\n that the next chunk completes. - const held = pending.endsWith('\r') ? '\r' : '' - const lines = (held ? pending.slice(0, -1) : pending).split(LINE_BREAK) - pending = (lines.pop() as string) + held + let start = 0 + if (skipLineFeed && text[0] === '\n') { + start = 1 + } + skipLineFeed = false - for (const line of lines) { - if (line.length > maxLength) { + LINE_BREAK.lastIndex = start + for (let match = LINE_BREAK.exec(text); match; match = LINE_BREAK.exec(text)) { + if (partsLength + (match.index - start) > maxLength) { refuse() } + + const line = parts.length > 0 ? parts.join('') + text.slice(start, match.index) : text.slice(start, match.index) + parts = [] + partsLength = 0 lineNumber += 1 yield line + + start = match.index + 1 + if (text[match.index] === '\r') { + if (text[start] === '\n') { + start += 1 + } else if (start === text.length) { + skipLineFeed = true + } + } + LINE_BREAK.lastIndex = start } - if (pending.length > maxLength) { - refuse() + if (start < text.length) { + partsLength += text.length - start + if (partsLength > maxLength) { + refuse() + } + parts.push(text.slice(start)) } } - pending += decoder.end() - const last = pending.endsWith('\r') ? pending.slice(0, -1) : pending - if (last.length > maxLength) { - refuse() + for await (const chunk of input) { + yield* read(typeof chunk === 'string' ? chunk : decoder.write(chunk)) } - if (last.length > 0) { - yield last + + // A character cut off at the end of the input is read as the replacement character, as `readline` reads it. + yield* read(decoder.end()) + + if (partsLength > 0) { + yield parts.join('') } } diff --git a/test/unit/services/event-import-service.spec.ts b/test/unit/services/event-import-service.spec.ts index e8b30f03f..55fe87d1e 100644 --- a/test/unit/services/event-import-service.spec.ts +++ b/test/unit/services/event-import-service.spec.ts @@ -747,15 +747,42 @@ describe('EventImportService', () => { expect((await importLines(['a\nb\n'])).lineNumbers).to.deep.equal([1, 2]) }) - it('reads a character split between two chunks', async () => { + it('reads a character split between two chunks whole', async () => { + const privateKey = 'a'.repeat(64) + const event = await signEvent(privateKey)( + await identifyEvent({ + pubkey: getPublicKey(privateKey), + created_at: 1700000000, + kind: EventKinds.TEXT_NOTE, + tags: [], + content: 'héllo wörld ✓', + }), + ) + const line = Buffer.from(`${JSON.stringify(event)}\n`) + const persisted: Event[] = [] + const importer = new EventImportService(async (events) => { + persisted.push(...events) + return events.length + }) + + for (const byte of [0xc3, 0xe2]) { + const cut = line.indexOf(byte) + 1 + persisted.length = 0 + + const stats = await importer.importFromReadable(Readable.from([line.subarray(0, cut), line.subarray(cut)])) + + expect(stats).to.deep.equal({ errors: 0, inserted: 1, processed: 1, skipped: 0 }) + expect(persisted.map(({ content }) => content)).to.deep.equal(['héllo wörld ✓']) + } + }) + + it('reads the last line before a character cut off at the end of the input', async () => { const [event] = getEvents() - const line = Buffer.from(`${JSON.stringify({ ...event, content: 'héllo wörld ✓' })}\n`) - const cut = line.indexOf(0xc3) + 1 - const { stats } = await importLines([line.subarray(0, cut), line.subarray(cut)]) + const { stats, lineNumbers } = await importLines([Buffer.from(`${JSON.stringify(event)}\r`), Buffer.from([0xc3])]) - expect(stats.processed).to.equal(1) - expect(stats.errors).to.equal(1) + expect(stats.inserted).to.equal(1) + expect(lineNumbers).to.deep.equal([2]) }) it('stops the import at a line that is too long, and says which', async () => { @@ -770,8 +797,30 @@ describe('EventImportService', () => { ).to.be.rejectedWith(`invalid: line 2 is longer than ${first.length} characters`) }) - it('accepts a line of exactly the limit', async () => { - const { stats } = await importLines(['x'.repeat(100), '\n'], { maxRecordLength: 100 }) + it('accepts a line of exactly the limit, whatever ends it and wherever the chunks end', async () => { + const line = 'x'.repeat(100) + + for (const chunks of [[line, '\n'], [`${line}\r`, '\n'], [`${line}\r`], [`${line}\r\n`], [line], [`${line}\n`]]) { + const { stats } = await importLines(chunks, { maxRecordLength: 100 }) + + expect(stats.processed, JSON.stringify(chunks)).to.equal(1) + } + }) + + it('refuses a line one past the limit, whatever ends it', async () => { + const line = 'x'.repeat(101) + + for (const chunks of [[line, '\n'], [`${line}\r`, '\n'], [`${line}\r`], [line]]) { + await expect(importLines(chunks, { maxRecordLength: 100 }), JSON.stringify(chunks)).to.be.rejectedWith( + 'longer than 100 characters', + ) + } + }) + + it('reads a long line given in many small chunks as one line', async () => { + const chunks = Array.from({ length: 2000 }, () => 'x'.repeat(100)) + + const { stats } = await importLines([...chunks, '\n'], { maxRecordLength: 200_000 }) expect(stats.processed).to.equal(1) })