scoop:scoop.http.asyncio:0.1.0
src/ndjson/source.scoop
Selected production source · src/ndjson/source.scoop
1
package scoop.http.asyncio3
import scoop.asyncio.*4
import scoop.http.NdjsonDecoder5
import scoop.platform.memory.NativeByteBuffer7
/** A demand-driven NDJSON record reader that borrows its input by default. */8
public class NdjsonSource private constructor(private val reader: NdjsonReader) : AsyncCloseable {9
public constructor(source: AsyncByteSource, maxRecordBytes: Long = 1048576L, bufferSize: Long = 8192L)10
: this(createNdjsonReader(source, None, maxRecordBytes, bufferSize)) {}12
public companion object {13
/** Transfers cleanup responsibility only after successful construction. */14
public fun <T> takeOwnership(source: T, maxRecordBytes: Long = 1048576L, bufferSize: Long = 8192L): NdjsonSource15
where T : AsyncByteSource, T : AsyncCloseable =16
NdjsonSource(createNdjsonReader(source, Some<AsyncCloseable>(source), maxRecordBytes, bufferSize))17
}19
public val isFinished: Boolean get() = reader.decoder.isFinished20
public val isClosed: Boolean get() = reader.io.isClosed21
public val failure: Throwable? get() = reader.io.failure23
/** Reads one record or clean EOF, without parsing JSON or discarding empty lines. */24
public suspend fun next(): String? = reader.next()26
public override suspend fun close() { reader.io.close() }27
}29
private fun createNdjsonReader(source: AsyncByteSource, owner: AsyncCloseable?, maximum: Long, bufferSize: Long): NdjsonReader {30
val loop = currentEventLoop()31
val job = httpJob(loop, true)32
if (bufferSize <= 0L) throw IllegalArgumentException(Some("NDJSON buffer size must be positive"))33
val decoder = NdjsonDecoder(maximum)34
val input = try { NativeByteBuffer.allocate(bufferSize) }35
catch (error: Throwable) {36
val failure = messageCleanup(Some(error)) { decoder.close() }37
throw failure!!38
}39
try {40
job.ensureActive()41
return NdjsonReader(source, owner, loop, decoder, input)42
} catch (error: Throwable) {43
var failure = messageCleanup(Some(error)) { input.close() }44
failure = messageCleanup(failure) { decoder.close() }45
throw failure!!46
}47
}