UndertowXhrTransport.java 19.6 KB
Newer Older
1
/*
J
Juergen Hoeller 已提交
2
 * Copyright 2002-2016 the original author or authors.
3 4 5 6 7
 *
 * Licensed 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
 *
J
Juergen Hoeller 已提交
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9 10 11 12 13 14 15 16 17 18 19 20
 *
 * 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.springframework.web.socket.sockjs.client;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
21
import java.lang.reflect.Method;
22 23 24 25 26 27 28 29 30 31 32 33
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;

import io.undertow.client.ClientCallback;
import io.undertow.client.ClientConnection;
import io.undertow.client.ClientExchange;
import io.undertow.client.ClientRequest;
import io.undertow.client.ClientResponse;
import io.undertow.client.UndertowClient;
34 35 36
import io.undertow.connector.ByteBufferPool;
import io.undertow.connector.PooledByteBuffer;
import io.undertow.server.DefaultByteBufferPool;
37 38 39 40 41 42 43
import io.undertow.util.AttachmentKey;
import io.undertow.util.HeaderMap;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import io.undertow.util.StringReadChannelListener;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
44
import org.xnio.IoFuture;
45 46 47
import org.xnio.IoUtils;
import org.xnio.OptionMap;
import org.xnio.Options;
48
import org.xnio.Pool;
49 50 51 52 53 54 55 56 57
import org.xnio.Xnio;
import org.xnio.XnioWorker;
import org.xnio.channels.StreamSinkChannel;
import org.xnio.channels.StreamSourceChannel;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
58 59
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
60 61 62 63 64 65 66 67 68 69 70 71
import org.springframework.util.concurrent.SettableListenableFuture;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.sockjs.SockJsException;
import org.springframework.web.socket.sockjs.SockJsTransportFailureException;
import org.springframework.web.socket.sockjs.frame.SockJsFrame;

/**
 * An XHR transport based on Undertow's {@link io.undertow.client.UndertowClient}.
72
 * Compatible with Undertow 1.0 to 1.3, as of Spring Framework 4.2.2.
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
 *
 * <p>When used for testing purposes (e.g. load testing) or for specific use cases
 * (like HTTPS configuration), a custom OptionMap should be provided:
 *
 * <pre class="code">
 * OptionMap optionMap = OptionMap.builder()
 *   .set(Options.WORKER_IO_THREADS, 8)
 *   .set(Options.TCP_NODELAY, true)
 *   .set(Options.KEEP_ALIVE, true)
 *   .set(Options.WORKER_NAME, "SockJSClient")
 *   .getMap();
 *
 * UndertowXhrTransport transport = new UndertowXhrTransport(optionMap);
 * </pre>
 *
 * @author Brian Clozel
R
Rossen Stoyanchev 已提交
89
 * @author Rossen Stoyanchev
90 91 92
 * @since 4.1.2
 * @see org.xnio.Options
 */
93
public class UndertowXhrTransport extends AbstractXhrTransport {
94 95 96

	private static final AttachmentKey<String> RESPONSE_BODY = AttachmentKey.create(String.class);

97 98 99
	private static final boolean undertow13Present = ClassUtils.isPresent(
			"io.undertow.connector.ByteBufferPool", UndertowXhrTransport.class.getClassLoader());

100

101 102
	private final OptionMap optionMap;

R
Rossen Stoyanchev 已提交
103 104
	private final UndertowClient httpClient;

105 106
	private final XnioWorker worker;

107
	private final UndertowBufferSupport undertowBufferSupport;
108

109 110 111 112 113 114

	public UndertowXhrTransport() throws IOException {
		this(OptionMap.builder().parse(Options.WORKER_NAME, "SockJSClient").getMap());
	}

	public UndertowXhrTransport(OptionMap optionMap) throws IOException {
J
Juergen Hoeller 已提交
115
		Assert.notNull(optionMap, "OptionMap is required");
116
		this.optionMap = optionMap;
J
Juergen Hoeller 已提交
117
		this.httpClient = UndertowClient.getInstance();
118
		this.worker = Xnio.getInstance().createWorker(optionMap);
119 120
		this.undertowBufferSupport =
				(undertow13Present ? new Undertow13BufferSupport() : new UndertowXnioBufferSupport());
121 122
	}

123

124 125 126 127
	/**
	 * Return Undertow's native HTTP client
	 */
	public UndertowClient getHttpClient() {
128
		return this.httpClient;
129 130 131
	}

	/**
132 133
	 * Return the {@link org.xnio.XnioWorker} backing the I/O operations
	 * for Undertow's HTTP client.
134 135 136 137 138 139
	 * @see org.xnio.Xnio
	 */
	public XnioWorker getWorker() {
		return this.worker;
	}

140

R
Rossen Stoyanchev 已提交
141 142 143 144 145
	@Override
	protected void connectInternal(TransportRequest request, WebSocketHandler handler, URI receiveUrl,
			HttpHeaders handshakeHeaders, XhrClientSockJsSession session,
			SettableListenableFuture<WebSocketSession> connectFuture) {

146
		executeReceiveRequest(request, receiveUrl, handshakeHeaders, session, connectFuture);
R
Rossen Stoyanchev 已提交
147 148
	}

149 150
	private void executeReceiveRequest(final TransportRequest transportRequest,
			final URI url, final HttpHeaders headers, final XhrClientSockJsSession session,
R
Rossen Stoyanchev 已提交
151 152 153
			final SettableListenableFuture<WebSocketSession> connectFuture) {

		if (logger.isTraceEnabled()) {
J
Juergen Hoeller 已提交
154
			logger.trace("Starting XHR receive request for " + url);
R
Rossen Stoyanchev 已提交
155 156
		}

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
		ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {
			@Override
			public void completed(ClientConnection connection) {
				ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
				HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
				request.getRequestHeaders().add(headerName, url.getHost());
				addHttpHeaders(request, headers);
				HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
				connection.sendRequest(request, createReceiveCallback(transportRequest,
						url, httpHeaders, session, connectFuture));
			}

			@Override
			public void failed(IOException ex) {
				throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
			}
		};

		this.undertowBufferSupport.httpClientConnect(this.httpClient, clientCallback, url, worker, this.optionMap);
R
Rossen Stoyanchev 已提交
176 177 178 179 180 181 182 183 184 185 186
	}

	private static void addHttpHeaders(ClientRequest request, HttpHeaders headers) {
		HeaderMap headerMap = request.getRequestHeaders();
		for (String name : headers.keySet()) {
			for (String value : headers.get(name)) {
				headerMap.add(HttpString.tryFromString(name), value);
			}
		}
	}

187 188
	private ClientCallback<ClientExchange> createReceiveCallback(final TransportRequest transportRequest,
			final URI url, final HttpHeaders headers, final XhrClientSockJsSession sockJsSession,
R
Rossen Stoyanchev 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
			final SettableListenableFuture<WebSocketSession> connectFuture) {

		return new ClientCallback<ClientExchange>() {
			@Override
			public void completed(final ClientExchange exchange) {
				exchange.setResponseListener(new ClientCallback<ClientExchange>() {
					@Override
					public void completed(ClientExchange result) {
						ClientResponse response = result.getResponse();
						if (response.getResponseCode() != 200) {
							HttpStatus status = HttpStatus.valueOf(response.getResponseCode());
							IoUtils.safeClose(result.getConnection());
							onFailure(new HttpServerErrorException(status, "Unexpected XHR receive status"));
						}
						else {
204 205 206
							SockJsResponseListener listener = new SockJsResponseListener(
									transportRequest, result.getConnection(), url, headers,
									sockJsSession, connectFuture);
R
Rossen Stoyanchev 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
							listener.setup(result.getResponseChannel());
						}
						if (logger.isTraceEnabled()) {
							logger.trace("XHR receive headers: " + toHttpHeaders(response.getResponseHeaders()));
						}
						try {
							StreamSinkChannel channel = result.getRequestChannel();
							channel.shutdownWrites();
							if (!channel.flush()) {
								channel.getWriteSetter().set(ChannelListeners.<StreamSinkChannel>flushingChannelListener(null, null));
								channel.resumeWrites();
							}
						}
						catch (IOException exc) {
							IoUtils.safeClose(result.getConnection());
							onFailure(exc);
						}
					}
225

R
Rossen Stoyanchev 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
					@Override
					public void failed(IOException exc) {
						IoUtils.safeClose(exchange.getConnection());
						onFailure(exc);
					}
				});
			}

			@Override
			public void failed(IOException exc) {
				onFailure(exc);
			}

			private void onFailure(Throwable failure) {
				if (connectFuture.setException(failure)) {
					return;
				}
				if (sockJsSession.isDisconnected()) {
					sockJsSession.afterTransportClosed(null);
				}
				else {
					sockJsSession.handleTransportError(failure);
					sockJsSession.afterTransportClosed(new CloseStatus(1006, failure.getMessage()));
				}
			}
		};
	}

	private static HttpHeaders toHttpHeaders(HeaderMap headerMap) {
		HttpHeaders httpHeaders = new HttpHeaders();
		for (HttpString name : headerMap.getHeaderNames()) {
			for (String value : headerMap.get(name)) {
				httpHeaders.add(name.toString(), value);
			}
		}
		return httpHeaders;
	}

264
	@Override
265 266
	protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) {
		return executeRequest(infoUrl, Methods.GET, headers, null);
267 268 269 270 271 272 273 274
	}

	@Override
	protected ResponseEntity<String> executeSendRequestInternal(URI url, HttpHeaders headers, TextMessage message) {
		return executeRequest(url, Methods.POST, headers, message.getPayload());
	}

	protected ResponseEntity<String> executeRequest(URI url, HttpString method, HttpHeaders headers, String body) {
275 276
		CountDownLatch latch = new CountDownLatch(1);
		List<ClientResponse> responses = new CopyOnWriteArrayList<ClientResponse>();
277 278

		try {
279 280
			ClientConnection connection = this.undertowBufferSupport
					.httpClientConnect(this.httpClient, url, this.worker, this.optionMap).get();
281
			try {
282
				ClientRequest request = new ClientRequest().setMethod(method).setPath(url.getPath());
283
				request.getRequestHeaders().add(HttpString.tryFromString(HttpHeaders.HOST), url.getHost());
284
				if (body != null && !body.isEmpty()) {
R
Rossen Stoyanchev 已提交
285 286
					HttpString headerName = HttpString.tryFromString(HttpHeaders.CONTENT_LENGTH);
					request.getRequestHeaders().add(headerName, body.length());
287 288 289 290 291
				}
				addHttpHeaders(request, headers);
				connection.sendRequest(request, createRequestCallback(body, responses, latch));

				latch.await();
292
				ClientResponse response = responses.iterator().next();
293 294 295 296 297 298 299 300 301 302 303 304
				HttpStatus status = HttpStatus.valueOf(response.getResponseCode());
				HttpHeaders responseHeaders = toHttpHeaders(response.getResponseHeaders());
				String responseBody = response.getAttachment(RESPONSE_BODY);
				return (responseBody != null ?
						new ResponseEntity<String>(responseBody, responseHeaders, status) :
						new ResponseEntity<String>(responseHeaders, status));
			}
			finally {
				IoUtils.safeClose(connection);
			}
		}
		catch (IOException ex) {
305
			throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
306
		}
307 308
		catch (InterruptedException ex) {
			throw new SockJsTransportFailureException("Interrupted while processing request to " + url, ex);
309 310 311 312 313 314 315 316 317 318 319
		}
	}

	private ClientCallback<ClientExchange> createRequestCallback(final String body,
			final List<ClientResponse> responses, final CountDownLatch latch) {

		return new ClientCallback<ClientExchange>() {
			@Override
			public void completed(ClientExchange result) {
				result.setResponseListener(new ClientCallback<ClientExchange>() {
					@Override
320
					@SuppressWarnings("deprecation")
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
					public void completed(final ClientExchange result) {
						responses.add(result.getResponse());
						new StringReadChannelListener(result.getConnection().getBufferPool()) {
							@Override
							protected void stringDone(String string) {
								result.getResponse().putAttachment(RESPONSE_BODY, string);
								latch.countDown();
							}
							@Override
							protected void error(IOException ex) {
								onFailure(latch, ex);
							}
						}.setup(result.getResponseChannel());
					}
					@Override
					public void failed(IOException ex) {
						onFailure(latch, ex);
					}
				});
				try {
R
Rossen Stoyanchev 已提交
341
					if (body != null) {
342 343 344
						result.getRequestChannel().write(ByteBuffer.wrap(body.getBytes()));
					}
					result.getRequestChannel().shutdownWrites();
R
Rossen Stoyanchev 已提交
345
					if (!result.getRequestChannel().flush()) {
346 347 348 349 350 351 352 353 354
						result.getRequestChannel().getWriteSetter()
								.set(ChannelListeners.<StreamSinkChannel>flushingChannelListener(null, null));
						result.getRequestChannel().resumeWrites();
					}
				}
				catch (IOException ex) {
					onFailure(latch, ex);
				}
			}
R
Rossen Stoyanchev 已提交
355

356 357 358 359
			@Override
			public void failed(IOException ex) {
				onFailure(latch, ex);
			}
R
Rossen Stoyanchev 已提交
360

361
			private void onFailure(CountDownLatch latch, IOException ex) {
362
				latch.countDown();
363
				throw new SockJsTransportFailureException("Failed to execute request", ex);
364 365 366 367
			}
		};
	}

368

R
Rossen Stoyanchev 已提交
369
	private class SockJsResponseListener implements ChannelListener<StreamSourceChannel> {
370

371 372
		private final TransportRequest request;

373
		private final ClientConnection connection;
374

375
		private final URI url;
376

377
		private final HttpHeaders headers;
378

379
		private final XhrClientSockJsSession session;
380

381 382 383 384
		private final SettableListenableFuture<WebSocketSession> connectFuture;

		private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

385
		public SockJsResponseListener(TransportRequest request, ClientConnection connection, URI url,
R
Rossen Stoyanchev 已提交
386 387
				HttpHeaders headers, XhrClientSockJsSession sockJsSession,
				SettableListenableFuture<WebSocketSession> connectFuture) {
388

389
			this.request = request;
390 391 392 393 394 395 396
			this.connection = connection;
			this.url = url;
			this.headers = headers;
			this.session = sockJsSession;
			this.connectFuture = connectFuture;
		}

397
		public void setup(StreamSourceChannel channel) {
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
			channel.suspendReads();
			channel.getReadSetter().set(this);
			channel.resumeReads();
		}

		@Override
		public void handleEvent(StreamSourceChannel channel) {
			if (this.session.isDisconnected()) {
				if (logger.isDebugEnabled()) {
					logger.debug("SockJS sockJsSession closed, closing response.");
				}
				IoUtils.safeClose(this.connection);
				throw new SockJsException("Session closed.", this.session.getId(), null);
			}

413
			Object pooled = undertowBufferSupport.allocatePooledResource();
414 415 416
			try {
				int r;
				do {
417
					ByteBuffer buffer = undertowBufferSupport.getByteBuffer(pooled);
418 419 420 421 422 423 424 425 426 427
					buffer.clear();
					r = channel.read(buffer);
					buffer.flip();
					if (r == 0) {
						return;
					}
					else if (r == -1) {
						onSuccess();
					}
					else {
428
						while (buffer.hasRemaining()) {
429 430 431 432 433 434 435 436 437
							int b = buffer.get();
							if (b == '\n') {
								handleFrame();
							}
							else {
								this.outputStream.write(b);
							}
						}
					}
438 439
				}
				while (r > 0);
440 441 442 443 444
			}
			catch (IOException exc) {
				onFailure(exc);
			}
			finally {
445
				undertowBufferSupport.closePooledResource(pooled);
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
			}
		}

		private void handleFrame() {
			byte[] bytes = this.outputStream.toByteArray();
			this.outputStream.reset();
			String content = new String(bytes, SockJsFrame.CHARSET);
			if (logger.isTraceEnabled()) {
				logger.trace("XHR content received: " + content);
			}
			if (!PRELUDE.equals(content)) {
				this.session.handleFrame(new String(bytes, SockJsFrame.CHARSET));
			}
		}

		public void onSuccess() {
			if (this.outputStream.size() > 0) {
				handleFrame();
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive request completed.");
			}
			IoUtils.safeClose(this.connection);
469
			executeReceiveRequest(this.request, this.url, this.headers, this.session, this.connectFuture);
470 471 472 473
		}

		public void onFailure(Throwable failure) {
			IoUtils.safeClose(this.connection);
J
Juergen Hoeller 已提交
474
			if (this.connectFuture.setException(failure)) {
475 476 477 478 479 480 481 482 483 484 485 486
				return;
			}
			if (this.session.isDisconnected()) {
				this.session.afterTransportClosed(null);
			}
			else {
				this.session.handleTransportError(failure);
				this.session.afterTransportClosed(new CloseStatus(1006, failure.getMessage()));
			}
		}
	}

487

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
	private interface UndertowBufferSupport {

		Object allocatePooledResource();

		ByteBuffer getByteBuffer(Object pooled);

		void closePooledResource(Object pooled);

		void httpClientConnect(UndertowClient httpClient, final ClientCallback<ClientConnection> listener,
				final URI uri, final XnioWorker worker, OptionMap options);

		IoFuture<ClientConnection> httpClientConnect(UndertowClient httpClient, final URI uri,
				final XnioWorker worker, OptionMap options);
	}

503 504

	private class UndertowXnioBufferSupport implements UndertowBufferSupport {
505 506 507 508 509 510 511

		private final org.xnio.Pool<ByteBuffer> xnioBufferPool;

		private final Method httpClientConnectCallbackMethod;

		private final Method httpClientConnectMethod;

512
		public UndertowXnioBufferSupport() {
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
			this.xnioBufferPool = new org.xnio.ByteBufferSlicePool(1048, 1048);
			this.httpClientConnectCallbackMethod = ReflectionUtils.findMethod(UndertowClient.class, "connect",
					ClientCallback.class, URI.class, XnioWorker.class, Pool.class, OptionMap.class);
			this.httpClientConnectMethod = ReflectionUtils.findMethod(UndertowClient.class, "connect",
					URI.class, XnioWorker.class, Pool.class, OptionMap.class);
		}

		@Override
		public Object allocatePooledResource() {
			return this.xnioBufferPool.allocate();
		}

		@Override
		@SuppressWarnings("unchecked")
		public ByteBuffer getByteBuffer(Object pooled) {
			return ((org.xnio.Pooled<ByteBuffer>) pooled).getResource();
		}

		@Override
		@SuppressWarnings("unchecked")
		public void closePooledResource(Object pooled) {
			((org.xnio.Pooled<ByteBuffer>) pooled).close();
		}

		@Override
		public void httpClientConnect(UndertowClient httpClient, ClientCallback<ClientConnection> listener, URI uri,
				XnioWorker worker, OptionMap options) {
			ReflectionUtils.invokeMethod(httpClientConnectCallbackMethod, httpClient, listener, uri, worker,
					this.xnioBufferPool, options);
		}

		@Override
		@SuppressWarnings("unchecked")
		public IoFuture<ClientConnection> httpClientConnect(UndertowClient httpClient, URI uri,
				XnioWorker worker, OptionMap options) {
			return (IoFuture<ClientConnection>) ReflectionUtils.invokeMethod(httpClientConnectMethod, httpClient, uri,
					worker, this.xnioBufferPool, options);
		}
	}

553

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
	private class Undertow13BufferSupport implements UndertowBufferSupport {

		private final ByteBufferPool undertowBufferPool;

		private final Method httpClientConnectCallbackMethod;

		private final Method httpClientConnectMethod;

		public Undertow13BufferSupport() {
			this.undertowBufferPool = new DefaultByteBufferPool(false, 1024, -1, 2);
			this.httpClientConnectCallbackMethod = ReflectionUtils.findMethod(UndertowClient.class, "connect",
					ClientCallback.class, URI.class, XnioWorker.class, ByteBufferPool.class, OptionMap.class);
			this.httpClientConnectMethod = ReflectionUtils.findMethod(UndertowClient.class, "connect",
					URI.class, XnioWorker.class, ByteBufferPool.class, OptionMap.class);
		}

		@Override
		public Object allocatePooledResource() {
			return this.undertowBufferPool.allocate();
		}

		@Override
		public ByteBuffer getByteBuffer(Object pooled) {
			return ((PooledByteBuffer) pooled).getBuffer();
		}

		@Override
		public void closePooledResource(Object pooled) {
			((PooledByteBuffer) pooled).close();
		}

		@Override
		public void httpClientConnect(UndertowClient httpClient, ClientCallback<ClientConnection> listener, URI uri,
				XnioWorker worker, OptionMap options) {
			ReflectionUtils.invokeMethod(httpClientConnectCallbackMethod, httpClient, listener, uri,
589
					worker, this.undertowBufferPool, options);
590 591 592 593 594 595 596 597 598 599 600
		}

		@Override
		@SuppressWarnings("unchecked")
		public IoFuture<ClientConnection> httpClientConnect(UndertowClient httpClient, URI uri,
				XnioWorker worker, OptionMap options) {
			return (IoFuture<ClientConnection>) ReflectionUtils.invokeMethod(httpClientConnectMethod, httpClient, uri,
					worker, this.undertowBufferPool, options);
		}
	}

601
}