You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@solr.apache.org by "jdyer1 (via GitHub)" <gi...@apache.org> on 2024/02/13 20:16:52 UTC
[PR] New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
jdyer1 opened a new pull request, #2259:
URL: https://github.com/apache/solr/pull/2259
https://issues.apache.org/jira/browse/SOLR-599
This PR adds `HttpSolrClientJdkImpl`, a Solr client using the built-in Java 11+ Http Client rather than an external dependency. This is intended to be a drop-in replacement for `Http2SolrClient` and/or `HttpSolrClient` for client applications running either Http/1.1 or Http/2. This is not intended for Solr's server-side inter-node requests. This new client is aimed at those users wishing to reduce transitive dependencies in their applications.
This PR factors out a new abstract superclass, `Http2SolrClientBase`, from which both `Http2SolrClient` and `HttpSolrClientJdkImpl` extend. A similar refactoring is made to the corresponding unit tests.
Should it be desirable to include this new client in a future SolrJ release, a possible follow-up would be to split the SolrJ artifact. A "core" artifact could be published having fewer transitive dependencies with additional artifacts per client library dependency. This would allow downstream applications to include only those transitive dependencies they need, without resorting to build tool exclusion mechanisms.
Although I am including this as a potential solution for [SOLR-599](https://issues.apache.org/jira/browse/SOLR-599), this client is only "lightweight" in the sense it does not require additional client dependencies. This client is intended to support most features included with the existing clients.
There is one TODO in the `HttpSolrClientJdkImpl` to possibly find a more memory-efficient way to handle POST requests. There is a NOCOMMIT in `solr-tests.policy`. I could not figure out how to properly set the permissions for `java.net.URLPermission`, resorting to `AllPermission` for the time being.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by David Smiley <ds...@apache.org>.
Alright; thanks for your thorough response. If you/someone notices a
failure and we need to touch this again, let's follow up with a PR.
And I suspect we'll want to factor out the cleanup so more tests might
use this without the copy-pasted hack. Perhaps HttpJdkSolrClient
could do this cleanup in its close instead of the test? Also I
thought I suggested before checking if httpClient implements
AutoCloseable in HttpJdkSolrClient.close() so you can call it. This
would work nicely when the user chooses to run in JDK 21.
On Fri, Mar 15, 2024 at 9:59 AM James Dyer <jd...@gmail.com> wrote:
>
> David, let me try and address your concerns with the approach. I am
> open to other approaches, however, we need something that will work
> consistently. I would like for what I have now to run in our CI for
> at least a week to see if we get more failures or not, before changing
> it further. I do not want to contribute to this project's flakey test
> problem.
>
> As the wisdom of the JDK designers had it, java.net.http.HttpClient
> did not originally implement Closable or Autoclosable. There was no
> way for a user of the library to release resources, particularly
> threads. You can pass your own Executor in the Builder, keep a
> reference to it and ensure you close it yourself. But this is not
> enough. The implementation appears to keep additional ("selector")
> threads not managed by that executor.
>
> See the description of [1] and the last paragraph of [2], where it is
> noted that prior to Java 21 (which adds close() methods) we must wait
> for a garbage collection. While developing this feature, I found that
> running a full gc in the "after" method of each test was enough to
> make the test framework happy. However, within a day of this being in
> our CI, we were getting failures from these "selector" threads still
> being active. As I said, I do not want to contribute further to our
> flakey test problem.
>
> Others suggest similar solutions in [3], although the reflection-based
> solutions are less-viable because they I believe require "--add-opens"
> to be added for the module, which I think we should avoid. I agree
> the current solution of interrupting all the "HttpClient" threads in
> the "after" method is an extraordinary step to take! It probably
> would be adequate to do it in "afterClass" but then again, it might be
> best if each test started with a clean slate. If we join the threads
> first, the test might block waiting. I am pretty sure the "system.gc"
> is no longer necessary after interrupting the threads, but in a unit
> test "after" method, what is the harm?
>
> I agree I should have used "forEach". I noticed this myself after
> pushing these changes. But this is the most minor of concerns.
> -----
> [1] https://bugs.openjdk.org/browse/JDK-8304165
> [2] https://inside.java/2023/12/10/sip092/
> [3] https://stackoverflow.com/questions/53919721/close-java-http-client
>
> On Thu, Mar 14, 2024 at 8:35 PM dsmiley (via GitHub) <gi...@apache.org> wrote:
> >
> >
> > dsmiley commented on PR #2259:
> > URL: https://github.com/apache/solr/pull/2259#issuecomment-1998742427
> >
> > Instead of simply interrupting the threads, shouldn't we also join on them?
> > Should that be in an AfterClass -- is it a problem between each test?
> > note: you don't need to gather a Set to then iterate; you can call `forEach` on the stream to do whatever you want to do. I don't think using a Set (for uniqueness) is necessary here either.
> > What is the GC accomplishing?
> >
> > I was looking again at all those test overrides that call super. I removed them locally and I was able to run at the CLI and IntelliJ and it ran all the intherited tests. This pattern is done elsewhere like SolrExampleTests
> >
> >
> > --
> > 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: issues-unsubscribe@solr.apache.org
> >
> > For queries about this service, please contact Infrastructure at:
> > users@infra.apache.org
> >
> >
> > ---------------------------------------------------------------------
> > To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
> > For additional commands, e-mail: issues-help@solr.apache.org
> >
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: dev-unsubscribe@solr.apache.org
> For additional commands, e-mail: dev-help@solr.apache.org
>
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@solr.apache.org
For additional commands, e-mail: dev-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by James Dyer <jd...@gmail.com>.
David, let me try and address your concerns with the approach. I am
open to other approaches, however, we need something that will work
consistently. I would like for what I have now to run in our CI for
at least a week to see if we get more failures or not, before changing
it further. I do not want to contribute to this project's flakey test
problem.
As the wisdom of the JDK designers had it, java.net.http.HttpClient
did not originally implement Closable or Autoclosable. There was no
way for a user of the library to release resources, particularly
threads. You can pass your own Executor in the Builder, keep a
reference to it and ensure you close it yourself. But this is not
enough. The implementation appears to keep additional ("selector")
threads not managed by that executor.
See the description of [1] and the last paragraph of [2], where it is
noted that prior to Java 21 (which adds close() methods) we must wait
for a garbage collection. While developing this feature, I found that
running a full gc in the "after" method of each test was enough to
make the test framework happy. However, within a day of this being in
our CI, we were getting failures from these "selector" threads still
being active. As I said, I do not want to contribute further to our
flakey test problem.
Others suggest similar solutions in [3], although the reflection-based
solutions are less-viable because they I believe require "--add-opens"
to be added for the module, which I think we should avoid. I agree
the current solution of interrupting all the "HttpClient" threads in
the "after" method is an extraordinary step to take! It probably
would be adequate to do it in "afterClass" but then again, it might be
best if each test started with a clean slate. If we join the threads
first, the test might block waiting. I am pretty sure the "system.gc"
is no longer necessary after interrupting the threads, but in a unit
test "after" method, what is the harm?
I agree I should have used "forEach". I noticed this myself after
pushing these changes. But this is the most minor of concerns.
-----
[1] https://bugs.openjdk.org/browse/JDK-8304165
[2] https://inside.java/2023/12/10/sip092/
[3] https://stackoverflow.com/questions/53919721/close-java-http-client
On Thu, Mar 14, 2024 at 8:35 PM dsmiley (via GitHub) <gi...@apache.org> wrote:
>
>
> dsmiley commented on PR #2259:
> URL: https://github.com/apache/solr/pull/2259#issuecomment-1998742427
>
> Instead of simply interrupting the threads, shouldn't we also join on them?
> Should that be in an AfterClass -- is it a problem between each test?
> note: you don't need to gather a Set to then iterate; you can call `forEach` on the stream to do whatever you want to do. I don't think using a Set (for uniqueness) is necessary here either.
> What is the GC accomplishing?
>
> I was looking again at all those test overrides that call super. I removed them locally and I was able to run at the CLI and IntelliJ and it ran all the intherited tests. This pattern is done elsewhere like SolrExampleTests
>
>
> --
> 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: issues-unsubscribe@solr.apache.org
>
> For queries about this service, please contact Infrastructure at:
> users@infra.apache.org
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
> For additional commands, e-mail: issues-help@solr.apache.org
>
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@solr.apache.org
For additional commands, e-mail: dev-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506446418
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -188,33 +210,52 @@ private HttpResponse<InputStream> doPutOrPost(
}
HttpRequest.BodyPublisher bodyPublisher;
-
+ final PipedOutputStream source;
if (contentWriter != null) {
- // TODO: There is likely a more memory-efficient way to do this!
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- contentWriter.write(baos);
- byte[] bytes = baos.toByteArray();
- bodyPublisher = HttpRequest.BodyPublishers.ofByteArray(bytes);
+ source = new PipedOutputStream();
+ PipedInputStream sink = new PipedInputStream(source);
+ bodyPublisher = HttpRequest.BodyPublishers.ofInputStream(() -> sink);
+ // NOCOMMIT - this does not work. The call to "client.send" sometimes will throw an
+ // IOException
+ // because our thread closes the outputstream too early. But if we wait to close it until
Review Comment:
I removed this NOCOMMIT and removed the unnecessary second close on the OutputStream. I also changed it to hold onto the Future so as to cancel on exception. I also made various other improvements.
The OutputStream was being closed early, but only on non-secure http2 requests. If using TLS or forcing Http1.1, it always worked. The problem was that with the first request, the JDK Http Client sends it as Http1.1 and requests an upgrade. When that first request happens to be a POST with a chunked body, it evidently sends the body with the upgrade request. Our Jetty server, however, does not allow a body with an upgrade request, so it replies with a GOAWAY frame. The workaround I found is to issue a "ping" request prior to the first real one. This lets the JDK Client know if our server supports Http2 in advance and upgrade requests are avoided after that.
I have two regrets with this round of changes: first, I cannot figure out a reliable way to write a unit test for the error handling when it calls "cancel" on the Future. Second, I am calling "ping" in the constructor, which I felt was a lesser evil than having to check a volatile boolean with each request to see if "ping" was called yet.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506438004
##########
solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrJdkClientTest.java:
##########
@@ -278,6 +281,15 @@ public void testUpdateDefault() throws Exception {
@Test
public void testUpdateXml() throws Exception {
+ testUpdateXml(false);
+ }
+
+ @Test
+ public void testUpdateXmlWithHttp11() throws Exception {
+ testUpdateXml(true);
+ }
Review Comment:
Or just use randomization -- easy and adequate even if a bit annoying to debug a failure.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1509376127
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieHandler;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.apache.solr.common.util.SolrNamedThreadFactory;
+import org.eclipse.jetty.util.BlockingArrayQueue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrJdkClient extends HttpSolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ protected HttpClient client;
+
+ protected ExecutorService executor;
+
+ private boolean shutdownExecutor;
+
+ protected HttpSolrJdkClient(String serverBaseUrl, HttpSolrJdkClient.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+
+ if (builder.executor != null) {
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ BlockingArrayQueue<Runnable> queue = new BlockingArrayQueue<>(32, 32);
+ this.executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 4,
+ 256,
+ 60,
+ TimeUnit.SECONDS,
+ queue,
+ new SolrNamedThreadFactory(this.getClass().getSimpleName()));
+ this.shutdownExecutor = true;
+ }
+ b.executor(this.executor);
+
+ if (builder.useHttp1_1) {
+ b.version(HttpClient.Version.HTTP_1_1);
Review Comment:
I would rather we avoid the ping at the expense of the possibility that a minority of users would be required to configure HTTP 1.1 explicitly on their client. After all, we know Solr supports Http/2 and it's been out there for quite some time. I can understand why the JDK's HttpClient defaults the way it does (kind of in the middle) but we know how we deploy Solr for the majority of users.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on PR #2259:
URL: https://github.com/apache/solr/pull/2259#issuecomment-1998742427
Instead of simply interrupting the threads, shouldn't we also join on them?
Should that be in an AfterClass -- is it a problem between each test?
note: you don't need to gather a Set to then iterate; you can call `forEach` on the stream to do whatever you want to do. I don't think using a Set (for uniqueness) is necessary here either.
What is the GC accomplishing?
I was looking again at all those test overrides that call super. I removed them locally and I was able to run at the CLI and IntelliJ and it ran all the intherited tests. This pattern is done elsewhere like SolrExampleTests
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506571244
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieHandler;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.apache.solr.common.util.SolrNamedThreadFactory;
+import org.eclipse.jetty.util.BlockingArrayQueue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrJdkClient extends HttpSolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ protected HttpClient client;
+
+ protected ExecutorService executor;
+
+ private boolean shutdownExecutor;
+
+ protected HttpSolrJdkClient(String serverBaseUrl, HttpSolrJdkClient.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+
+ if (builder.executor != null) {
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ BlockingArrayQueue<Runnable> queue = new BlockingArrayQueue<>(32, 32);
+ this.executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 4,
+ 256,
+ 60,
+ TimeUnit.SECONDS,
+ queue,
+ new SolrNamedThreadFactory(this.getClass().getSimpleName()));
+ this.shutdownExecutor = true;
+ }
+ b.executor(this.executor);
+
+ if (builder.useHttp1_1) {
+ b.version(HttpClient.Version.HTTP_1_1);
Review Comment:
Well, maybe. The ping is not needed if the user says they prefer http/1.. Then again the JDK client perhaps might still use Http/2 if the server doesn't support http/1.1. In any case it also is unnecessary if the connection is over TLS/SSL. All of started to seem complicated to me so I just had it try a ping every time.
My real worry about this is how it might fail. I do not know much about Http/2 nor about how this Jdk implementation works. I worry there is no guarantee it _never_ will try to do an upgrade request with a chunked POST in the future. I am afraid to release this just to find out it fails intermittently for users in production.
The safest thing I think would be to have some type of retry logic, if a POST request fails with this kind of problem, then try a ping (or a HEAD request?) and then try again, and then if it still fails to fallback to http/1.1. But this also seems like a terrible thing to have to go do.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1511966490
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
By "every time" I mean with every POST request that meets the criteria. (chunked body; no TLS; not forcing Http/1.1). This generally will mean every Solr Update will incur both an Http HEAD and an Http POST. This should be no different if the JDK Client behaved as the Jetty maintainers think it should: to incur both an Empty Upgrade then the Actual Request. It is true most of the time the Http HEAD request is unnecessary. However, I do not know how we know _when_ it is unnecessary. So at the expense of performance, we get it to work correctly on a consistent basis.
@janhoy No ping in constructor! I realized a HEAD request is needed instead when trying this on my own application and finding out we do not allow clients to issue pings! And yes, not in the constructor as your comment about the host possibly not being available yet is a real concern!
Maybe for a Version Two, we could get into retry logic, where if it fails, then try a HEAD request and then try the POST once again. But the more I think about what it would take to do this right the less motivated I feel to go down this path.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 merged PR #2259:
URL: https://github.com/apache/solr/pull/2259
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1498446345
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ break;
+ }
+ case POST:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.POST(result.bodyPublisher);
+ break;
+ }
+ case PUT:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.PUT(result.bodyPublisher);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ resp = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private static class PreparePostPutRequestResult {
Review Comment:
See `org.apache.solr.common.util.Pair`
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1499996594
##########
solr/solrj/src/test/org/apache/solr/client/solrj/impl/Http2SolrClientTest.java:
##########
@@ -335,7 +327,7 @@ public void testCollectionParameters() throws IOException, SolrServerException {
@Test
public void testQueryString() throws Exception {
- testQueryString(Http2SolrClient.class, Http2SolrClient.Builder.class);
+ super.testQueryString();
}
Review Comment:
I initially did it that way but then found that it confused IntelliJ.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506455155
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieHandler;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.apache.solr.common.util.SolrNamedThreadFactory;
+import org.eclipse.jetty.util.BlockingArrayQueue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrJdkClient extends HttpSolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ protected HttpClient client;
+
+ protected ExecutorService executor;
+
+ private boolean shutdownExecutor;
+
+ protected HttpSolrJdkClient(String serverBaseUrl, HttpSolrJdkClient.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+
+ if (builder.executor != null) {
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ BlockingArrayQueue<Runnable> queue = new BlockingArrayQueue<>(32, 32);
+ this.executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 4,
+ 256,
+ 60,
+ TimeUnit.SECONDS,
+ queue,
+ new SolrNamedThreadFactory(this.getClass().getSimpleName()));
+ this.shutdownExecutor = true;
+ }
+ b.executor(this.executor);
+
+ if (builder.useHttp1_1) {
+ b.version(HttpClient.Version.HTTP_1_1);
Review Comment:
If you expressly set the version to HTTP 2, can we avoid the ping altogether?
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieHandler;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.apache.solr.common.util.SolrNamedThreadFactory;
+import org.eclipse.jetty.util.BlockingArrayQueue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrJdkClient extends HttpSolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ protected HttpClient client;
+
+ protected ExecutorService executor;
+
+ private boolean shutdownExecutor;
+
+ protected HttpSolrJdkClient(String serverBaseUrl, HttpSolrJdkClient.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+
+ if (builder.executor != null) {
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ BlockingArrayQueue<Runnable> queue = new BlockingArrayQueue<>(32, 32);
+ this.executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 4,
+ 256,
+ 60,
+ TimeUnit.SECONDS,
+ queue,
+ new SolrNamedThreadFactory(this.getClass().getSimpleName()));
+ this.shutdownExecutor = true;
+ }
+ b.executor(this.executor);
+
+ if (builder.useHttp1_1) {
+ b.version(HttpClient.Version.HTTP_1_1);
+ }
+
+ if (builder.cookieHandler != null) {
+ b.cookieHandler(builder.cookieHandler);
+ }
+
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+
+ // This is a workaround for the case where the first request using
+ // this client:
+ //
+ // (1) no SSL/TLS (2) using POST with stream and (3) using Http/2
+ //
+ // The JDK Http Client will send an upgrade request over Http/1
+ // along with request content in the same request. However,
+ // the Jetty Server underpinning Solr does not accept this.
+ //
+ // By sending a ping before any real requests occur, the client
+ // knows if Solr can accept Http/2, and no additional
+ // upgrade requests will be sent.
+ //
+ // See https://bugs.openjdk.org/browse/JDK-8287589
+ // See https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
+ //
+ try {
+ ping();
+ } catch (Exception e) {
+ // ignore
+ }
+
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ resp = doGet(url, reqb, solrRequest, queryParams);
+ break;
+ }
+ case POST:
+ {
+ resp = doPutOrPost(url, false, reqb, solrRequest, queryParams);
+ break;
+ }
+ case PUT:
+ {
+ resp = doPutOrPost(url, true, reqb, solrRequest, queryParams);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private HttpResponse<InputStream> doGet(
+ String url,
+ HttpRequest.Builder reqb,
+ SolrRequest<?> solrRequest,
+ ModifiableSolrParams queryParams)
+ throws IOException, InterruptedException, URISyntaxException {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ return client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ }
+
+ private HttpResponse<InputStream> doPutOrPost(
+ String url,
+ boolean isPut,
Review Comment:
instead of a boolean, can you use the enum reference? Boolean args are not very clear. And this would allow you to combine both case statements back in the switch.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506577750
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -210,50 +243,50 @@ private HttpResponse<InputStream> doPutOrPost(
}
HttpRequest.BodyPublisher bodyPublisher;
- final PipedOutputStream source;
+ Future<?> contentWritingFuture = null;
if (contentWriter != null) {
- source = new PipedOutputStream();
- PipedInputStream sink = new PipedInputStream(source);
+
+ final PipedOutputStream source = new PipedOutputStream();
+ final PipedInputStream sink = new PipedInputStream(source);
bodyPublisher = HttpRequest.BodyPublishers.ofInputStream(() -> sink);
- // NOCOMMIT - this does not work. The call to "client.send" sometimes will throw an
- // IOException
- // because our thread closes the outputstream too early. But if we wait to close it until
- // after the response returns, "client.send" blocks.
- executor.submit(
- () -> {
- try (source) {
- contentWriter.write(source);
- } catch (Exception e) {
- log.error("Cannot write Content Stream", e);
- }
- });
+
+ contentWritingFuture =
+ executor.submit(
+ () -> {
+ try (source) {
+ contentWriter.write(source);
+ } catch (Exception e) {
+ log.error("Cannot write Content Stream", e);
+ }
+ });
} else if (streams != null && streams.size() == 1) {
- source = null;
InputStream is = streams.iterator().next().getStream();
bodyPublisher = HttpRequest.BodyPublishers.ofInputStream(() -> is);
} else if (queryParams != null && urlParamNames != null) {
- source = null;
ModifiableSolrParams requestParams = queryParams;
queryParams = calculateQueryParams(urlParamNames, requestParams);
queryParams.add(calculateQueryParams(solrRequest.getQueryParams(), requestParams));
bodyPublisher = HttpRequest.BodyPublishers.ofString(requestParams.toString());
} else {
- source = null;
bodyPublisher = HttpRequest.BodyPublishers.noBody();
}
+
if (isPut) {
reqb.PUT(bodyPublisher);
} else {
reqb.POST(bodyPublisher);
}
decorateRequest(reqb, solrRequest);
reqb.uri(new URI(url + "?" + queryParams));
- HttpResponse<InputStream> response =
- client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+
+ HttpResponse<InputStream> response;
try {
- source.close();
- } catch (Exception e1) {
- // ignore
+ response = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ } catch (IOException | InterruptedException | RuntimeException e) {
+ if (contentWritingFuture != null) {
+ contentWritingFuture.cancel(true);
+ }
+ throw e;
}
Review Comment:
yes, good _catch_ here. I changed it.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506546804
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientBuilderBase.java:
##########
@@ -38,7 +37,7 @@ public abstract class HttpSolrClientBuilderBase<
protected Set<String> urlParamNames;
protected Integer maxConnectionsPerHost;
protected ExecutorService executor;
- protected CookieStore cookieStore;
+ protected boolean useHttp1_1 = Boolean.getBoolean("solr.http1");
Review Comment:
This was moved from `Http2SolrClient` so I left it as-is. I initially did not see any value in supporting this in the new client. I reconsidered after realizing the stream-cancelling bug was http/2-specific.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientBuilderBase.java:
##########
@@ -38,7 +37,7 @@ public abstract class HttpSolrClientBuilderBase<
protected Set<String> urlParamNames;
protected Integer maxConnectionsPerHost;
protected ExecutorService executor;
- protected CookieStore cookieStore;
+ protected boolean useHttp1_1 = Boolean.getBoolean("solr.http1");
Review Comment:
This was moved from `Http2SolrClient` so I left it as-is. I initially did not see any value in supporting this in the new client. I reconsidered after realizing the stream-cancelling bug was http/2-specific.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1521443795
##########
gradle/testing/randomization/policies/solr-tests.policy:
##########
Review Comment:
Unfortunately, I think we do need to enumerate every possible url for the security manager as it only allows wildcards in the last path position. Thankfully it allows wildcards for the ports and headers. I am waiting for the CI test failures to start coming once this is merged should any test setup use something other than the 3 localhost variants we have here.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1521448629
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -278,64 +285,74 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
- private volatile boolean headRequested;
- private volatile boolean headSucceeded;
-
/**
- * TODO: we should only try this if not set to Http/1.1 and not TLS
- *
- *
- * This is a workaround for the case where the first request using
- * this client:
+ * This is a workaround for the case where:
*
- * (1) no SSL/TLS (2) using POST with stream and (3) using Http/2
+ * <p>(1) no SSL/TLS (2) using POST with stream and (3) using Http/2
*
- * The JDK Http Client will send an upgrade request over Http/1
- * along with request content in the same request. However,
- * the Jetty Server underpinning Solr does not accept this.
+ * <p>The JDK Http Client will send an upgrade request over Http/1 along with request content in
+ * the same request. However, the Jetty Server underpinning Solr does not accept this.
*
- * By sending a ping before any real requests occur, the client
- * knows if Solr can accept Http/2, and no additional
- * upgrade requests will be sent.
+ * <p>We send a HEAD request first, then the client knows if Solr can accept Http/2, and no
+ * additional upgrade requests will be sent.
*
- * See https://bugs.openjdk.org/browse/JDK-8287589
- * See https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
+ * <p>See https://bugs.openjdk.org/browse/JDK-8287589 See
+ * https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
*
- * We only try once, and if it fails, we downgrade to Http/1
+ * <p>We only try once, and if it fails, we downgrade to Http/1
*
* @param url the url with no request parameters
* @return true if success
*/
- private synchronized boolean maybeTryHeadRequest(String url) {
- if(headRequested) {
+ private boolean maybeTryHeadRequest(String url) {
+ if (forceHttp11 || url == null || url.toLowerCase(Locale.ROOT).startsWith("https://")) {
+ return true;
+ }
+ return maybeTryHeadRequestSync(url);
+ }
+
+ protected volatile boolean headRequested; // must be threadsafe
+ private boolean headSucceeded; // must be threadsafe
+
+ private synchronized boolean maybeTryHeadRequestSync(String url) {
+ if (headRequested) {
return headSucceeded;
}
+
URI uriNoQueryParams;
try {
uriNoQueryParams = new URI(url);
- } catch(URISyntaxException e) {
- headSucceeded = false;
+ } catch (URISyntaxException e) {
+
+ // If the url is invalid, let a subsequent request try again.
return false;
}
- HttpRequest.Builder headReqB = HttpRequest.newBuilder(uriNoQueryParams).method("HEAD", HttpRequest.BodyPublishers.noBody());
+ HttpRequest.Builder headReqB =
+ HttpRequest.newBuilder(uriNoQueryParams)
+ .method("HEAD", HttpRequest.BodyPublishers.noBody());
decorateRequest(headReqB, new QueryRequest());
try {
httpClient.send(headReqB.build(), HttpResponse.BodyHandlers.discarding());
headSucceeded = true;
- } catch(IOException ioe) {
+ } catch (IOException ioe) {
log.warn("Could not issue HEAD request to {} ", url, ioe);
headSucceeded = false;
- } catch(InterruptedException ie) {
+ } catch (InterruptedException ie) {
Thread.currentThread().interrupt();
headSucceeded = false;
} finally {
+
+ // The HEAD request is tried only once. All future requests will skip this check.
headRequested = true;
+
+ if (!headSucceeded) {
+ log.info("All insecure POST requests with a chunked body will use http/1.1");
Review Comment:
I can change this to _unencrypted_. Let's try not to offend our users, eh?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on PR #2259:
URL: https://github.com/apache/solr/pull/2259#issuecomment-1942728149
This is so cool! Let’s make it the new default client in a solrj-core artifact?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1520495658
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -278,64 +285,74 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
- private volatile boolean headRequested;
- private volatile boolean headSucceeded;
-
/**
- * TODO: we should only try this if not set to Http/1.1 and not TLS
- *
- *
- * This is a workaround for the case where the first request using
- * this client:
+ * This is a workaround for the case where:
*
- * (1) no SSL/TLS (2) using POST with stream and (3) using Http/2
+ * <p>(1) no SSL/TLS (2) using POST with stream and (3) using Http/2
*
- * The JDK Http Client will send an upgrade request over Http/1
- * along with request content in the same request. However,
- * the Jetty Server underpinning Solr does not accept this.
+ * <p>The JDK Http Client will send an upgrade request over Http/1 along with request content in
+ * the same request. However, the Jetty Server underpinning Solr does not accept this.
*
- * By sending a ping before any real requests occur, the client
- * knows if Solr can accept Http/2, and no additional
- * upgrade requests will be sent.
+ * <p>We send a HEAD request first, then the client knows if Solr can accept Http/2, and no
+ * additional upgrade requests will be sent.
*
- * See https://bugs.openjdk.org/browse/JDK-8287589
- * See https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
+ * <p>See https://bugs.openjdk.org/browse/JDK-8287589 See
+ * https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
*
- * We only try once, and if it fails, we downgrade to Http/1
+ * <p>We only try once, and if it fails, we downgrade to Http/1
*
* @param url the url with no request parameters
* @return true if success
*/
- private synchronized boolean maybeTryHeadRequest(String url) {
- if(headRequested) {
+ private boolean maybeTryHeadRequest(String url) {
+ if (forceHttp11 || url == null || url.toLowerCase(Locale.ROOT).startsWith("https://")) {
+ return true;
+ }
+ return maybeTryHeadRequestSync(url);
+ }
+
+ protected volatile boolean headRequested; // must be threadsafe
+ private boolean headSucceeded; // must be threadsafe
+
+ private synchronized boolean maybeTryHeadRequestSync(String url) {
+ if (headRequested) {
return headSucceeded;
}
+
URI uriNoQueryParams;
try {
uriNoQueryParams = new URI(url);
- } catch(URISyntaxException e) {
- headSucceeded = false;
+ } catch (URISyntaxException e) {
+
+ // If the url is invalid, let a subsequent request try again.
return false;
}
- HttpRequest.Builder headReqB = HttpRequest.newBuilder(uriNoQueryParams).method("HEAD", HttpRequest.BodyPublishers.noBody());
+ HttpRequest.Builder headReqB =
+ HttpRequest.newBuilder(uriNoQueryParams)
+ .method("HEAD", HttpRequest.BodyPublishers.noBody());
decorateRequest(headReqB, new QueryRequest());
try {
httpClient.send(headReqB.build(), HttpResponse.BodyHandlers.discarding());
headSucceeded = true;
- } catch(IOException ioe) {
+ } catch (IOException ioe) {
log.warn("Could not issue HEAD request to {} ", url, ioe);
headSucceeded = false;
- } catch(InterruptedException ie) {
+ } catch (InterruptedException ie) {
Thread.currentThread().interrupt();
headSucceeded = false;
} finally {
+
+ // The HEAD request is tried only once. All future requests will skip this check.
headRequested = true;
+
+ if (!headSucceeded) {
+ log.info("All insecure POST requests with a chunked body will use http/1.1");
Review Comment:
Would replacing "insecure" with "HTTP" or "unencrypted" or "non-SSL" be fine? To me, there's something about the word "insecure" that refers to overall security posture, thus implying the user is negligent here which is not necessarily the case.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -278,64 +285,74 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
- private volatile boolean headRequested;
- private volatile boolean headSucceeded;
-
/**
- * TODO: we should only try this if not set to Http/1.1 and not TLS
- *
- *
- * This is a workaround for the case where the first request using
- * this client:
+ * This is a workaround for the case where:
*
- * (1) no SSL/TLS (2) using POST with stream and (3) using Http/2
+ * <p>(1) no SSL/TLS (2) using POST with stream and (3) using Http/2
*
- * The JDK Http Client will send an upgrade request over Http/1
- * along with request content in the same request. However,
- * the Jetty Server underpinning Solr does not accept this.
+ * <p>The JDK Http Client will send an upgrade request over Http/1 along with request content in
+ * the same request. However, the Jetty Server underpinning Solr does not accept this.
*
- * By sending a ping before any real requests occur, the client
- * knows if Solr can accept Http/2, and no additional
- * upgrade requests will be sent.
+ * <p>We send a HEAD request first, then the client knows if Solr can accept Http/2, and no
+ * additional upgrade requests will be sent.
*
- * See https://bugs.openjdk.org/browse/JDK-8287589
- * See https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
+ * <p>See https://bugs.openjdk.org/browse/JDK-8287589 See
+ * https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
*
- * We only try once, and if it fails, we downgrade to Http/1
+ * <p>We only try once, and if it fails, we downgrade to Http/1
*
* @param url the url with no request parameters
* @return true if success
*/
- private synchronized boolean maybeTryHeadRequest(String url) {
- if(headRequested) {
+ private boolean maybeTryHeadRequest(String url) {
Review Comment:
Would protected scope be useful to allow a user to change?
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -64,6 +62,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+/**
+ * A SolrClient implementation that communicates to a Solr server using the built-in Java 11+ Http
+ * Client. This client is targeted for those users who wish to minimize application dependencies.
+ * This client will connect to solr using Http/2 but can seamlessly downgrade to Http/1.1 when
+ * connecting to Solr hosts running on older versions.
+ */
public class HttpSolrJdkClient extends HttpSolrClientBase {
Review Comment:
If I suggested the "Jdk" between Solr & Client then I misspoke; I recall HttpJdkSolrClient or "JdkHttpSolrClient" (I like the second) because "SolrClient" is the important base type here.
##########
gradle/testing/randomization/policies/solr-tests.policy:
##########
Review Comment:
This is only for tests; must we be so specific on the URLs?
I'd like to remind us why we even use the security manager for tests in the first place. It's for the file system to tame tests. Makes sense; a clever solution. I never recall anyone advocating that more than that is important. Yet it was a slippery slope of "hey why not" for all these other things. But it's plain here that this is burdensome for us to maintain; not to mention Oracle tells us it's all going away anyhow. I'll raise this on the dev list.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -278,64 +285,74 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
- private volatile boolean headRequested;
- private volatile boolean headSucceeded;
-
/**
- * TODO: we should only try this if not set to Http/1.1 and not TLS
- *
- *
- * This is a workaround for the case where the first request using
- * this client:
+ * This is a workaround for the case where:
*
- * (1) no SSL/TLS (2) using POST with stream and (3) using Http/2
+ * <p>(1) no SSL/TLS (2) using POST with stream and (3) using Http/2
*
- * The JDK Http Client will send an upgrade request over Http/1
- * along with request content in the same request. However,
- * the Jetty Server underpinning Solr does not accept this.
+ * <p>The JDK Http Client will send an upgrade request over Http/1 along with request content in
+ * the same request. However, the Jetty Server underpinning Solr does not accept this.
*
- * By sending a ping before any real requests occur, the client
- * knows if Solr can accept Http/2, and no additional
- * upgrade requests will be sent.
+ * <p>We send a HEAD request first, then the client knows if Solr can accept Http/2, and no
+ * additional upgrade requests will be sent.
*
- * See https://bugs.openjdk.org/browse/JDK-8287589
- * See https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
+ * <p>See https://bugs.openjdk.org/browse/JDK-8287589 See
+ * https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
*
- * We only try once, and if it fails, we downgrade to Http/1
+ * <p>We only try once, and if it fails, we downgrade to Http/1
*
* @param url the url with no request parameters
* @return true if success
*/
- private synchronized boolean maybeTryHeadRequest(String url) {
- if(headRequested) {
+ private boolean maybeTryHeadRequest(String url) {
+ if (forceHttp11 || url == null || url.toLowerCase(Locale.ROOT).startsWith("https://")) {
+ return true;
+ }
+ return maybeTryHeadRequestSync(url);
+ }
+
+ protected volatile boolean headRequested; // must be threadsafe
+ private boolean headSucceeded; // must be threadsafe
+
+ private synchronized boolean maybeTryHeadRequestSync(String url) {
+ if (headRequested) {
return headSucceeded;
}
+
URI uriNoQueryParams;
try {
uriNoQueryParams = new URI(url);
- } catch(URISyntaxException e) {
- headSucceeded = false;
+ } catch (URISyntaxException e) {
+
Review Comment:
remove blank
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1520321105
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
I left this as it is and it only will complete a HEAD request the very first time a POST request with a chunked body is executed. If the HEAD request succeeds it lets the jdk client send upgrade requests from then on. If it fails, it forces http/1.1 for all POST requests with a chunked body. I did add an INFO logging message so users might get a clue of what is going on in these instances.
None of this applies if the request uses TLS. For secure requests, Jetty and the JDK are in agreement on the correct way to negotiate the protocol so all of this is unnecessary. Of course, if the user requests to always downgrade to http/1.1 this log is skipped as well.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on PR #2259:
URL: https://github.com/apache/solr/pull/2259#issuecomment-1989281014
Today I did my best in covering all the possible security manager permissions in *solr-tests.policy*. The *NOCOMIT* with the "all permission" is gone. I will be surprised though once we have CI runs with this if we do not see failures due to the policy file not handling some other variation of "localhost".
Besides this, I will try to write something up for the reference guide and then if there are no objections I would like to merge this to main soon, and ?perhaps maybe to branch_9x as well?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1499996419
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientBuilderBase.java:
##########
@@ -24,7 +24,8 @@
import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.request.RequestWriter;
-public abstract class HttpSolrClientBuilderBase {
+public abstract class HttpSolrClientBuilderBase<
+ B extends HttpSolrClientBuilderBase<?, ?>, C extends Http2SolrClientBase> {
Review Comment:
I did remove the "2" from the name. However, any classes here I am naming `*Base` were factored out of something specific to `Http2SolrClient`. I know there might have been some copy/paste when the various other clients were written but I did not check to see if we could create an abstract builder that applies to all of the clients. That might be a worthy follow-up project though.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -75,9 +77,16 @@ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Buil
if (builder.sslContext != null) {
b.sslContext(builder.sslContext);
}
+
if (builder.executor != null) {
- b.executor(builder.executor);
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ this.executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
Review Comment:
I initially wanted to more-or-less mimic what `java.net.util.http.HttpClient` does if you do not pass in an Executor, and only reluctantly create my own because we need access to it for the pipes. But deferring to `ForbiddenAPIs` I did switch it to the `ExecutorUtil` version (sorry I accidently pushed WIP here).
I will mention here that I am a little concerned that `ExecutorUtil` has some things in it that really do not belong to the client, that exist only for inter-node requests. For this reason I was hoping to avoid it. See my other PR for one case where this could possibly cause trouble. https://github.com/apache/solr/pull/2242
##########
solr/solrj/src/test/org/apache/solr/client/solrj/impl/Http2SolrClientTest.java:
##########
@@ -36,34 +36,32 @@
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Test;
-public class Http2SolrClientTest extends Http2SolrClientTestBase<Http2SolrClient.Builder> {
+public class Http2SolrClientTest extends Http2SolrClientTestBase {
@Override
protected String expectedUserAgent() {
return "Solr[" + Http2SolrClient.class.getName() + "] 2.0";
}
@Override
- protected <B extends HttpSolrClientBuilderBase> B builder(
- String url, int connectionTimeout, int socketTimeout, Class<B> type) {
Review Comment:
I will say that writing a generic builder in Java is no easy task! Maybe I'm wrong on this but I do not think we can avoid unchecked casts here unless we require the user to pass in the target class as an additional parameter on each method.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1515577380
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
I don't think anybody would notice an HTTP 2 to HTTP 1.1 fallback. It works.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1520321105
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
I left this as it is and it only will complete a HEAD request the very first time a POST request with a chunked body is executed. If the HEAD request succeeds it lets the jdk client send upgrade requests from then on. If it fails, it forces http/1.1 for all POST requests with a chunked body. I did add an INFO logging message so users might get a clue of what is going on in these instances.
None of this applies if the request uses TLS. For secure requests, Jetty and the JDK are in agreement on the correct way to negotiate the protocol so all of this is unnecessary. Of course, if the user requests to always downgrade to http/1.1 this logic is skipped as well.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1521445967
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -64,6 +62,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+/**
+ * A SolrClient implementation that communicates to a Solr server using the built-in Java 11+ Http
+ * Client. This client is targeted for those users who wish to minimize application dependencies.
+ * This client will connect to solr using Http/2 but can seamlessly downgrade to Http/1.1 when
+ * connecting to Solr hosts running on older versions.
+ */
public class HttpSolrJdkClient extends HttpSolrClientBase {
Review Comment:
Let's go with `HttpJdkSolrClient`. Putting *Jdk* first emphasis an implementation detail over what the class actually does. It also would be at odds with how our other clients are named. I agree having *Jdk* between *solr* and *client* is a bit awkward.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1499996243
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/Http2SolrClientBase.java:
##########
@@ -0,0 +1,385 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import static org.apache.solr.common.util.Utils.getObjectByPath;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrClient;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.request.V2Request;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.CommonParams;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.Utils;
+
+public abstract class Http2SolrClientBase extends SolrClient {
Review Comment:
I removed the "2' from both base class names.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/Http2SolrClientBase.java:
##########
@@ -371,6 +371,10 @@ public boolean isV2ApiRequest(final SolrRequest<?> request) {
return request instanceof V2Request || request.getPath().contains("/____v2");
}
+ public String getBaseURL() {
Review Comment:
This was copied over from `Http2SolrClient` so to maintain backwards-compatibility we should keep the spelling the same.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506760404
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -0,0 +1,449 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieHandler;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.apache.solr.common.util.SolrNamedThreadFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrJdkClient extends HttpSolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ protected HttpClient httpClient;
+
+ protected ExecutorService executor;
+
+ private boolean shutdownExecutor;
+
+ protected HttpSolrJdkClient(String serverBaseUrl, HttpSolrJdkClient.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+
+ if (builder.executor != null) {
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(1024);
+ this.executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 4,
+ 256,
+ 60,
+ TimeUnit.SECONDS,
+ queue,
+ new SolrNamedThreadFactory(this.getClass().getSimpleName()));
+ this.shutdownExecutor = true;
+ }
+ b.executor(this.executor);
+
+ if (builder.useHttp1_1) {
+ b.version(HttpClient.Version.HTTP_1_1);
+ }
+
+ if (builder.cookieHandler != null) {
+ b.cookieHandler(builder.cookieHandler);
+ }
+
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.httpClient = b.build();
+ updateDefaultMimeTypeForParser();
+
+ // This is a workaround for the case where the first request using
+ // this client:
+ //
+ // (1) no SSL/TLS (2) using POST with stream and (3) using Http/2
+ //
+ // The JDK Http Client will send an upgrade request over Http/1
+ // along with request content in the same request. However,
+ // the Jetty Server underpinning Solr does not accept this.
+ //
+ // By sending a ping before any real requests occur, the client
+ // knows if Solr can accept Http/2, and no additional
+ // upgrade requests will be sent.
+ //
+ // See https://bugs.openjdk.org/browse/JDK-8287589
+ // See https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
+ //
+ try {
+ ping();
Review Comment:
> Second, I am calling "ping" in the constructor, which I felt was a lesser evil than having to check a volatile boolean with each request to see if "ping" was called yet.
It would be somewhat unexpected to have the client start sending calls to the server by just constructing it. May it even cause real issues since startup order between a customer client application and the solr server would then become significant?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1498447578
##########
solr/solrj/src/java/org/apache/solr/client/solrj/embedded/SSLConfigBase.java:
##########
@@ -40,35 +52,75 @@ public SSLConfigBase(
this.trustStorePassword = trustStorePassword;
}
+ /**
+ * If set to false, all other settings are ignored.
+ *
+ * @param useSsl boolean
+ */
public void setUseSSL(boolean useSsl) {
this.useSsl = useSsl;
}
+ /**
+ * Set whether client authentication should be requested. If set to false, truststore settings are
+ * ignored.
+ *
+ * @param clientAuth boolean
+ */
public void setClientAuth(boolean clientAuth) {
this.clientAuth = clientAuth;
}
- /** All other settings on this object are ignored unless this is true */
+ /**
+ * All other settings on this object are ignored unless this is true
+ *
+ * @return boolean
+ */
public boolean isSSLMode() {
return useSsl;
}
+ /**
+ * Whether client authentication should be requested. If false, truststore settings are ignored.
+ *
+ * @return boolean
+ */
public boolean isClientAuthMode() {
return clientAuth;
}
+ /**
+ * The keystore to use.
Review Comment:
I don't know much about keystores; do they have names or is this a path?
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -239,16 +244,16 @@ private void setBasicAuthHeader(SolrRequest<?> solrRequest, HttpRequest.Builder
}
}
- private static final Pattern MIME_TYPE_PATTERN = Pattern.compile("^(.*?)(?:;| |$)");
+ private static final Pattern MIME_TYPE_PATTERN = Pattern.compile("[^;]*");
private String contentTypeToMimeType(String contentType) {
Matcher mimeTypeMatcher = MIME_TYPE_PATTERN.matcher(contentType);
- return mimeTypeMatcher.find() ? mimeTypeMatcher.group(1) : null;
+ return mimeTypeMatcher.find() ? mimeTypeMatcher.group() : null;
}
- private static final Pattern CHARSET_PATTERN = Pattern.compile("(?i)^.*charset=(.*)?(?:;| |$)");
+ private static final Pattern CHARSET_PATTERN = Pattern.compile("(?i)^.*charset=(.*)$");
Review Comment:
I was thinking maybe `(?i)[; ]charset=([^;]*)` but not important
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientBuilderBase.java:
##########
@@ -24,7 +24,8 @@
import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.request.RequestWriter;
-public abstract class HttpSolrClientBuilderBase {
+public abstract class HttpSolrClientBuilderBase<
+ B extends HttpSolrClientBuilderBase<?, ?>, C extends Http2SolrClientBase> {
Review Comment:
Is it overly specific to insist that C extends Http2SolrClientBase? In other words, can just say it's a SolrClient? The "2" in there makes me hope we can remove it one way or another.
##########
solr/solrj/src/test/org/apache/solr/client/solrj/impl/Http2SolrClientTest.java:
##########
@@ -36,34 +36,32 @@
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Test;
-public class Http2SolrClientTest extends Http2SolrClientTestBase<Http2SolrClient.Builder> {
+public class Http2SolrClientTest extends Http2SolrClientTestBase {
@Override
protected String expectedUserAgent() {
return "Solr[" + Http2SolrClient.class.getName() + "] 2.0";
}
@Override
- protected <B extends HttpSolrClientBuilderBase> B builder(
- String url, int connectionTimeout, int socketTimeout, Class<B> type) {
Review Comment:
I'm on the fence of you removing `Class<B> type` for the builder. I *think* this would enable you to remove all those SuppressWarning lines.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientBuilderBase.java:
##########
@@ -43,43 +44,43 @@ public abstract class HttpSolrClientBuilderBase {
protected boolean proxyIsSocks4;
protected boolean proxyIsSecure;
- public HttpSolrClientBuilderBase() {}
-
- protected abstract <B extends Http2SolrClientBase> B build(Class<B> type);
-
- public HttpSolrClientBuilderBase(String baseSolrUrl) {
- this.baseSolrUrl = baseSolrUrl;
- }
+ public abstract C build();
/** Provides a {@link RequestWriter} for created clients to use when handing requests. */
- public HttpSolrClientBuilderBase withRequestWriter(RequestWriter requestWriter) {
+ @SuppressWarnings(value = "unchecked")
+ public B withRequestWriter(RequestWriter requestWriter) {
this.requestWriter = requestWriter;
- return this;
+ return (B) this;
}
/** Provides a {@link ResponseParser} for created clients to use when handling requests. */
- public HttpSolrClientBuilderBase withResponseParser(ResponseParser responseParser) {
+ @SuppressWarnings(value = "unchecked")
+ public B withResponseParser(ResponseParser responseParser) {
this.responseParser = responseParser;
- return this;
+ return (B) this;
}
/** Sets a default for core or collection based requests. */
- public HttpSolrClientBuilderBase withDefaultCollection(String defaultCoreOrCollection) {
+ @SuppressWarnings(value = "unchecked")
+ public B withDefaultCollection(String defaultCoreOrCollection) {
this.defaultCollection = defaultCoreOrCollection;
- return this;
+ return (B) this;
}
- public HttpSolrClientBuilderBase withFollowRedirects(boolean followRedirects) {
+ @SuppressWarnings(value = "unchecked")
Review Comment:
The `value = ` part isn't necessary as it's the default param
##########
solr/solrj/src/test/org/apache/solr/client/solrj/impl/DebugServlet.java:
##########
@@ -125,6 +126,11 @@ private void recordRequest(HttpServletRequest req, HttpServletResponse resp) {
setParameters(req);
setQueryString(req);
setCookies(req);
+ try {
+ requestBody = req.getInputStream().readAllBytes();
Review Comment:
some tidy formatting to do, I see
##########
solr/solrj/src/test/org/apache/solr/client/solrj/impl/Http2SolrClientTest.java:
##########
@@ -335,7 +327,7 @@ public void testCollectionParameters() throws IOException, SolrServerException {
@Test
public void testQueryString() throws Exception {
- testQueryString(Http2SolrClient.class, Http2SolrClient.Builder.class);
+ super.testQueryString();
}
Review Comment:
I *think* this isn't needed, as long as testQueryString in the superclass is marked as a test like this one.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -75,9 +77,16 @@ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Buil
if (builder.sslContext != null) {
b.sslContext(builder.sslContext);
}
+
if (builder.executor != null) {
- b.executor(builder.executor);
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ this.executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
Review Comment:
Normally we use `ExecutorUtil`. Are you copying existing code? FYI @iamsanjay is working on a PR that will likely touch this because the executor initialization is a bit inconsistent / broken.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/embedded/SSLConfigBase.java:
##########
@@ -40,35 +52,75 @@ public SSLConfigBase(
this.trustStorePassword = trustStorePassword;
}
+ /**
+ * If set to false, all other settings are ignored.
+ *
+ * @param useSsl boolean
+ */
public void setUseSSL(boolean useSsl) {
this.useSsl = useSsl;
}
+ /**
+ * Set whether client authentication should be requested. If set to false, truststore settings are
+ * ignored.
+ *
+ * @param clientAuth boolean
+ */
public void setClientAuth(boolean clientAuth) {
this.clientAuth = clientAuth;
}
- /** All other settings on this object are ignored unless this is true */
+ /**
+ * All other settings on this object are ignored unless this is true
+ *
+ * @return boolean
Review Comment:
You should remove these useless lines. In the end your javadoc will be so short that tidy will put it on one actual line, which is rather satisfying.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/Http2SolrClientBase.java:
##########
@@ -371,6 +371,10 @@ public boolean isV2ApiRequest(final SolrRequest<?> request) {
return request instanceof V2Request || request.getPath().contains("/____v2");
}
+ public String getBaseURL() {
Review Comment:
Our current project naming conventions are to use "Url" capitalization in this case.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1496266003
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/Http2SolrClient.java:
##########
@@ -1057,188 +806,64 @@ public void waitForComplete() {
}
}
- public static class Builder {
+ public static class Builder extends HttpSolrClientBuilderBase {
Review Comment:
I agree. The less copy/paste the better.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
Review Comment:
Your name is at least as good as mine. I renamed it. Maybe we could consider someday have some kind of factory so users do not need to think as much about which implementation best meets their needs. This would also make the implementation names matter less.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506575930
##########
solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrJdkClientTest.java:
##########
@@ -278,6 +281,15 @@ public void testUpdateDefault() throws Exception {
@Test
public void testUpdateXml() throws Exception {
+ testUpdateXml(false);
+ }
+
+ @Test
+ public void testUpdateXmlWithHttp11() throws Exception {
+ testUpdateXml(true);
+ }
Review Comment:
I just read up a little on Junit4 Parameterized tests, and well, it seems so much more complicated than what I have done here. Yes, randomization will make the test suite run some ms faster, but I'd rather better know that nothing broke with 1 green test run. In my opinion while randomization is very useful we perhaps overuse it sometimes.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1521446351
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -278,64 +285,74 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
- private volatile boolean headRequested;
- private volatile boolean headSucceeded;
-
/**
- * TODO: we should only try this if not set to Http/1.1 and not TLS
- *
- *
- * This is a workaround for the case where the first request using
- * this client:
+ * This is a workaround for the case where:
*
- * (1) no SSL/TLS (2) using POST with stream and (3) using Http/2
+ * <p>(1) no SSL/TLS (2) using POST with stream and (3) using Http/2
*
- * The JDK Http Client will send an upgrade request over Http/1
- * along with request content in the same request. However,
- * the Jetty Server underpinning Solr does not accept this.
+ * <p>The JDK Http Client will send an upgrade request over Http/1 along with request content in
+ * the same request. However, the Jetty Server underpinning Solr does not accept this.
*
- * By sending a ping before any real requests occur, the client
- * knows if Solr can accept Http/2, and no additional
- * upgrade requests will be sent.
+ * <p>We send a HEAD request first, then the client knows if Solr can accept Http/2, and no
+ * additional upgrade requests will be sent.
*
- * See https://bugs.openjdk.org/browse/JDK-8287589
- * See https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
+ * <p>See https://bugs.openjdk.org/browse/JDK-8287589 See
+ * https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
*
- * We only try once, and if it fails, we downgrade to Http/1
+ * <p>We only try once, and if it fails, we downgrade to Http/1
*
* @param url the url with no request parameters
* @return true if success
*/
- private synchronized boolean maybeTryHeadRequest(String url) {
- if(headRequested) {
+ private boolean maybeTryHeadRequest(String url) {
Review Comment:
Yes, this is a good idea.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1521449499
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -64,6 +62,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+/**
+ * A SolrClient implementation that communicates to a Solr server using the built-in Java 11+ Http
+ * Client. This client is targeted for those users who wish to minimize application dependencies.
+ * This client will connect to solr using Http/2 but can seamlessly downgrade to Http/1.1 when
+ * connecting to Solr hosts running on older versions.
+ */
public class HttpSolrJdkClient extends HttpSolrClientBase {
Review Comment:
Cool; that was my second preference.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1522841030
##########
gradle/testing/randomization/policies/solr-tests.policy:
##########
Review Comment:
According to [docs](https://docs.oracle.com/en%2Fjava%2Fjavase%2F21%2Fdocs%2Fapi%2F%2F/java.base/java/net/URLPermission.html), it looks like a `-` acts as a recursive wildcard. I also think you could use wildcard for method, e.g.
```
permission "java.net.URLPermission" "https://127.0.0.1:*/solr/-", "*:*";
```
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1509879152
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -268,13 +258,14 @@ private HttpResponse<InputStream> doPutOrPost(
bodyPublisher = HttpRequest.BodyPublishers.noBody();
}
+ decorateRequest(reqb, solrRequest);
if (method == SolrRequest.METHOD.PUT) {
- reqb.PUT(bodyPublisher);
+ reqb.method("PUT", bodyPublisher);
} else {
- reqb.POST(bodyPublisher);
+ reqb.method("POST", bodyPublisher);
Review Comment:
could use one line (no if-else) via method.toString to get the string of the method
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
volatile isn't needed because it's only accessed by one method (which ought to be mentioned in a comment so this invariant holds)
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1500030227
##########
solr/solrj/src/java/org/apache/solr/client/solrj/embedded/SSLConfigBase.java:
##########
@@ -40,35 +52,75 @@ public SSLConfigBase(
this.trustStorePassword = trustStorePassword;
}
+ /**
+ * If set to false, all other settings are ignored.
+ *
+ * @param useSsl boolean
+ */
public void setUseSSL(boolean useSsl) {
this.useSsl = useSsl;
}
+ /**
+ * Set whether client authentication should be requested. If set to false, truststore settings are
+ * ignored.
+ *
+ * @param clientAuth boolean
+ */
public void setClientAuth(boolean clientAuth) {
this.clientAuth = clientAuth;
}
- /** All other settings on this object are ignored unless this is true */
+ /**
+ * All other settings on this object are ignored unless this is true
+ *
+ * @return boolean
Review Comment:
I removed `SSLConfigBase` and reverted `SSLConfig` back. My initial thought is the base class could be shared between the two clients but it did not work out that way. Now we need not worry about the javadoc.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1501026138
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -75,9 +77,16 @@ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Buil
if (builder.sslContext != null) {
b.sslContext(builder.sslContext);
}
+
if (builder.executor != null) {
- b.executor(builder.executor);
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ this.executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
Review Comment:
It would be good to have a clearer distinction between the solrj classes that are meant for end user consumption vs the ones that are only ever to be used by the server.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1496266918
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/Http2SolrClientBase.java:
##########
@@ -0,0 +1,385 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import static org.apache.solr.common.util.Utils.getObjectByPath;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrClient;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.request.V2Request;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.CommonParams;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.Utils;
+
+public abstract class Http2SolrClientBase extends SolrClient {
+
+ protected static final String DEFAULT_PATH = "/select";
+ protected static final Charset FALLBACK_CHARSET = StandardCharsets.UTF_8;
+ private static final List<String> errPath = Arrays.asList("metadata", "error-class");
+
+ /** The URL of the Solr server. */
+ protected final String serverBaseUrl;
Review Comment:
This was missed when factoring out the base class. I went ahead and move that getter from `Http2SolrClient` to here.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on PR #2259:
URL: https://github.com/apache/solr/pull/2259#issuecomment-1954793953
I am reminded here that we have a **NOCOMMIT** in `solr-tests.policy`. I am worried here that the only way to properly set the `java.net.URLPermission` is to enumerate all possible URL's (with ports) that might be hit during the test. In this case, we might need to generate the policy file in the @beforeClass method. I am hoping someone can suggest something easier!
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506599770
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieHandler;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.apache.solr.common.util.SolrNamedThreadFactory;
+import org.eclipse.jetty.util.BlockingArrayQueue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrJdkClient extends HttpSolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ protected HttpClient client;
+
+ protected ExecutorService executor;
+
+ private boolean shutdownExecutor;
+
+ protected HttpSolrJdkClient(String serverBaseUrl, HttpSolrJdkClient.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+
+ if (builder.executor != null) {
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ BlockingArrayQueue<Runnable> queue = new BlockingArrayQueue<>(32, 32);
+ this.executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 4,
+ 256,
+ 60,
+ TimeUnit.SECONDS,
+ queue,
+ new SolrNamedThreadFactory(this.getClass().getSimpleName()));
+ this.shutdownExecutor = true;
+ }
+ b.executor(this.executor);
+
+ if (builder.useHttp1_1) {
+ b.version(HttpClient.Version.HTTP_1_1);
+ }
+
+ if (builder.cookieHandler != null) {
+ b.cookieHandler(builder.cookieHandler);
+ }
+
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+
+ // This is a workaround for the case where the first request using
+ // this client:
+ //
+ // (1) no SSL/TLS (2) using POST with stream and (3) using Http/2
+ //
+ // The JDK Http Client will send an upgrade request over Http/1
+ // along with request content in the same request. However,
+ // the Jetty Server underpinning Solr does not accept this.
+ //
+ // By sending a ping before any real requests occur, the client
+ // knows if Solr can accept Http/2, and no additional
+ // upgrade requests will be sent.
+ //
+ // See https://bugs.openjdk.org/browse/JDK-8287589
+ // See https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
+ //
+ try {
+ ping();
+ } catch (Exception e) {
+ // ignore
+ }
+
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ resp = doGet(url, reqb, solrRequest, queryParams);
+ break;
+ }
+ case POST:
+ {
+ resp = doPutOrPost(url, false, reqb, solrRequest, queryParams);
+ break;
+ }
+ case PUT:
+ {
+ resp = doPutOrPost(url, true, reqb, solrRequest, queryParams);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private HttpResponse<InputStream> doGet(
+ String url,
+ HttpRequest.Builder reqb,
+ SolrRequest<?> solrRequest,
+ ModifiableSolrParams queryParams)
+ throws IOException, InterruptedException, URISyntaxException {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ return client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ }
+
+ private HttpResponse<InputStream> doPutOrPost(
+ String url,
+ boolean isPut,
Review Comment:
Not sure it buys much, but I went ahead and made this change.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1523315023
##########
gradle/testing/randomization/policies/solr-tests.policy:
##########
Review Comment:
Yes, the dash wildcard works. I stared at that document so long and do not know how I missed that line. I appreciate your mentioning this and will commit this change to simplify the policy file. It reduces it to just 9 lines. I listed out the methods out of a desire to minimize use of wildcards where I could without needing to add lines to the file.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1499999852
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ break;
+ }
+ case POST:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.POST(result.bodyPublisher);
+ break;
+ }
+ case PUT:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.PUT(result.bodyPublisher);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ resp = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private static class PreparePostPutRequestResult {
+ ModifiableSolrParams queryParams;
+ HttpRequest.BodyPublisher bodyPublisher;
+
+ PreparePostPutRequestResult(
+ ModifiableSolrParams queryParams, HttpRequest.BodyPublisher bodyPublisher) {
+ this.queryParams = queryParams;
+ this.bodyPublisher = bodyPublisher;
+ }
+ }
+
+ private PreparePostPutRequestResult preparePostPutRequest(
+ HttpRequest.Builder reqb, SolrRequest<?> solrRequest, ModifiableSolrParams queryParams)
+ throws IOException {
+ RequestWriter.ContentWriter contentWriter = requestWriter.getContentWriter(solrRequest);
+
+ Collection<ContentStream> streams = null;
+ if (contentWriter == null) {
+ streams = requestWriter.getContentStreams(solrRequest);
+ }
+
+ String contentType = "application/x-www-form-urlencoded";
+ if (contentWriter != null && contentWriter.getContentType() != null) {
+ contentType = contentWriter.getContentType();
+ }
+ reqb.header("Content-Type", contentType);
+
+ if (isMultipart(streams)) {
+ throw new UnsupportedOperationException("This client does not support multipart.");
+ }
+
+ if (contentWriter != null) {
+ // TODO: There is likely a more memory-efficient way to do this!
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ contentWriter.write(baos);
+ byte[] bytes = baos.toByteArray();
+ return new PreparePostPutRequestResult(
Review Comment:
I have the Piped Stream modifications more-or-less implemented. However, I have another NOCOMMIT here as clearly I am missed something!
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ break;
+ }
+ case POST:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.POST(result.bodyPublisher);
+ break;
+ }
+ case PUT:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.PUT(result.bodyPublisher);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ resp = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private static class PreparePostPutRequestResult {
+ ModifiableSolrParams queryParams;
+ HttpRequest.BodyPublisher bodyPublisher;
+
+ PreparePostPutRequestResult(
+ ModifiableSolrParams queryParams, HttpRequest.BodyPublisher bodyPublisher) {
+ this.queryParams = queryParams;
+ this.bodyPublisher = bodyPublisher;
+ }
+ }
+
+ private PreparePostPutRequestResult preparePostPutRequest(
+ HttpRequest.Builder reqb, SolrRequest<?> solrRequest, ModifiableSolrParams queryParams)
+ throws IOException {
+ RequestWriter.ContentWriter contentWriter = requestWriter.getContentWriter(solrRequest);
+
+ Collection<ContentStream> streams = null;
+ if (contentWriter == null) {
+ streams = requestWriter.getContentStreams(solrRequest);
+ }
+
+ String contentType = "application/x-www-form-urlencoded";
+ if (contentWriter != null && contentWriter.getContentType() != null) {
+ contentType = contentWriter.getContentType();
+ }
+ reqb.header("Content-Type", contentType);
+
+ if (isMultipart(streams)) {
+ throw new UnsupportedOperationException("This client does not support multipart.");
+ }
+
+ if (contentWriter != null) {
+ // TODO: There is likely a more memory-efficient way to do this!
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ contentWriter.write(baos);
+ byte[] bytes = baos.toByteArray();
+ return new PreparePostPutRequestResult(
Review Comment:
I have the Piped Stream modifications more-or-less implemented. However, I have another NOCOMMIT here as clearly I missed something!
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1496266236
##########
solr/solrj/src/java/org/apache/solr/client/solrj/embedded/SSLConfigBase.java:
##########
@@ -0,0 +1,75 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.embedded;
+
+public class SSLConfigBase {
Review Comment:
Ok, I added some very minimal Javadocs to this class.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
Review Comment:
I was on the fence with this one. I chose the log warning over the exception because (1) `Http2SolrClient` already does the same thing for `keyStoreReloadIntervalSecs`. and (2) JDK-8214516 _could_ maybe get resolved in such a way that a future JDK could work with socks2 without any changes on our end. But then again, looking at the last (5 year old) comment on that ticket, this doesn't seem likely!
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ break;
+ }
+ case POST:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.POST(result.bodyPublisher);
+ break;
+ }
+ case PUT:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.PUT(result.bodyPublisher);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ resp = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private static class PreparePostPutRequestResult {
Review Comment:
Well, I really wish Java had tuples for this purpose. I always hate creating a little class just so my private method can return two things. To be less misleading I renamed it `PreparePostPutRequestReturnValue`.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1511245577
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
Does a "HEAD request every time" -- do you mean when the client is opened/instantiated? Fine; agree to "progress not perfection". It can be improved later driven by actual vs perceived problems.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1511966490
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
By "every time" I mean with every POST request that meets the criteria. (chunked body; no TLS; not forcing Http/1.1). This generally will mean every Solr Update will incur both an Http HEAD and an Http POST. This should be no different if the JDK Client behaved as the Jetty maintainers think it should: to incur both an Empty Upgrade then the Actual Request. It is true most of the time the Http HEAD request is unnecessary. However, I do not know how we know _when_ it is unnecessary. So at the expense of performance, we get it to work correctly on a consistent basis.
Maybe for a Version Two, we could get into retry logic, where if it fails, then try a HEAD request and then try the POST once again. But the more I think about what it would take to do this right the less motivated I feel to go down this path.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1511969130
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
I'd much prefer the boolean return to ensure we do this once and not every time. Any issues with that?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506760404
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -0,0 +1,449 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieHandler;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.apache.solr.common.util.SolrNamedThreadFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrJdkClient extends HttpSolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ protected HttpClient httpClient;
+
+ protected ExecutorService executor;
+
+ private boolean shutdownExecutor;
+
+ protected HttpSolrJdkClient(String serverBaseUrl, HttpSolrJdkClient.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+
+ if (builder.executor != null) {
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(1024);
+ this.executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 4,
+ 256,
+ 60,
+ TimeUnit.SECONDS,
+ queue,
+ new SolrNamedThreadFactory(this.getClass().getSimpleName()));
+ this.shutdownExecutor = true;
+ }
+ b.executor(this.executor);
+
+ if (builder.useHttp1_1) {
+ b.version(HttpClient.Version.HTTP_1_1);
+ }
+
+ if (builder.cookieHandler != null) {
+ b.cookieHandler(builder.cookieHandler);
+ }
+
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.httpClient = b.build();
+ updateDefaultMimeTypeForParser();
+
+ // This is a workaround for the case where the first request using
+ // this client:
+ //
+ // (1) no SSL/TLS (2) using POST with stream and (3) using Http/2
+ //
+ // The JDK Http Client will send an upgrade request over Http/1
+ // along with request content in the same request. However,
+ // the Jetty Server underpinning Solr does not accept this.
+ //
+ // By sending a ping before any real requests occur, the client
+ // knows if Solr can accept Http/2, and no additional
+ // upgrade requests will be sent.
+ //
+ // See https://bugs.openjdk.org/browse/JDK-8287589
+ // See https://github.com/jetty/jetty.project/issues/9998#issuecomment-1614216870
+ //
+ try {
+ ping();
Review Comment:
> Second, I am calling "ping" in the constructor, which I felt was a lesser evil than having to check a volatile boolean with each request to see if "ping" was called yet.
It would be somewhat unexpected to have the client start sending calls to the server by just constructing it. May it even cause real issues since startup order between a customer client application and the solr server would then become significant?
E.g. what happens if the client is constructed while Solr is unavailable, then this ping call fails (no harm due to the try-catch), and then solr is started before the first query/update is sent. Then I suppose JDK http client will try the request upgrade again since it still does not know the server. And we'd have no second chance to force a ping ahead of time...
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1511202322
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieHandler;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.apache.solr.common.util.SolrNamedThreadFactory;
+import org.eclipse.jetty.util.BlockingArrayQueue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrJdkClient extends HttpSolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ protected HttpClient client;
+
+ protected ExecutorService executor;
+
+ private boolean shutdownExecutor;
+
+ protected HttpSolrJdkClient(String serverBaseUrl, HttpSolrJdkClient.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+
+ if (builder.executor != null) {
+ this.executor = builder.executor;
+ this.shutdownExecutor = false;
+ } else {
+ BlockingArrayQueue<Runnable> queue = new BlockingArrayQueue<>(32, 32);
+ this.executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 4,
+ 256,
+ 60,
+ TimeUnit.SECONDS,
+ queue,
+ new SolrNamedThreadFactory(this.getClass().getSimpleName()));
+ this.shutdownExecutor = true;
+ }
+ b.executor(this.executor);
+
+ if (builder.useHttp1_1) {
+ b.version(HttpClient.Version.HTTP_1_1);
Review Comment:
We can't tell it to always use Http/2. Although this feature was requested (see https://bugs.openjdk.org/browse/JDK-8287589) it does not look like the JDK client will support this any time soon.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506391902
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -108,6 +118,29 @@ protected HttpSolrJdkClient(String serverBaseUrl, HttpSolrJdkClient.Builder buil
}
this.client = b.build();
updateDefaultMimeTypeForParser();
+
+ // This is a workaround for the case where the first request using
Review Comment:
Awesome comment/explanation.
Should this ping be gated on http2 only?
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -64,7 +66,7 @@ public class HttpSolrJdkClient extends HttpSolrClientBase {
private static final String USER_AGENT =
"Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
- private HttpClient client;
+ protected HttpClient client;
Review Comment:
minor, but can we call this `httpClient` to make it clearer wherever we use it what sort of client we're talking about?
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -210,50 +243,50 @@ private HttpResponse<InputStream> doPutOrPost(
}
HttpRequest.BodyPublisher bodyPublisher;
- final PipedOutputStream source;
+ Future<?> contentWritingFuture = null;
if (contentWriter != null) {
- source = new PipedOutputStream();
- PipedInputStream sink = new PipedInputStream(source);
+
+ final PipedOutputStream source = new PipedOutputStream();
+ final PipedInputStream sink = new PipedInputStream(source);
bodyPublisher = HttpRequest.BodyPublishers.ofInputStream(() -> sink);
- // NOCOMMIT - this does not work. The call to "client.send" sometimes will throw an
- // IOException
- // because our thread closes the outputstream too early. But if we wait to close it until
- // after the response returns, "client.send" blocks.
- executor.submit(
- () -> {
- try (source) {
- contentWriter.write(source);
- } catch (Exception e) {
- log.error("Cannot write Content Stream", e);
- }
- });
+
+ contentWritingFuture =
+ executor.submit(
+ () -> {
+ try (source) {
+ contentWriter.write(source);
+ } catch (Exception e) {
+ log.error("Cannot write Content Stream", e);
+ }
+ });
} else if (streams != null && streams.size() == 1) {
- source = null;
InputStream is = streams.iterator().next().getStream();
bodyPublisher = HttpRequest.BodyPublishers.ofInputStream(() -> is);
} else if (queryParams != null && urlParamNames != null) {
- source = null;
ModifiableSolrParams requestParams = queryParams;
queryParams = calculateQueryParams(urlParamNames, requestParams);
queryParams.add(calculateQueryParams(solrRequest.getQueryParams(), requestParams));
bodyPublisher = HttpRequest.BodyPublishers.ofString(requestParams.toString());
} else {
- source = null;
bodyPublisher = HttpRequest.BodyPublishers.noBody();
}
+
if (isPut) {
reqb.PUT(bodyPublisher);
} else {
reqb.POST(bodyPublisher);
}
decorateRequest(reqb, solrRequest);
reqb.uri(new URI(url + "?" + queryParams));
- HttpResponse<InputStream> response =
- client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+
+ HttpResponse<InputStream> response;
try {
- source.close();
- } catch (Exception e1) {
- // ignore
+ response = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ } catch (IOException | InterruptedException | RuntimeException e) {
+ if (contentWritingFuture != null) {
+ contentWritingFuture.cancel(true);
+ }
+ throw e;
}
Review Comment:
It's okay to cancel a task that has already completed. So we can simplify this to move the logic to a finally. No need to catch exceptions.
##########
solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrJdkClientTest.java:
##########
@@ -278,6 +281,15 @@ public void testUpdateDefault() throws Exception {
@Test
public void testUpdateXml() throws Exception {
+ testUpdateXml(false);
+ }
+
+ @Test
+ public void testUpdateXmlWithHttp11() throws Exception {
+ testUpdateXml(true);
+ }
Review Comment:
Could we parameterize the test instead so that the whole test runs in both modes?
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientBuilderBase.java:
##########
@@ -38,7 +37,7 @@ public abstract class HttpSolrClientBuilderBase<
protected Set<String> urlParamNames;
protected Integer maxConnectionsPerHost;
protected ExecutorService executor;
- protected CookieStore cookieStore;
+ protected boolean useHttp1_1 = Boolean.getBoolean("solr.http1");
Review Comment:
I like it but I can't help but notice that no other field here has a default that is defined here. So _maybe_ this new setting should be initialized elsewhere?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1511219624
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
I think these booleans need to go away anyhow. My reasoning here is we cannot guarantee the client will behave the same every time with this 1-shot try with a HEAD request. What if there is a network issue? Then that client instance is stuck on Http/1.1 for its lifetime for these requests.
I think it is probably best to issue the HEAD request every time, to guarantee consistency. This only affects POST requests with a chunked body (updates, not queries). It only will be needed if not TLS, and if the user does not force Http/1.1. I do not think it adds anymore overhead than if it always issued an upgrade request with no body (as the Eclipse maintainers seem to think it ought to.) We can put a note about this in the Javadoc and if none of these options are workable for any user, they always have `Http2SolrClient` to fall back on.
Progress, not Perfection, eh?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1506578312
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -64,7 +66,7 @@ public class HttpSolrJdkClient extends HttpSolrClientBase {
private static final String USER_AGENT =
"Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
- private HttpClient client;
+ protected HttpClient client;
Review Comment:
I changed the name as you suggested.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1511969130
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
I'd much prefer the boolean field to ensure we do this once and not every time. Any issues with that?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1500124827
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -188,33 +210,52 @@ private HttpResponse<InputStream> doPutOrPost(
}
HttpRequest.BodyPublisher bodyPublisher;
-
+ final PipedOutputStream source;
if (contentWriter != null) {
- // TODO: There is likely a more memory-efficient way to do this!
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- contentWriter.write(baos);
- byte[] bytes = baos.toByteArray();
- bodyPublisher = HttpRequest.BodyPublishers.ofByteArray(bytes);
+ source = new PipedOutputStream();
+ PipedInputStream sink = new PipedInputStream(source);
+ bodyPublisher = HttpRequest.BodyPublishers.ofInputStream(() -> sink);
+ // NOCOMMIT - this does not work. The call to "client.send" sometimes will throw an
+ // IOException
+ // because our thread closes the outputstream too early. But if we wait to close it until
Review Comment:
Hmm; doesn't make sense to me. Writer should close to signify there's no more data. The reader will eventually see this and return -1 bytes read to signify EOF. I reviewed the code for that as well.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -188,33 +210,52 @@ private HttpResponse<InputStream> doPutOrPost(
}
HttpRequest.BodyPublisher bodyPublisher;
-
+ final PipedOutputStream source;
if (contentWriter != null) {
- // TODO: There is likely a more memory-efficient way to do this!
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- contentWriter.write(baos);
- byte[] bytes = baos.toByteArray();
- bodyPublisher = HttpRequest.BodyPublishers.ofByteArray(bytes);
+ source = new PipedOutputStream();
+ PipedInputStream sink = new PipedInputStream(source);
+ bodyPublisher = HttpRequest.BodyPublishers.ofInputStream(() -> sink);
+ // NOCOMMIT - this does not work. The call to "client.send" sometimes will throw an
+ // IOException
+ // because our thread closes the outputstream too early. But if we wait to close it until
+ // after the response returns, "client.send" blocks.
+ executor.submit(
+ () -> {
+ try (source) {
+ contentWriter.write(source);
+ } catch (Exception e) {
+ log.error("Cannot write Content Stream", e);
+ }
+ });
} else if (streams != null && streams.size() == 1) {
- ContentStream contentStream = streams.iterator().next();
- InputStream is = contentStream.getStream();
+ source = null;
+ InputStream is = streams.iterator().next().getStream();
bodyPublisher = HttpRequest.BodyPublishers.ofInputStream(() -> is);
} else if (queryParams != null && urlParamNames != null) {
+ source = null;
ModifiableSolrParams requestParams = queryParams;
queryParams = calculateQueryParams(urlParamNames, requestParams);
queryParams.add(calculateQueryParams(solrRequest.getQueryParams(), requestParams));
bodyPublisher = HttpRequest.BodyPublishers.ofString(requestParams.toString());
} else {
+ source = null;
bodyPublisher = HttpRequest.BodyPublishers.noBody();
}
- if(isPut) {
+ if (isPut) {
reqb.PUT(bodyPublisher);
} else {
reqb.POST(bodyPublisher);
}
decorateRequest(reqb, solrRequest);
reqb.uri(new URI(url + "?" + queryParams));
- return client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ HttpResponse<InputStream> response =
+ client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ try {
+ source.close();
+ } catch (Exception e1) {
+ // ignore
+ }
Review Comment:
I don't think this is necessary; source should already be closed. But a concern is that, what if send() or other code fails... we want that executor thread to cancel/stop. I think a Future should be kept so that we can cancel it in a try-finally.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1498445940
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
Review Comment:
You've thought about it more than me; I defer to your judgement.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1511450537
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
I'm ok with HEAD every time as a start. Then perhaps we can make it more clever over time. And if/when JDK improves, we can detect JDK version and conditionally force HTTP/2.
This also means we can avoid sending ping in constructor, right?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1514615289
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrJdkClient.java:
##########
@@ -287,6 +278,64 @@ private HttpResponse<InputStream> doPutOrPost(
return response;
}
+ private volatile boolean headRequested;
+ private volatile boolean headSucceeded;
Review Comment:
The issue with doing it just once is it cannot guarantee the client will behave the same every time. If we try once with the first request, we are at the mercy of luck as to whether or not it could fail for some unrelated reason. Then the client is downgraded to Http/1.1 for its lifetime (which could be the life of the application). I can see future bug reports along the lines of "sometimes, after application restart, my solr client downgrades to Http/1.1 for an unknown reason and then I have to restart again to fix it."
I think the main use-case for chunked body POST requests are index updates, and most users would batch these, so the cost of an additional HEAD request might be negligible?
Maybe I am missing something here, perhaps there is a better way to ensure consistency without adding (much) cost?
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "jdyer1 (via GitHub)" <gi...@apache.org>.
jdyer1 commented on code in PR #2259:
URL: https://github.com/apache/solr/pull/2259#discussion_r1496266548
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ break;
+ }
+ case POST:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.POST(result.bodyPublisher);
+ break;
+ }
+ case PUT:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.PUT(result.bodyPublisher);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ resp = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private static class PreparePostPutRequestResult {
+ ModifiableSolrParams queryParams;
+ HttpRequest.BodyPublisher bodyPublisher;
+
+ PreparePostPutRequestResult(
+ ModifiableSolrParams queryParams, HttpRequest.BodyPublisher bodyPublisher) {
+ this.queryParams = queryParams;
+ this.bodyPublisher = bodyPublisher;
+ }
+ }
+
+ private PreparePostPutRequestResult preparePostPutRequest(
+ HttpRequest.Builder reqb, SolrRequest<?> solrRequest, ModifiableSolrParams queryParams)
+ throws IOException {
+ RequestWriter.ContentWriter contentWriter = requestWriter.getContentWriter(solrRequest);
+
+ Collection<ContentStream> streams = null;
+ if (contentWriter == null) {
+ streams = requestWriter.getContentStreams(solrRequest);
+ }
+
+ String contentType = "application/x-www-form-urlencoded";
+ if (contentWriter != null && contentWriter.getContentType() != null) {
+ contentType = contentWriter.getContentType();
+ }
+ reqb.header("Content-Type", contentType);
+
+ if (isMultipart(streams)) {
+ throw new UnsupportedOperationException("This client does not support multipart.");
+ }
+
+ if (contentWriter != null) {
+ // TODO: There is likely a more memory-efficient way to do this!
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ contentWriter.write(baos);
+ byte[] bytes = baos.toByteArray();
+ return new PreparePostPutRequestResult(
Review Comment:
I might like to try and work on this in a little while, although I was really holding out for some hero to come through with something simple and elegant.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ break;
+ }
+ case POST:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.POST(result.bodyPublisher);
+ break;
+ }
+ case PUT:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.PUT(result.bodyPublisher);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ resp = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private static class PreparePostPutRequestResult {
+ ModifiableSolrParams queryParams;
+ HttpRequest.BodyPublisher bodyPublisher;
+
+ PreparePostPutRequestResult(
+ ModifiableSolrParams queryParams, HttpRequest.BodyPublisher bodyPublisher) {
+ this.queryParams = queryParams;
+ this.bodyPublisher = bodyPublisher;
+ }
+ }
+
+ private PreparePostPutRequestResult preparePostPutRequest(
+ HttpRequest.Builder reqb, SolrRequest<?> solrRequest, ModifiableSolrParams queryParams)
+ throws IOException {
+ RequestWriter.ContentWriter contentWriter = requestWriter.getContentWriter(solrRequest);
+
+ Collection<ContentStream> streams = null;
+ if (contentWriter == null) {
+ streams = requestWriter.getContentStreams(solrRequest);
+ }
+
+ String contentType = "application/x-www-form-urlencoded";
+ if (contentWriter != null && contentWriter.getContentType() != null) {
+ contentType = contentWriter.getContentType();
+ }
+ reqb.header("Content-Type", contentType);
+
+ if (isMultipart(streams)) {
+ throw new UnsupportedOperationException("This client does not support multipart.");
+ }
+
+ if (contentWriter != null) {
+ // TODO: There is likely a more memory-efficient way to do this!
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ contentWriter.write(baos);
+ byte[] bytes = baos.toByteArray();
+ return new PreparePostPutRequestResult(
+ queryParams, HttpRequest.BodyPublishers.ofByteArray(bytes));
+ } else if (streams != null && streams.size() == 1) {
+ ContentStream contentStream = streams.iterator().next();
+ InputStream is = contentStream.getStream();
+ return new PreparePostPutRequestResult(
+ queryParams, HttpRequest.BodyPublishers.ofInputStream(() -> is));
+ } else if (queryParams != null && urlParamNames != null) {
+ ModifiableSolrParams requestParams = queryParams;
+ queryParams = calculateQueryParams(urlParamNames, requestParams);
+ queryParams.add(calculateQueryParams(solrRequest.getQueryParams(), requestParams));
+ return new PreparePostPutRequestResult(
+ queryParams, HttpRequest.BodyPublishers.ofString(requestParams.toString()));
+ } else {
+ return new PreparePostPutRequestResult(queryParams, HttpRequest.BodyPublishers.noBody());
+ }
+ }
+
+ private void decorateRequest(HttpRequest.Builder reqb, SolrRequest<?> solrRequest) {
+ if (requestTimeoutMillis > 0) {
+ reqb.timeout(Duration.of(requestTimeoutMillis, ChronoUnit.MILLIS));
+ } else {
+ reqb.timeout(Duration.of(idleTimeoutMillis, ChronoUnit.MILLIS));
+ }
+ reqb.header("User-Agent", USER_AGENT);
+ setBasicAuthHeader(solrRequest, reqb);
+ Map<String, String> headers = solrRequest.getHeaders();
+ if (headers != null) {
+ for (Map.Entry<String, String> entry : headers.entrySet()) {
+ reqb.header(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
+ private void setBasicAuthHeader(SolrRequest<?> solrRequest, HttpRequest.Builder reqb) {
+ if (solrRequest.getBasicAuthUser() != null && solrRequest.getBasicAuthPassword() != null) {
+ String encoded =
+ basicAuthCredentialsToAuthorizationString(
+ solrRequest.getBasicAuthUser(), solrRequest.getBasicAuthPassword());
+ reqb.header("Authorization", encoded);
+ } else if (basicAuthAuthorizationStr != null) {
+ reqb.header("Authorization", basicAuthAuthorizationStr);
+ }
+ }
+
+ private static final Pattern MIME_TYPE_PATTERN = Pattern.compile("^(.*?)(?:;| |$)");
+
+ private String contentTypeToMimeType(String contentType) {
+ Matcher mimeTypeMatcher = MIME_TYPE_PATTERN.matcher(contentType);
+ return mimeTypeMatcher.find() ? mimeTypeMatcher.group(1) : null;
+ }
+
+ private static final Pattern CHARSET_PATTERN = Pattern.compile("(?i)^.*charset=(.*)?(?:;| |$)");
+
+ private String contentTypeToEncoding(String contentType) {
+ Matcher encodingMatcher = CHARSET_PATTERN.matcher(contentType);
+ return encodingMatcher.find() ? encodingMatcher.group(1) : null;
+ }
+
+ private NamedList<Object> processErrorsAndResponse(
+ SolrRequest<?> solrRequest, ResponseParser parser, HttpResponse<InputStream> resp, String url)
+ throws SolrServerException {
+ String contentType = resp.headers().firstValue("Content-Type").orElse(null);
+ contentType = contentType == null ? "" : contentType;
+ String mimeType = contentTypeToMimeType(contentType);
+ String encoding = contentTypeToEncoding(contentType);
+ String method = resp.request() == null ? null : resp.request().method();
+ int status = resp.statusCode();
+ String reason = "" + status;
+ InputStream is = resp.body();
+ return processErrorsAndResponse(
+ status, reason, method, parser, is, mimeType, encoding, isV2ApiRequest(solrRequest), url);
+ }
+
+ @Override
+ public void close() throws IOException {
Review Comment:
Wouldn't the user need to start their application with an "--adds-opens" in order to be able to get into the implementation class? If there is a way to do this without placing such burdens on users, then I'd agree. I think the unit test at least demonstrates that everything is cleaned up after this falls out of scope, after a full gc. That is the best we can do until we require Jdk21, no?
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ break;
+ }
+ case POST:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.POST(result.bodyPublisher);
+ break;
+ }
+ case PUT:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.PUT(result.bodyPublisher);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ resp = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private static class PreparePostPutRequestResult {
+ ModifiableSolrParams queryParams;
+ HttpRequest.BodyPublisher bodyPublisher;
+
+ PreparePostPutRequestResult(
+ ModifiableSolrParams queryParams, HttpRequest.BodyPublisher bodyPublisher) {
+ this.queryParams = queryParams;
+ this.bodyPublisher = bodyPublisher;
+ }
+ }
+
+ private PreparePostPutRequestResult preparePostPutRequest(
+ HttpRequest.Builder reqb, SolrRequest<?> solrRequest, ModifiableSolrParams queryParams)
+ throws IOException {
+ RequestWriter.ContentWriter contentWriter = requestWriter.getContentWriter(solrRequest);
+
+ Collection<ContentStream> streams = null;
+ if (contentWriter == null) {
+ streams = requestWriter.getContentStreams(solrRequest);
+ }
+
+ String contentType = "application/x-www-form-urlencoded";
+ if (contentWriter != null && contentWriter.getContentType() != null) {
+ contentType = contentWriter.getContentType();
+ }
+ reqb.header("Content-Type", contentType);
+
+ if (isMultipart(streams)) {
+ throw new UnsupportedOperationException("This client does not support multipart.");
+ }
+
+ if (contentWriter != null) {
+ // TODO: There is likely a more memory-efficient way to do this!
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ contentWriter.write(baos);
+ byte[] bytes = baos.toByteArray();
+ return new PreparePostPutRequestResult(
+ queryParams, HttpRequest.BodyPublishers.ofByteArray(bytes));
+ } else if (streams != null && streams.size() == 1) {
+ ContentStream contentStream = streams.iterator().next();
+ InputStream is = contentStream.getStream();
+ return new PreparePostPutRequestResult(
+ queryParams, HttpRequest.BodyPublishers.ofInputStream(() -> is));
+ } else if (queryParams != null && urlParamNames != null) {
+ ModifiableSolrParams requestParams = queryParams;
+ queryParams = calculateQueryParams(urlParamNames, requestParams);
+ queryParams.add(calculateQueryParams(solrRequest.getQueryParams(), requestParams));
+ return new PreparePostPutRequestResult(
+ queryParams, HttpRequest.BodyPublishers.ofString(requestParams.toString()));
+ } else {
+ return new PreparePostPutRequestResult(queryParams, HttpRequest.BodyPublishers.noBody());
+ }
+ }
+
+ private void decorateRequest(HttpRequest.Builder reqb, SolrRequest<?> solrRequest) {
+ if (requestTimeoutMillis > 0) {
+ reqb.timeout(Duration.of(requestTimeoutMillis, ChronoUnit.MILLIS));
+ } else {
+ reqb.timeout(Duration.of(idleTimeoutMillis, ChronoUnit.MILLIS));
+ }
+ reqb.header("User-Agent", USER_AGENT);
+ setBasicAuthHeader(solrRequest, reqb);
+ Map<String, String> headers = solrRequest.getHeaders();
+ if (headers != null) {
+ for (Map.Entry<String, String> entry : headers.entrySet()) {
+ reqb.header(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
+ private void setBasicAuthHeader(SolrRequest<?> solrRequest, HttpRequest.Builder reqb) {
+ if (solrRequest.getBasicAuthUser() != null && solrRequest.getBasicAuthPassword() != null) {
+ String encoded =
+ basicAuthCredentialsToAuthorizationString(
+ solrRequest.getBasicAuthUser(), solrRequest.getBasicAuthPassword());
+ reqb.header("Authorization", encoded);
+ } else if (basicAuthAuthorizationStr != null) {
+ reqb.header("Authorization", basicAuthAuthorizationStr);
+ }
+ }
+
+ private static final Pattern MIME_TYPE_PATTERN = Pattern.compile("^(.*?)(?:;| |$)");
+
+ private String contentTypeToMimeType(String contentType) {
+ Matcher mimeTypeMatcher = MIME_TYPE_PATTERN.matcher(contentType);
+ return mimeTypeMatcher.find() ? mimeTypeMatcher.group(1) : null;
+ }
+
+ private static final Pattern CHARSET_PATTERN = Pattern.compile("(?i)^.*charset=(.*)?(?:;| |$)");
Review Comment:
I simplified it and added a unit test.
##########
solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClientJdkImpl.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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.
+ */
+
+package org.apache.solr.client.solrj.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.CookieStore;
+import java.net.InetSocketAddress;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.time.temporal.ChronoUnit;
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import javax.net.ssl.SSLContext;
+import org.apache.solr.client.solrj.ResponseParser;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.request.RequestWriter;
+import org.apache.solr.client.solrj.util.ClientUtils;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ContentStream;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.ObjectReleaseTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpSolrClientJdkImpl extends Http2SolrClientBase {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String USER_AGENT =
+ "Solr[" + MethodHandles.lookup().lookupClass().getName() + "] 1.0";
+
+ private HttpClient client;
+
+ protected HttpSolrClientJdkImpl(String serverBaseUrl, HttpSolrClientJdkImpl.Builder builder) {
+ super(serverBaseUrl, builder);
+
+ HttpClient.Redirect followRedirects =
+ Boolean.TRUE.equals(builder.followRedirects)
+ ? HttpClient.Redirect.NORMAL
+ : HttpClient.Redirect.NEVER;
+ HttpClient.Builder b = HttpClient.newBuilder().followRedirects(followRedirects);
+ if (builder.sslContext != null) {
+ b.sslContext(builder.sslContext);
+ }
+ if (builder.executor != null) {
+ b.executor(builder.executor);
+ }
+ if (builder.proxyHost != null) {
+ if (builder.proxyIsSocks4) {
+ log.warn(
+ "Socks4 is likely not supported by this client. See https://bugs.openjdk.org/browse/JDK-8214516");
+ }
+ b.proxy(ProxySelector.of(new InetSocketAddress(builder.proxyHost, builder.proxyPort)));
+ }
+ this.client = b.build();
+ updateDefaultMimeTypeForParser();
+ assert ObjectReleaseTracker.track(this);
+ }
+
+ @Override
+ public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
+ throws SolrServerException, IOException {
+ checkClosed();
+ if (ClientUtils.shouldApplyDefaultCollection(collection, solrRequest)) {
+ collection = defaultCollection;
+ }
+ String url = getRequestPath(solrRequest, collection);
+ ResponseParser parser = responseParser(solrRequest);
+ ModifiableSolrParams queryParams = initalizeSolrParams(solrRequest);
+ HttpResponse<InputStream> resp = null;
+ try {
+ var reqb = HttpRequest.newBuilder();
+ switch (solrRequest.getMethod()) {
+ case GET:
+ {
+ validateGetRequest(solrRequest);
+ reqb.GET();
+ break;
+ }
+ case POST:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.POST(result.bodyPublisher);
+ break;
+ }
+ case PUT:
+ {
+ PreparePostPutRequestResult result =
+ preparePostPutRequest(reqb, solrRequest, queryParams);
+ queryParams = result.queryParams;
+ reqb.PUT(result.bodyPublisher);
+ break;
+ }
+ default:
+ {
+ throw new IllegalStateException("Unsupported method: " + solrRequest.getMethod());
+ }
+ }
+ decorateRequest(reqb, solrRequest);
+ reqb.uri(new URI(url + "?" + queryParams));
+ resp = client.send(reqb.build(), HttpResponse.BodyHandlers.ofInputStream());
+ return processErrorsAndResponse(solrRequest, parser, resp, url);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ } catch (HttpTimeoutException e) {
+ throw new SolrServerException(
+ "Timeout occurred while waiting response from server at: " + url, e);
+ } catch (SolrException se) {
+ throw se;
+ } catch (URISyntaxException | RuntimeException re) {
+ throw new SolrServerException(re);
+ } finally {
+ // See
+ // https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()
+ if (!wantStream(parser)) {
+ try {
+ resp.body().close();
+ } catch (Exception e1) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private static class PreparePostPutRequestResult {
+ ModifiableSolrParams queryParams;
+ HttpRequest.BodyPublisher bodyPublisher;
+
+ PreparePostPutRequestResult(
+ ModifiableSolrParams queryParams, HttpRequest.BodyPublisher bodyPublisher) {
+ this.queryParams = queryParams;
+ this.bodyPublisher = bodyPublisher;
+ }
+ }
+
+ private PreparePostPutRequestResult preparePostPutRequest(
+ HttpRequest.Builder reqb, SolrRequest<?> solrRequest, ModifiableSolrParams queryParams)
+ throws IOException {
+ RequestWriter.ContentWriter contentWriter = requestWriter.getContentWriter(solrRequest);
+
+ Collection<ContentStream> streams = null;
+ if (contentWriter == null) {
+ streams = requestWriter.getContentStreams(solrRequest);
+ }
+
+ String contentType = "application/x-www-form-urlencoded";
+ if (contentWriter != null && contentWriter.getContentType() != null) {
+ contentType = contentWriter.getContentType();
+ }
+ reqb.header("Content-Type", contentType);
+
+ if (isMultipart(streams)) {
+ throw new UnsupportedOperationException("This client does not support multipart.");
+ }
+
+ if (contentWriter != null) {
+ // TODO: There is likely a more memory-efficient way to do this!
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ contentWriter.write(baos);
+ byte[] bytes = baos.toByteArray();
+ return new PreparePostPutRequestResult(
+ queryParams, HttpRequest.BodyPublishers.ofByteArray(bytes));
+ } else if (streams != null && streams.size() == 1) {
+ ContentStream contentStream = streams.iterator().next();
+ InputStream is = contentStream.getStream();
+ return new PreparePostPutRequestResult(
+ queryParams, HttpRequest.BodyPublishers.ofInputStream(() -> is));
+ } else if (queryParams != null && urlParamNames != null) {
+ ModifiableSolrParams requestParams = queryParams;
+ queryParams = calculateQueryParams(urlParamNames, requestParams);
+ queryParams.add(calculateQueryParams(solrRequest.getQueryParams(), requestParams));
+ return new PreparePostPutRequestResult(
+ queryParams, HttpRequest.BodyPublishers.ofString(requestParams.toString()));
+ } else {
+ return new PreparePostPutRequestResult(queryParams, HttpRequest.BodyPublishers.noBody());
+ }
+ }
+
+ private void decorateRequest(HttpRequest.Builder reqb, SolrRequest<?> solrRequest) {
+ if (requestTimeoutMillis > 0) {
+ reqb.timeout(Duration.of(requestTimeoutMillis, ChronoUnit.MILLIS));
+ } else {
+ reqb.timeout(Duration.of(idleTimeoutMillis, ChronoUnit.MILLIS));
+ }
+ reqb.header("User-Agent", USER_AGENT);
+ setBasicAuthHeader(solrRequest, reqb);
+ Map<String, String> headers = solrRequest.getHeaders();
+ if (headers != null) {
+ for (Map.Entry<String, String> entry : headers.entrySet()) {
+ reqb.header(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
+ private void setBasicAuthHeader(SolrRequest<?> solrRequest, HttpRequest.Builder reqb) {
+ if (solrRequest.getBasicAuthUser() != null && solrRequest.getBasicAuthPassword() != null) {
+ String encoded =
+ basicAuthCredentialsToAuthorizationString(
+ solrRequest.getBasicAuthUser(), solrRequest.getBasicAuthPassword());
+ reqb.header("Authorization", encoded);
+ } else if (basicAuthAuthorizationStr != null) {
+ reqb.header("Authorization", basicAuthAuthorizationStr);
+ }
+ }
+
+ private static final Pattern MIME_TYPE_PATTERN = Pattern.compile("^(.*?)(?:;| |$)");
Review Comment:
I simplified it and added a unit test.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org
Re: [PR] SOLR-599 New Solr Client Using Java 11+ java.net.http.HttpClient [solr]
Posted by "dsmiley (via GitHub)" <gi...@apache.org>.
dsmiley commented on PR #2259:
URL: https://github.com/apache/solr/pull/2259#issuecomment-1998729601
@jdyer1 Lets use a PR to collaborate on workaroundToReleaseThreads_noClosableUntilJava21. Getting all threads and interrupting each is a hack I'd like to try and avoid. I don't recall any test doing that despite us having a crazy number of tests.
--
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: issues-unsubscribe@solr.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org