ok2c commented on code in PR #703: URL: https://github.com/apache/httpcomponents-client/pull/703#discussion_r2278903822
########## httpclient5/src/main/java/org/apache/hc/client5/http/async/methods/DeflatingZstdEntityProducer.java: ########## @@ -0,0 +1,345 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * <http://www.apache.org/>. + * + */ + +package org.apache.hc.client5.http.async.methods; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.Collections; +import java.util.Deque; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import com.github.luben.zstd.ZstdDirectBufferCompressingStream; + +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.nio.AsyncEntityProducer; +import org.apache.hc.core5.http.nio.DataStreamChannel; +import org.apache.hc.core5.util.Args; + +/** + * {@code AsyncEntityProducer} that compresses the bytes produced by a delegate entity + * into a single <a href="https://www.rfc-editor.org/rfc/rfc8878">Zstandard</a> (zstd) frame + * on the fly. + * + * <p>This producer wraps a {@link org.apache.hc.core5.http.nio.AsyncEntityProducer} and + * performs streaming, ByteBuffer-to-ByteBuffer compression as the delegate writes to the + * provided {@link org.apache.hc.core5.http.nio.DataStreamChannel}. No {@code InputStream} + * is used in the client pipeline.</p> + * + * <p>Metadata reported by this producer:</p> + * <ul> + * <li>{@link #getContentEncoding()} returns {@code "zstd"}.</li> + * <li>{@link #getContentLength()} returns {@code -1} (unknown after compression).</li> + * <li>{@link #isChunked()} returns {@code true} (requests are typically sent chunked).</li> + * </ul> + * + * <h3>Usage</h3> + * <pre>{@code + * AsyncEntityProducer plain = new StringAsyncEntityProducer("payload", ContentType.TEXT_PLAIN); + * AsyncEntityProducer zstd = new DeflatingZstdEntityProducer(plain); + * + * SimpleHttpRequest req = SimpleRequestBuilder.post("http://localhost/echo") + * .setHeader(HttpHeaders.CONTENT_ENCODING, "zstd") // inform the server + * .build(); + * + * client.execute( + * new BasicRequestProducer(req, zstd), + * new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), + * null); + * }</pre> + * + * <h3>Behavior</h3> + * <ul> + * <li><b>Streaming & back-pressure:</b> compressed output is staged in direct + * {@link java.nio.ByteBuffer}s and written only when the channel accepts bytes. + * When {@code DataStreamChannel.write(...)} returns {@code 0}, the producer pauses and + * requests another output turn.</li> + * <li><b>Finalization:</b> after the delegate signals {@code endStream()}, this producer emits + * the zstd frame epilogue and then calls {@code DataStreamChannel.endStream()}.</li> + * <li><b>Repeatability:</b> repeatable only if the delegate is repeatable.</li> + * <li><b>Headers:</b> callers are responsible for sending {@code Content-Encoding: zstd} on + * the request if required by the server. Content length is not known in advance.</li> + * <li><b>Resources:</b> invoke {@link #releaseResources()} to free native compressor resources.</li> + * </ul> + * + * <h3>Constructors</h3> + * <ul> + * <li>{@code DeflatingZstdEntityProducer(delegate)} – uses a default compression level.</li> + * <li>{@code DeflatingZstdEntityProducer(delegate, level)} – explicitly sets the zstd level.</li> + * </ul> + * + * <h3>Thread-safety</h3> + * <p>Not thread-safe; one instance per message exchange.</p> + * + * <h3>Runtime dependency</h3> + * <p>Requires {@code com.github.luben:zstd-jni} on the classpath.</p> + * + * @see org.apache.hc.client5.http.async.methods.InflatingZstdDataConsumer + * @see org.apache.hc.core5.http.nio.support.BasicRequestProducer + * @see org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer + * @see org.apache.hc.client5.http.impl.async.ContentCompressionAsyncExec + * @since 5.6 + */ +public final class DeflatingZstdEntityProducer implements AsyncEntityProducer { + + private static final int IN_BUF = 64 * 1024; + private static final int OUT_BUF_DEFAULT = 128 * 1024; + + private final AsyncEntityProducer delegate; + + /** + * Direct staging for heap inputs. + */ + private final ByteBuffer inDirect = ByteBuffer.allocateDirect(IN_BUF); + + /** + * Pending compressed output buffers, ready to write (pos=0..limit). + */ + private final Deque<ByteBuffer> pending = new ArrayDeque<>(); + + /** + * Current output buffer owned by zstd; replaced when it overflows or flushes. + */ + private ByteBuffer outBuf; + + /** + * Zstd compressor stream. + */ + private final ZstdDirectBufferCompressingStream zstream; + + private volatile boolean upstreamEnded = false; + private volatile boolean finished = false; + private final AtomicBoolean released = new AtomicBoolean(false); + + public DeflatingZstdEntityProducer(final AsyncEntityProducer delegate) { + this(delegate, 3); // default compression level + } + + public DeflatingZstdEntityProducer(final AsyncEntityProducer delegate, final int level) { + this.delegate = Args.notNull(delegate, "delegate"); + inDirect.limit(0); + + // Pick a sensible out buffer size (at least the recommended size). + final int rec = ZstdDirectBufferCompressingStream.recommendedOutputBufferSize(); + final int outCap = Math.max(OUT_BUF_DEFAULT, rec); + outBuf = ByteBuffer.allocateDirect(outCap); + + // Create the compressor; override flushBuffer to queue full buffers. + try { + this.zstream = new ZstdDirectBufferCompressingStream(outBuf, level) { Review Comment: @arturobernalg Could this bit be moved to `#produce` to avoid the ugliness with the exception handling? ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/ContentCompressionAsyncExec.java: ########## @@ -102,8 +121,11 @@ public void execute( final boolean enabled = ctx.getRequestConfigOrDefault().isContentCompressionEnabled(); if (enabled && !request.containsHeader(HttpHeaders.ACCEPT_ENCODING)) { - request.addHeader(MessageSupport.headerOfTokens( - HttpHeaders.ACCEPT_ENCODING, Arrays.asList("gzip", "x-gzip", "deflate"))); + final List<String> tokens = new ArrayList<>(Arrays.asList("gzip", "x-gzip", "deflate")); Review Comment: @arturobernalg Could not this list be built at the same time with `decoders `? ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/ContentCompressionAsyncExec.java: ########## @@ -78,15 +80,32 @@ public ContentCompressionAsyncExec( */ public ContentCompressionAsyncExec() { final LinkedHashMap<String, UnaryOperator<AsyncDataConsumer>> map = new LinkedHashMap<>(); - map.put(ContentCoding.DEFLATE.token(), - d -> new InflatingAsyncDataConsumer(d, null)); + map.put(ContentCoding.DEFLATE.token(), d -> new InflatingAsyncDataConsumer(d, null)); map.put(ContentCoding.GZIP.token(), InflatingGzipDataConsumer::new); map.put(ContentCoding.X_GZIP.token(), InflatingGzipDataConsumer::new); - this.decoders = RegistryBuilder.<UnaryOperator<AsyncDataConsumer>>create() - .register(ContentCoding.GZIP.token(), map.get(ContentCoding.GZIP.token())) - .register(ContentCoding.X_GZIP.token(), map.get(ContentCoding.X_GZIP.token())) - .register(ContentCoding.DEFLATE.token(), map.get(ContentCoding.DEFLATE.token())) - .build(); + + final RegistryBuilder<UnaryOperator<AsyncDataConsumer>> rb = + RegistryBuilder.<UnaryOperator<AsyncDataConsumer>>create() + .register(ContentCoding.GZIP.token(), InflatingGzipDataConsumer::new) + .register(ContentCoding.X_GZIP.token(), InflatingGzipDataConsumer::new) + .register(ContentCoding.DEFLATE.token(), d -> new InflatingAsyncDataConsumer(d, null)); + + // Add zstd only when zstd-jni is present + if (ZstdRuntime.available()) { + // Use reflection to avoid hard-linking InflatingZstdDataConsumer when absent + rb.register(ContentCoding.ZSTD.token(), downstream -> { + try { + final Class<?> c = Class.forName( Review Comment: The use of reflection is not necessary. This code should never execute if `ZstdRuntime#available` returns `falser` and compile time dependency on ZSTD is fine. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
