Scoop API

scoop:scoop.http.asyncio:0.1.0

src/http1_buffered_response.scoop

Selected production source · src/http1_buffered_response.scoop

1package scoop.http.asyncio
3import scoop.asyncio.*
4import scoop.http.*
5import scoop.platform.io.WriteZeroException
6import scoop.platform.memory.NativeByteBorrow
7import scoop.platform.memory.NativeByteBuffer
8import scoop.time.Duration
10@GCLeaf
11@Extern(name = "scoop_platform_memory_move")
12private fun moveResponseBytes(destination: Ptr<Byte>, source: Ptr<Byte>, count: Long)
14/** Body progress for one completed or failed immutable-array response operation. */
15public class Http1ResponseProgress public constructor() {
16 private var written: Long = 0L
17 /** Actual accepted body bytes, readable after the associated send returns or throws. */
18 public val writtenBytes: Long get() = written
19 internal fun record(value: Long) {
20 written = value
21 }
24private enum H1ResponseSource {
25 Native(NativeByteBorrow)
26 Bytes(Array<Byte>, Http1ResponseProgress?)
29private class H1ResponseTransfer(val source: H1ResponseSource, val length: Long) {
30 var headSize: Long = 0L
31 var sent: Long = 0L
33 fun bodyProgress(): Long =
34 if (sent > headSize)
35 sent - headSize
36 else
37 0L
39 fun copyInto(buffer: NativeByteBuffer, offset: Long, count: Long) {
40 when (source) {
41 case Native(val borrow) -> @Unsafe
42 {
43 val pointer = borrow.pointer()!! + offset
44 buffer.withWritableBytes {
45 destination, _ ->
46 @Unsafe
47 {
48 moveResponseBytes(destination!!, pointer, count)
49 }
50 count
51 }
52 }
53 case Bytes(val bytes, _) -> buffer.writeBytes(bytes, offset, count)
54 }
55 }
57 fun complete() {
58 when (source) {
59 case Native(val borrow) -> @Unsafe
60 {
61 borrow.complete(bodyProgress())
62 }
63 case Bytes(_, val progress) -> progress?.record(bodyProgress())
64 }
65 }
68internal 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 @Unsafe
79 {
80 val transfer =
81 H1ResponseTransfer(H1ResponseSource.Native(buffer.borrowReadable(count)), count)
82 sendH1CompleteResponse(state, head, transfer, writeIdle)
83 }
86internal 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)
102private 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.length
120 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 else
128 Http1BodyFraming.Empty
129 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 writeIdle
137 )
138 state.outgoing = Some(output)
139 (output, bytes)
140 },
141 writeIdle
142 )
143 val body =
144 try {
145 operation.job.ensureActive()
146 val(output, bytes) = operation.prepared
147 writeH1BufferedResponse(state, bytes, transfer)
148 completeH1Output(state, output)
149 output
150 } catch (error: Throwable) {
151 failH1Operation(operation, error)
152 }
153 endH1Operation(operation)
154 closeAfterH1Output(state, body)
155 } finally {
156 transfer.complete()
157 }
160private suspend fun writeH1BufferedResponse(
161 state: H1State,
162 head: Array<Byte>,
163 transfer: H1ResponseTransfer
164) {
165 transfer.headSize = head.size
166 if (head.size > Long.MAX_VALUE - transfer.length)
167 throw ArithmeticException()
168 val size = head.size + transfer.length
169 val blockSize =
170 if (size < 65536L)
171 size
172 else
173 65536L
174 state.output.clear()
175 state.output.ensureWritable(blockSize)
176 var position = 0L
177 while (position < size) {
178 if (position != 0L)
179 state.output.clear()
180 if (position < head.size) {
181 val remaining = head.size - position
182 val count =
183 if (remaining < blockSize)
184 remaining
185 else
186 blockSize
187 state.output.writeBytes(head, position, count)
188 position += count
189 }
190 val available = blockSize - state.output.readableBytes
191 if (position >= head.size && position < size && available > 0L) {
192 val offset = position - head.size
193 val remaining = size - position
194 val count =
195 if (remaining < available)
196 remaining
197 else
198 available
199 transfer.copyInto(state.output, offset, count)
200 position += count
201 }
202 var remaining = state.output.readableBytes
203 while (remaining > 0L) {
204 beginH1Io(state, false)
205 val before = remaining
206 val written =
207 try {
208 state.transport.writeFrom(state.output, before)
209 }
210 finally {
211 remaining = state.output.readableBytes
212 transfer.sent += before - remaining
213 }
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)