|
14 | 14 | import org.elasticsearch.common.recycler.Recycler; |
15 | 15 | import org.elasticsearch.common.xcontent.ChunkedToXContent; |
16 | 16 | import org.elasticsearch.core.IOUtils; |
| 17 | +import org.elasticsearch.core.Releasables; |
17 | 18 | import org.elasticsearch.core.Streams; |
18 | 19 | import org.elasticsearch.xcontent.ToXContent; |
19 | 20 | import org.elasticsearch.xcontent.XContentBuilder; |
@@ -92,20 +93,32 @@ public boolean isDone() { |
92 | 93 |
|
93 | 94 | @Override |
94 | 95 | public ReleasableBytesReference encodeChunk(int sizeHint, Recycler<BytesRef> recycler) throws IOException { |
95 | | - final RecyclerBytesStreamOutput chunkStream = new RecyclerBytesStreamOutput(recycler); |
96 | | - assert this.target == null; |
97 | | - this.target = chunkStream; |
98 | | - while (serialization.hasNext()) { |
99 | | - serialization.next().toXContent(builder, params); |
100 | | - if (chunkStream.size() >= sizeHint) { |
101 | | - break; |
| 96 | + try { |
| 97 | + final RecyclerBytesStreamOutput chunkStream = new RecyclerBytesStreamOutput(recycler); |
| 98 | + assert target == null; |
| 99 | + target = chunkStream; |
| 100 | + while (serialization.hasNext()) { |
| 101 | + serialization.next().toXContent(builder, params); |
| 102 | + if (chunkStream.size() >= sizeHint) { |
| 103 | + break; |
| 104 | + } |
| 105 | + } |
| 106 | + if (serialization.hasNext() == false) { |
| 107 | + builder.close(); |
| 108 | + } |
| 109 | + final var result = new ReleasableBytesReference( |
| 110 | + chunkStream.bytes(), |
| 111 | + () -> Releasables.closeExpectNoException(chunkStream) |
| 112 | + ); |
| 113 | + target = null; |
| 114 | + return result; |
| 115 | + } finally { |
| 116 | + if (target != null) { |
| 117 | + assert false : "failure encoding chunk"; |
| 118 | + IOUtils.closeWhileHandlingException(target); |
| 119 | + target = null; |
102 | 120 | } |
103 | 121 | } |
104 | | - if (serialization.hasNext() == false) { |
105 | | - builder.close(); |
106 | | - } |
107 | | - this.target = null; |
108 | | - return new ReleasableBytesReference(chunkStream.bytes(), () -> IOUtils.closeWhileHandlingException(chunkStream)); |
109 | 122 | } |
110 | 123 |
|
111 | 124 | @Override |
|
0 commit comments