001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2016-2024 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.http;
020
021import java.io.IOException;
022import java.net.InetSocketAddress;
023import java.net.SocketAddress;
024import java.nio.Buffer;
025import java.nio.ByteBuffer;
026import java.nio.CharBuffer;
027import java.util.Optional;
028import java.util.concurrent.Callable;
029import org.jdrupes.httpcodec.ClientEngine;
030import org.jdrupes.httpcodec.Codec;
031import org.jdrupes.httpcodec.Decoder;
032import org.jdrupes.httpcodec.MessageHeader;
033import org.jdrupes.httpcodec.ProtocolException;
034import org.jdrupes.httpcodec.protocols.http.HttpField;
035import org.jdrupes.httpcodec.protocols.http.HttpOptions;
036import org.jdrupes.httpcodec.protocols.http.HttpResponse;
037import org.jdrupes.httpcodec.protocols.http.client.HttpRequestEncoder;
038import org.jdrupes.httpcodec.protocols.http.client.HttpResponseDecoder;
039import org.jdrupes.httpcodec.protocols.websocket.WsCloseFrame;
040import org.jdrupes.httpcodec.protocols.websocket.WsMessageHeader;
041import org.jdrupes.httpcodec.types.Converters;
042import org.jgrapes.core.Channel;
043import org.jgrapes.core.ClassChannel;
044import org.jgrapes.core.Component;
045import org.jgrapes.core.Components;
046import org.jgrapes.core.Components.PoolingIndex;
047import org.jgrapes.core.EventPipeline;
048import org.jgrapes.core.annotation.Handler;
049import org.jgrapes.core.annotation.HandlerDefinition.ChannelReplacements;
050import org.jgrapes.http.events.HostUnresolved;
051import org.jgrapes.http.events.HttpConnected;
052import org.jgrapes.http.events.Request;
053import org.jgrapes.http.events.Response;
054import org.jgrapes.http.events.WebSocketClose;
055import org.jgrapes.io.IOSubchannel.DefaultIOSubchannel;
056import org.jgrapes.io.events.Close;
057import org.jgrapes.io.events.Closed;
058import org.jgrapes.io.events.IOError;
059import org.jgrapes.io.events.Input;
060import org.jgrapes.io.events.OpenSocketConnection;
061import org.jgrapes.io.events.Output;
062import org.jgrapes.io.util.ManagedBuffer;
063import org.jgrapes.io.util.ManagedBufferPool;
064import org.jgrapes.net.SocketIOChannel;
065import org.jgrapes.net.events.ClientConnected;
066
067/**
068 * A converter component that receives and sends web application
069 * layer messages and byte buffers on associated network channels.
070 */
071@SuppressWarnings({ "PMD.CouplingBetweenObjects" })
072public class HttpConnector extends Component {
073
074    private int applicationBufferSize = -1;
075    private final Channel netMainChannel;
076    private final Channel netSecureChannel;
077    private final PoolingIndex<SocketAddress, SocketIOChannel> pooled
078        = new PoolingIndex<>();
079    private HttpOptions httpOptions;
080
081    /**
082     * Denotes the network channel in handler annotations.
083     */
084    private static final class NetworkChannel extends ClassChannel {
085    }
086
087    /**
088     * Create a new connector that uses the {@code networkChannel} for network
089     * level I/O.
090     * 
091     * @param appChannel
092     *            this component's channel
093     * @param networkChannel
094     *            the channel for network level I/O
095     * @param secureChannel
096     *            the channel for secure network level I/O
097     */
098    public HttpConnector(Channel appChannel, Channel networkChannel,
099            Channel secureChannel) {
100        super(appChannel, ChannelReplacements.create()
101            .add(NetworkChannel.class, networkChannel, secureChannel));
102        this.netMainChannel = networkChannel;
103        this.netSecureChannel = secureChannel;
104    }
105
106    /**
107     * Create a new connector that uses the {@code networkChannel} for network
108     * level I/O.
109     * 
110     * @param appChannel
111     *            this component's channel
112     * @param networkChannel
113     *            the channel for network level I/O
114     */
115    public HttpConnector(Channel appChannel, Channel networkChannel) {
116        super(appChannel, ChannelReplacements.create()
117            .add(NetworkChannel.class, networkChannel));
118        this.netMainChannel = networkChannel;
119        this.netSecureChannel = null;
120    }
121
122    /**
123     * Sets the [HttpOptions] to use.
124     *
125     * @param options the options
126     * @return the http connector for easy chaining
127     */
128    public HttpConnector setHttpOptions(HttpOptions options) {
129        this.httpOptions = options;
130        return this;
131    }
132
133    /**
134     * Sets the size of the buffers used for {@link Input} events
135     * on the application channel. Defaults to the upstream buffer size
136     * minus 512 (estimate for added protocol overhead).
137     * 
138     * @param applicationBufferSize the size to set
139     * @return the http connector for easy chaining
140     */
141    public HttpConnector setApplicationBufferSize(int applicationBufferSize) {
142        this.applicationBufferSize = applicationBufferSize;
143        return this;
144    }
145
146    /**
147     * Returns the size of the application side (receive) buffers.
148     * 
149     * @return the value or -1 if not set
150     */
151    public int applicationBufferSize() {
152        return applicationBufferSize;
153    }
154
155    /**
156     * Starts the processing of a request from the application layer.
157     * When a network connection has been established, the application
158     * layer will be informed by a {@link HttpConnected} event, fired
159     * on a subchannel that is created for the processing of this
160     * request.
161     *
162     * @param event the request
163     * @throws InterruptedException if processing is interrupted
164     * @throws IOException Signals that an I/O exception has occurred.
165     */
166    @Handler
167    public void onRequest(Request.Out event)
168            throws InterruptedException, IOException {
169        new WebAppMsgChannel(event);
170    }
171
172    /**
173     * Handles output from the application. This may be the payload
174     * of e.g. a POST or data to be transferes on a websocket connection.
175     *
176     * @param event the event
177     * @param appChannel the application layer channel
178     * @throws InterruptedException the interrupted exception
179     */
180    @Handler
181    @SuppressWarnings({ "PMD.CompareObjectsWithEquals",
182        "PMD.AvoidDuplicateLiterals" })
183    public void onOutput(Output<?> event, WebAppMsgChannel appChannel)
184            throws InterruptedException {
185        if (appChannel.httpConnector() == this) {
186            appChannel.handleAppOutput(event);
187        }
188    }
189
190    /**
191     * Called when the network connection is established. Triggers the
192     * further processing of the initial request.
193     *
194     * @param event the event
195     * @param netConnChannel the network layer channel
196     * @throws InterruptedException if the execution is interrupted
197     * @throws IOException Signals that an I/O exception has occurred.
198     */
199    @Handler(channels = NetworkChannel.class)
200    public void onConnected(ClientConnected event,
201            SocketIOChannel netConnChannel)
202            throws InterruptedException, IOException {
203        // Check if this is a response to our request
204        @SuppressWarnings("PMD.CompareObjectsWithEquals")
205        var appChannel = event.openEvent().associated(WebAppMsgChannel.class)
206            .filter(c -> c.httpConnector() == this);
207        if (appChannel.isPresent()) {
208            appChannel.get().connected(netConnChannel);
209        }
210    }
211
212    /**
213     * Handles I/O error events from the network layer.
214     *
215     * @param event the event
216     * @throws IOException Signals that an I/O exception has occurred.
217     */
218    @Handler(channels = NetworkChannel.class)
219    @SuppressWarnings("PMD.CompareObjectsWithEquals")
220    public void onIoError(IOError event) throws IOException {
221        for (Channel channel : event.channels()) {
222            if (channel instanceof SocketIOChannel netConnChannel) {
223                // Error while using established network connection
224                Optional<WebAppMsgChannel> appChannel
225                    = netConnChannel.associated(WebAppMsgChannel.class)
226                        .filter(c -> c.httpConnector() == this);
227                if (appChannel.isPresent()) {
228                    // Error while using a network connection
229                    appChannel.get().handleIoError(event, netConnChannel);
230                    continue;
231                }
232                // Just in case...
233                pooled.remove(netConnChannel.remoteAddress(), netConnChannel);
234                continue;
235            }
236
237            // Error while trying to establish the network connection
238            if (event.event() instanceof OpenSocketConnection connEvent) {
239                connEvent.associated(WebAppMsgChannel.class)
240                    .filter(c -> c.httpConnector() == this).ifPresent(c -> {
241                        c.openError(event);
242                    });
243            }
244        }
245    }
246
247    /**
248     * Processes any input from the network layer.
249     *
250     * @param event the event
251     * @param netConnChannel the network layer channel
252     * @throws InterruptedException if the thread is interrupted
253     * @throws ProtocolException if the protocol is violated
254     */
255    @Handler(channels = NetworkChannel.class)
256    @SuppressWarnings("PMD.CompareObjectsWithEquals")
257    public void onInput(Input<ByteBuffer> event, SocketIOChannel netConnChannel)
258            throws InterruptedException, ProtocolException {
259        Optional<WebAppMsgChannel> appChannel
260            = netConnChannel.associated(WebAppMsgChannel.class)
261                .filter(c -> c.httpConnector() == this);
262        if (appChannel.isPresent()) {
263            appChannel.get().handleNetInput(event, netConnChannel);
264        }
265    }
266
267    /**
268     * Called when the network connection is closed. 
269     *
270     * @param event the event
271     * @param netConnChannel the net conn channel
272     */
273    @Handler(channels = NetworkChannel.class)
274    @SuppressWarnings("PMD.CompareObjectsWithEquals")
275    public void onClosed(Closed<?> event, SocketIOChannel netConnChannel) {
276        netConnChannel.associated(WebAppMsgChannel.class)
277            .filter(c -> c.httpConnector() == this).ifPresent(
278                appChannel -> appChannel.handleClosed(event));
279        pooled.remove(netConnChannel.remoteAddress(), netConnChannel);
280    }
281
282    /**
283     * Handles a close event from the application channel. Such an
284     * event may only be fired if the connection has been upgraded
285     * to a websocket connection.
286     *
287     * @param event the event
288     * @param appChannel the application channel
289     */
290    @Handler
291    @SuppressWarnings("PMD.CompareObjectsWithEquals")
292    public void onClose(Close event, WebAppMsgChannel appChannel) {
293        if (appChannel.httpConnector() == this) {
294            appChannel.handleClose(event);
295        }
296    }
297
298    /**
299     * An application layer channel.
300     */
301    @SuppressWarnings("PMD.PublicMemberInNonPublicType")
302    private class WebAppMsgChannel extends DefaultIOSubchannel {
303        // Starts as ClientEngine<HttpRequest,HttpResponse> but may change
304        private final ClientEngine<?, ?> engine
305            = new ClientEngine<>(new HttpRequestEncoder(),
306                new HttpResponseDecoder());
307        private final InetSocketAddress serverAddress;
308        private final Request.Out request;
309        private ManagedBuffer<ByteBuffer> outBuffer;
310        private ManagedBufferPool<ManagedBuffer<ByteBuffer>,
311                ByteBuffer> byteBufferPool;
312        private ManagedBufferPool<ManagedBuffer<CharBuffer>,
313                CharBuffer> charBufferPool;
314        private ManagedBufferPool<?, ?> currentPool;
315        private SocketIOChannel netConnChannel;
316        private final EventPipeline downPipeline;
317        private WsMessageHeader currentWsMessage;
318
319        /**
320         * Instantiates a new channel.
321         *
322         * @param event the event
323         * @param netChannel the net channel
324         * @throws InterruptedException 
325         * @throws IOException 
326         */
327        @SuppressWarnings({ "PMD.PublicMemberInNonPublicType",
328            "PMD.ConstructorCallsOverridableMethod",
329            "PMD.AvoidLiteralsInIfCondition" })
330        public WebAppMsgChannel(Request.Out event)
331                throws InterruptedException, IOException {
332            super(channel(), newEventPipeline());
333            engine.responseDecoder().options(httpOptions);
334
335            // Downstream pipeline, needed even if connection fails
336            downPipeline = newEventPipeline();
337
338            // Extract request data and check host
339            request = event;
340            var uri = request.requestUri();
341            var port = uri.getPort();
342            if (port == -1) {
343                if ("https".equalsIgnoreCase(uri.getScheme())) {
344                    port = 443;
345                } else if ("http".equalsIgnoreCase(uri.getScheme())) {
346                    port = 80;
347                }
348            }
349            serverAddress = new InetSocketAddress(uri.getHost(), port);
350            if (serverAddress.isUnresolved()) {
351                downPipeline.fire(new HostUnresolved(event,
352                    "Host cannot be resolved."), this);
353                return;
354            }
355
356            // Re-use network connection, if possible
357            SocketIOChannel recycled = pooled.poll(serverAddress);
358            if (recycled != null) {
359                connected(recycled);
360                return;
361            }
362
363            // Fire on network channel (targeting the network connector)
364            // as a follow up event (using the current pipeline).
365            @SuppressWarnings("PMD.LiteralsFirstInComparisons")
366            var useSecure = uri.getScheme().equalsIgnoreCase("https")
367                && netSecureChannel != null;
368            fire(new OpenSocketConnection(serverAddress)
369                .setAssociated(WebAppMsgChannel.class, this),
370                useSecure ? netSecureChannel : netMainChannel);
371        }
372
373        private HttpConnector httpConnector() {
374            return HttpConnector.this;
375        }
376
377        /**
378         * Error in response to trying to open a new TCP connection.
379         *
380         * @param event the event
381         */
382        public void openError(IOError event) {
383            // Already removed from connecting by caller, simply forward.
384            downPipeline.fire(IOError.duplicate(event), this);
385        }
386
387        /**
388         * Error from established TCP connection.
389         *
390         * @param event the event
391         * @param netConnChannel the network channel
392         */
393        public void handleIoError(IOError event,
394                SocketIOChannel netConnChannel) {
395            downPipeline.fire(IOError.duplicate(event), this);
396        }
397
398        /**
399         * Sets the network connection channel for this application channel.
400         *
401         * @param netConnChannel the net conn channel
402         * @throws InterruptedException the interrupted exception
403         * @throws IOException Signals that an I/O exception has occurred.
404         */
405        @SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
406        public final void connected(SocketIOChannel netConnChannel)
407                throws InterruptedException, IOException {
408            // Associate the network channel with this application channel
409            this.netConnChannel = netConnChannel;
410            netConnChannel.setAssociated(WebAppMsgChannel.class, this);
411            request.connectedCallback().ifPresent(
412                consumer -> consumer.accept(request, netConnChannel));
413
414            // Estimate "good" application buffer size
415            int bufferSize = applicationBufferSize;
416            if (bufferSize <= 0) {
417                bufferSize = netConnChannel.byteBufferPool().bufferSize() - 512;
418                if (bufferSize < 4096) {
419                    bufferSize = 4096;
420                }
421            }
422            String channelName = Components.objectName(HttpConnector.this)
423                + "." + Components.objectName(this);
424            byteBufferPool().setName(channelName + ".upstream.byteBuffers");
425            charBufferPool().setName(channelName + ".upstream.charBuffers");
426            // Allocate downstream buffer pools. Note that decoding WebSocket
427            // network packets may result in several WS frames that are each
428            // delivered in independent events. Therefore provide some
429            // additional buffers.
430            final int bufSize = bufferSize;
431            byteBufferPool = new ManagedBufferPool<>(ManagedBuffer::new,
432                () -> {
433                    return ByteBuffer.allocate(bufSize);
434                }, 2, 100)
435                    .setName(channelName + ".downstream.byteBuffers");
436            charBufferPool = new ManagedBufferPool<>(ManagedBuffer::new,
437                () -> {
438                    return CharBuffer.allocate(bufSize);
439                }, 2, 100)
440                    .setName(channelName + ".downstream.charBuffers");
441
442            sendMessageUpstream(request.httpRequest(), netConnChannel);
443
444            // Forward Connected event downstream to e.g. start preparation
445            // of output events for payload data.
446            downPipeline.fire(new HttpConnected(request,
447                netConnChannel.localAddress(), netConnChannel.remoteAddress()),
448                this);
449        }
450
451        @SuppressWarnings({ "PMD.CognitiveComplexity",
452            "PMD.AvoidDuplicateLiterals" })
453        private void sendMessageUpstream(MessageHeader message,
454                SocketIOChannel netConnChannel) {
455            // Now send request as if it came from downstream (to
456            // avoid confusion with output events that may be
457            // generated in parallel, see below).
458            responsePipeline().submit("SynchronizedResponse",
459                new Callable<Void>() {
460
461                    @Override
462                    @SuppressWarnings({
463                        "PMD.AvoidBranchingStatementAsLastInLoop",
464                        "PMD.AvoidInstantiatingObjectsInLoops" })
465                    public Void call() throws InterruptedException {
466                        @SuppressWarnings("unchecked")
467                        ClientEngine<MessageHeader, MessageHeader> untypedEngine
468                            = (ClientEngine<MessageHeader,
469                                    MessageHeader>) engine;
470                        untypedEngine.encode(message);
471                        boolean hasBody = message.hasPayload();
472                        while (true) {
473                            outBuffer
474                                = netConnChannel.byteBufferPool().acquire();
475                            Codec.Result result
476                                = engine.encode(Codec.EMPTY_IN,
477                                    outBuffer.backingBuffer(), !hasBody);
478                            if (result.isOverflow()) {
479                                netConnChannel
480                                    .respond(Output.fromSink(outBuffer, false));
481                                continue;
482                            }
483                            if (hasBody) {
484                                // Keep buffer with incomplete request to be
485                                // further
486                                // filled by subsequent Output events
487                                break;
488                            }
489                            // Request is completely encoded
490                            if (outBuffer.position() > 0) {
491                                netConnChannel
492                                    .respond(Output.fromSink(outBuffer, true));
493                            } else {
494                                outBuffer.unlockBuffer();
495                            }
496                            outBuffer = null;
497                            if (result.closeConnection()) {
498                                netConnChannel.respond(new Close());
499                            }
500                            break;
501                        }
502                        return null;
503                    }
504                });
505        }
506
507        @SuppressWarnings({ "PMD.CommentRequired", "PMD.CyclomaticComplexity",
508            "PMD.NPathComplexity", "PMD.AvoidInstantiatingObjectsInLoops",
509            "PMD.AvoidDuplicateLiterals", "PMD.CognitiveComplexity" })
510        public void handleAppOutput(Output<?> event)
511                throws InterruptedException {
512            Buffer eventData = event.data();
513            Buffer input;
514            if (eventData instanceof ByteBuffer) {
515                input = ((ByteBuffer) eventData).duplicate();
516            } else if (eventData instanceof CharBuffer) {
517                input = ((CharBuffer) eventData).duplicate();
518            } else {
519                return;
520            }
521            if (engine.switchedTo().equals(Optional.of("websocket"))
522                && currentWsMessage == null) {
523                // When switched to WebSockets, we only have Input and Output
524                // events. Add header automatically.
525                @SuppressWarnings("unchecked")
526                ClientEngine<MessageHeader, ?> wsEngine
527                    = (ClientEngine<MessageHeader, ?>) engine;
528                currentWsMessage = new WsMessageHeader(
529                    event.buffer().backingBuffer() instanceof CharBuffer,
530                    true);
531                wsEngine.encode(currentWsMessage);
532            }
533            while (input.hasRemaining() || event.isEndOfRecord()) {
534                if (outBuffer == null) {
535                    outBuffer = netConnChannel.byteBufferPool().acquire();
536                }
537                Codec.Result result = engine.encode(input,
538                    outBuffer.backingBuffer(), event.isEndOfRecord());
539                if (result.isOverflow()) {
540                    netConnChannel.respond(Output.fromSink(outBuffer, false));
541                    outBuffer = netConnChannel.byteBufferPool().acquire();
542                    continue;
543                }
544                if (event.isEndOfRecord() || result.closeConnection()) {
545                    if (outBuffer.position() > 0) {
546                        netConnChannel
547                            .respond(Output.fromSink(outBuffer, true));
548                    } else {
549                        outBuffer.unlockBuffer();
550                    }
551                    outBuffer = null;
552                    if (result.closeConnection()) {
553                        netConnChannel.respond(new Close());
554                    }
555                    break;
556                }
557            }
558            if (engine.switchedTo().equals(Optional.of("websocket"))
559                && event.isEndOfRecord()) {
560                currentWsMessage = null;
561            }
562        }
563
564        @SuppressWarnings({ "PMD.CommentRequired", "PMD.CognitiveComplexity" })
565        public void handleNetInput(Input<ByteBuffer> event,
566                SocketIOChannel netConnChannel)
567                throws InterruptedException, ProtocolException {
568            // Send the data from the event through the decoder.
569            ByteBuffer inData = event.data();
570            // Don't unnecessary allocate a buffer, may be header only message
571            ManagedBuffer<?> bodyData = null;
572            boolean wasOverflow = false;
573            Decoder.Result<?> result;
574            while (inData.hasRemaining()) {
575                if (wasOverflow) {
576                    // Message has (more) body
577                    bodyData = currentPool.acquire();
578                }
579                result = engine.decode(inData,
580                    bodyData == null ? null : bodyData.backingBuffer(),
581                    event.isEndOfRecord());
582                if (result.response().isPresent()) {
583                    sendMessageUpstream(result.response().get(),
584                        netConnChannel);
585                    if (result.isResponseOnly()) {
586                        maybeReleaseConnection(result);
587                        continue;
588                    }
589                }
590                if (result.isHeaderCompleted()) {
591                    MessageHeader header
592                        = engine.responseDecoder().header().get();
593                    if (!handleResponseHeader(header)) {
594                        maybeReleaseConnection(result);
595                        break;
596                    }
597                }
598                if (bodyData != null) {
599                    if (bodyData.position() > 0) {
600                        boolean eor
601                            = !result.isOverflow() && !result.isUnderflow();
602                        downPipeline.fire(Input.fromSink(bodyData, eor), this);
603                    } else {
604                        bodyData.unlockBuffer();
605                    }
606                    bodyData = null;
607                }
608                maybeReleaseConnection(result);
609                wasOverflow = result.isOverflow();
610            }
611        }
612
613        @SuppressWarnings({ "PMD.CognitiveComplexity",
614            "PMD.AvoidDeeplyNestedIfStmts" })
615        private boolean handleResponseHeader(MessageHeader response) {
616            if (response instanceof HttpResponse) {
617                HttpResponse httpResponse = (HttpResponse) response;
618                if (httpResponse.hasPayload()) {
619                    if (httpResponse.findValue(
620                        HttpField.CONTENT_TYPE, Converters.MEDIA_TYPE)
621                        .map(type -> "text"
622                            .equalsIgnoreCase(type.value().topLevelType()))
623                        .orElse(false)) {
624                        currentPool = charBufferPool;
625                    } else {
626                        currentPool = byteBufferPool;
627                    }
628                }
629                downPipeline.fire(new Response(httpResponse), this);
630            } else if (response instanceof WsMessageHeader) {
631                WsMessageHeader wsMessage = (WsMessageHeader) response;
632                if (wsMessage.hasPayload()) {
633                    if (wsMessage.isTextMode()) {
634                        currentPool = charBufferPool;
635                    } else {
636                        currentPool = byteBufferPool;
637                    }
638                }
639            } else if (response instanceof WsCloseFrame) {
640                downPipeline.fire(
641                    new WebSocketClose((WsCloseFrame) response, this));
642            }
643            return true;
644        }
645
646        private void maybeReleaseConnection(Decoder.Result<?> result) {
647            if (result.isOverflow() || result.isUnderflow()) {
648                // Data remains to be processed
649                return;
650            }
651            MessageHeader header
652                = engine.responseDecoder().header().get();
653            // Don't release if something follows
654            if (header instanceof HttpResponse
655                && ((HttpResponse) header).statusCode() % 100 == 1) {
656                return;
657            }
658            if (engine.switchedTo().equals(Optional.of("websocket"))) {
659                if (!result.closeConnection()) {
660                    return;
661                }
662                // Is web socket close, inform application layer
663                downPipeline.fire(new Closed<>(), this);
664            }
665            netConnChannel.setAssociated(WebAppMsgChannel.class, null);
666            if (!result.closeConnection()) {
667                // May be reused
668                pooled.add(serverAddress, netConnChannel);
669            }
670            netConnChannel = null;
671        }
672
673        @SuppressWarnings("PMD.CommentRequired")
674        public void handleClose(Close event) {
675            if (engine.switchedTo().equals(Optional.of("websocket"))) {
676                sendMessageUpstream(new WsCloseFrame(null, null),
677                    netConnChannel);
678            }
679        }
680
681        @SuppressWarnings("PMD.CommentRequired")
682        public void handleClosed(Closed<?> event) {
683            if (engine.switchedTo().equals(Optional.of("websocket"))) {
684                downPipeline.fire(new Closed<>(), this);
685            }
686        }
687
688    }
689
690}