|
1 | 1 | package de.gesellix.docker.remote.api.core
|
2 | 2 |
|
3 | 3 | import de.gesellix.docker.response.Reader
|
| 4 | +import okio.Buffer |
4 | 5 | import okio.BufferedSource
|
5 | 6 | import okio.Source
|
6 | 7 | import okio.buffer
|
7 | 8 |
|
8 | 9 | class FrameReader(source: Source, private val expectMultiplexedResponse: Boolean = false) : Reader<Frame> {
|
9 | 10 |
|
10 |
| - private val buffer: BufferedSource = source.buffer() |
| 11 | + private val bufferedSource: BufferedSource = source.buffer() |
| 12 | + |
| 13 | + private val buffer = Buffer() |
11 | 14 |
|
12 | 15 | override fun readNext(type: Class<Frame>?): Frame {
|
13 | 16 | return if (expectMultiplexedResponse) {
|
14 | 17 | // See https://docs.docker.com/engine/api/v1.41/#operation/ContainerAttach for the stream format documentation.
|
15 | 18 | // header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
|
16 | 19 |
|
17 |
| - val streamType = Frame.StreamType.valueOf(buffer.readByte()) |
18 |
| - buffer.skip(3) |
19 |
| - val frameSize = buffer.readInt() |
| 20 | + val streamType = Frame.StreamType.valueOf(bufferedSource.readByte()) |
| 21 | + bufferedSource.skip(3) |
| 22 | + val frameSize = bufferedSource.readInt() |
20 | 23 |
|
21 |
| - Frame(streamType, buffer.readByteArray(frameSize.toLong())) |
| 24 | + Frame(streamType, bufferedSource.readByteArray(frameSize.toLong())) |
22 | 25 | } else {
|
23 |
| - // TODO consider reading plain bytes, not line separated |
24 |
| - Frame(Frame.StreamType.RAW, buffer.readUtf8Line()?.encodeToByteArray()) |
| 26 | + var byteCount: Long |
| 27 | + bufferedSource.read(buffer, 8192L).also { byteCount = it } |
| 28 | + if (byteCount < 0) { |
| 29 | + Frame(Frame.StreamType.RAW, null) |
| 30 | + } else { |
| 31 | + Frame(Frame.StreamType.RAW, buffer.readByteArray(byteCount)) |
| 32 | + } |
25 | 33 | }
|
26 | 34 | }
|
27 | 35 |
|
28 | 36 | override fun hasNext(): Boolean {
|
29 |
| - return !Thread.currentThread().isInterrupted && !buffer.exhausted() |
| 37 | + return try { |
| 38 | + !Thread.currentThread().isInterrupted |
| 39 | +// && bufferedSource.isOpen |
| 40 | + && !bufferedSource.peek().exhausted() |
| 41 | + } catch (e: Exception) { |
| 42 | + return false |
| 43 | + } |
30 | 44 | }
|
31 | 45 | }
|
0 commit comments