Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/import-bound-jsonl-record-size.md
Original file line number Diff line number Diff line change
@@ -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, 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.
1 change: 1 addition & 0 deletions docs/OPERATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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), 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.
Expand Down
105 changes: 95 additions & 10 deletions src/services/event-import-service.ts
Original file line number Diff line number Diff line change
@@ -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 }
Expand Down Expand Up @@ -94,8 +94,93 @@ 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]/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. 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<string> {
const decoder = new StringDecoder('utf8')
// 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`)
}

function* read(text: string): Generator<string> {
if (text.length === 0) {
return
}

let start = 0
if (skipLineFeed && text[0] === '\n') {
start = 1
}
skipLineFeed = false

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 (start < text.length) {
partsLength += text.length - start
if (partsLength > maxLength) {
refuse()
}
parts.push(text.slice(start))
}
}

for await (const chunk of input) {
yield* read(typeof chunk === 'string' ? chunk : decoder.write(chunk))
}

// 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('')
}
}

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
}
Expand Down Expand Up @@ -223,7 +308,10 @@ export class EventImportService {
input: NodeJS.ReadableStream,
options: EventImportOptions = {},
): Promise<EventImportStats> {
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<EventImportStats> {
Expand All @@ -238,16 +326,14 @@ export class EventImportService {
return this.importFromCandidates(this.readJsonArrayCandidates(filePath), options)
}

private async *readJsonlCandidatesFromStream(input: NodeJS.ReadableStream): AsyncGenerator<EventImportCandidate> {
const lineReader = readline.createInterface({
crlfDelay: Infinity,
input,
})

private async *readJsonlCandidatesFromStream(
input: NodeJS.ReadableStream,
maxRecordLength: number,
): AsyncGenerator<EventImportCandidate> {
let lineNumber = 0

try {
for await (const line of lineReader) {
for await (const line of readBoundedLines(input, maxRecordLength)) {
lineNumber += 1

const trimmedLine = line.trim()
Expand All @@ -268,7 +354,6 @@ export class EventImportService {
}
}
} finally {
lineReader.close()
if (isDestroyableStream(input)) {
input.destroy()
}
Expand Down
149 changes: 148 additions & 1 deletion test/unit/services/event-import-service.spec.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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[] = []

Expand Down Expand Up @@ -713,4 +718,146 @@ 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 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 { stats, lineNumbers } = await importLines([Buffer.from(`${JSON.stringify(event)}\r`), Buffer.from([0xc3])])

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 () => {
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, 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)
})

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)
})
})
})
Loading