Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up on exception while chunking XContent #92024

Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/changelog/92024.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pr: 92024
summary: Clean up on exception while chunking XContent
area: Network
type: bug
issues: []
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import org.elasticsearch.common.recycler.Recycler;
import org.elasticsearch.common.xcontent.ChunkedToXContent;
import org.elasticsearch.core.IOUtils;
import org.elasticsearch.core.Releasables;
import org.elasticsearch.core.Streams;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
Expand Down Expand Up @@ -92,20 +93,32 @@ public boolean isDone() {

@Override
public ReleasableBytesReference encodeChunk(int sizeHint, Recycler<BytesRef> recycler) throws IOException {
final RecyclerBytesStreamOutput chunkStream = new RecyclerBytesStreamOutput(recycler);
assert this.target == null;
this.target = chunkStream;
while (serialization.hasNext()) {
serialization.next().toXContent(builder, params);
if (chunkStream.size() >= sizeHint) {
break;
try {
final RecyclerBytesStreamOutput chunkStream = new RecyclerBytesStreamOutput(recycler);
assert target == null;
target = chunkStream;
while (serialization.hasNext()) {
serialization.next().toXContent(builder, params);
if (chunkStream.size() >= sizeHint) {
break;
}
}
if (serialization.hasNext() == false) {
builder.close();
}
final var result = new ReleasableBytesReference(
chunkStream.bytes(),
() -> Releasables.closeExpectNoException(chunkStream)
);
target = null;
return result;
} finally {
if (target != null) {
assert false : "failure encoding chunk";
IOUtils.closeWhileHandlingException(target);
target = null;
}
}
if (serialization.hasNext() == false) {
builder.close();
}
this.target = null;
return new ReleasableBytesReference(chunkStream.bytes(), () -> IOUtils.closeWhileHandlingException(chunkStream));
}

@Override
Expand Down