scoop:scoop.http.asyncio:0.1.0
src/http1_buffered_response.scoop
Selected production source · src/http1_buffered_response.scoop
1
package scoop.http.asyncio3
import scoop.asyncio.*4
import scoop.http.*5
import scoop.platform.io.WriteZeroException6
import scoop.platform.memory.NativeByteBorrow7
import scoop.platform.memory.NativeByteBuffer8
import scoop.time.Duration10
@GCLeaf11
@Extern(name = "scoop_platform_memory_move")12
private fun moveResponseBytes(destination: Ptr<Byte>, source: Ptr<Byte>, count: Long)14
/** Body progress for one completed or failed immutable-array response operation. */15
public class Http1ResponseProgress public constructor() {16
private var written: Long = 0L17
/** Actual accepted body bytes, readable after the associated send returns or throws. */18
public val writtenBytes: Long get() = written19
internal fun record(value: Long) {20
written = value21
}22
}24
private enum H1ResponseSource {25
Native(NativeByteBorrow)26
Bytes(Array<Byte>, Http1ResponseProgress?)27
}29
private class H1ResponseTransfer(val source: H1ResponseSource, val length: Long) {30
var headSize: Long = 0L31
var sent: Long = 0L33
fun bodyProgress(): Long =34
if (sent > headSize)35
sent - headSize36
else37
0L39
fun copyInto(buffer: NativeByteBuffer, offset: Long, count: Long) {40
when (source) {41
case Native(val borrow) -> @Unsafe42
{43
val pointer = borrow.pointer()!! + offset44
buffer.withWritableBytes {45
destination, _ ->46
@Unsafe47
{48
moveResponseBytes(destination!!, pointer, count)49
}50
count51
}52
}53
case Bytes(val bytes, _) -> buffer.writeBytes(bytes, offset, count)54
}55
}57
fun complete() {58
when (source) {59
case Native(val borrow) -> @Unsafe60
{61
borrow.complete(bodyProgress())62
}63
case Bytes(_, val progress) -> progress?.record(bodyProgress())64
}65
}66
}68
internal suspend fun sendH1BufferedResponse(69
state: H1State,70
head: HttpResponseHead,71
buffer: NativeByteBuffer,72
count: Long,73
writeIdle: Duration?74
) {75
httpJob(state.loop, true)76
httpIdleLimit(writeIdle)77
httpCount(count, buffer.readableBytes)78
@Unsafe79
{80
val transfer =81
H1ResponseTransfer(H1ResponseSource.Native(buffer.borrowReadable(count)), count)82
sendH1CompleteResponse(state, head, transfer, writeIdle)83
}84
}86
internal suspend fun sendH1ArrayResponse(87
state: H1State,88
head: HttpResponseHead,89
bytes: Array<Byte>,90
count: Long,91
writeIdle: Duration?,92
progress: Http1ResponseProgress?93
) {94
httpJob(state.loop, true)95
httpIdleLimit(writeIdle)96
httpCount(count, bytes.size)97
progress?.record(0L)98
val transfer = H1ResponseTransfer(H1ResponseSource.Bytes(bytes, progress), count)99
sendH1CompleteResponse(state, head, transfer, writeIdle)100
}102
private suspend fun sendH1CompleteResponse(103
state: H1State,104
head: HttpResponseHead,105
transfer: H1ResponseTransfer,106
writeIdle: Duration?107
) {108
try {109
val operation =110
beginH1Operation<(H1Output, Array<Byte>)>(111
state,112
false,113
{114
requireH1Output(state, HttpRole.Server)115
val request =116
state.requests.firstOrNone() ?:117
throw IllegalStateException(Some("no HTTP/1 request to answer"))118
val content = httpResponseAllowsContent(head, request.method)119
val count = transfer.length120
if (!content && count != 0L)121
throw IllegalArgumentException(122
Some("this HTTP response cannot carry a body")123
)124
val framing =125
if (content)126
Http1BodyFraming.Length(count)127
else128
Http1BodyFraming.Empty129
val bytes = state.encoder.beginResponse(head, request.method, framing)130
state.encoder.prepareBody(count)131
state.encoder.finish()132
val output =133
H1Output(134
head.status >= 200U || head.status == 101U,135
Some(request),136
writeIdle137
)138
state.outgoing = Some(output)139
(output, bytes)140
},141
writeIdle142
)143
val body =144
try {145
operation.job.ensureActive()146
val(output, bytes) = operation.prepared147
writeH1BufferedResponse(state, bytes, transfer)148
completeH1Output(state, output)149
output150
} catch (error: Throwable) {151
failH1Operation(operation, error)152
}153
endH1Operation(operation)154
closeAfterH1Output(state, body)155
} finally {156
transfer.complete()157
}158
}160
private suspend fun writeH1BufferedResponse(161
state: H1State,162
head: Array<Byte>,163
transfer: H1ResponseTransfer164
) {165
transfer.headSize = head.size166
if (head.size > Long.MAX_VALUE - transfer.length)167
throw ArithmeticException()168
val size = head.size + transfer.length169
val blockSize =170
if (size < 65536L)171
size172
else173
65536L174
state.output.clear()175
state.output.ensureWritable(blockSize)176
var position = 0L177
while (position < size) {178
if (position != 0L)179
state.output.clear()180
if (position < head.size) {181
val remaining = head.size - position182
val count =183
if (remaining < blockSize)184
remaining185
else186
blockSize187
state.output.writeBytes(head, position, count)188
position += count189
}190
val available = blockSize - state.output.readableBytes191
if (position >= head.size && position < size && available > 0L) {192
val offset = position - head.size193
val remaining = size - position194
val count =195
if (remaining < available)196
remaining197
else198
available199
transfer.copyInto(state.output, offset, count)200
position += count201
}202
var remaining = state.output.readableBytes203
while (remaining > 0L) {204
beginH1Io(state, false)205
val before = remaining206
val written =207
try {208
state.transport.writeFrom(state.output, before)209
}210
finally {211
remaining = state.output.readableBytes212
transfer.sent += before - remaining213
}214
httpProgress(written, before)215
if (before - remaining != written)216
throw IllegalStateException(217
Some("HTTP transport reported inconsistent write progress")218
)219
if (written == 0L)220
throw WriteZeroException()221
progressH1Io(state, false, true)222
}223
}224
flushH1Transport(state)225
}