001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2016-2018 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.net;
020
021import java.io.IOException;
022import java.lang.management.ManagementFactory;
023import java.lang.ref.WeakReference;
024import java.net.InetSocketAddress;
025import java.net.SocketAddress;
026import java.net.StandardProtocolFamily;
027import java.net.UnixDomainSocketAddress;
028import java.nio.channels.SelectionKey;
029import java.nio.channels.ServerSocketChannel;
030import java.nio.channels.SocketChannel;
031import java.util.ArrayList;
032import java.util.Collections;
033import java.util.Comparator;
034import java.util.HashSet;
035import java.util.IntSummaryStatistics;
036import java.util.List;
037import java.util.Optional;
038import java.util.Set;
039import java.util.SortedMap;
040import java.util.TreeMap;
041import java.util.stream.Collectors;
042import javax.management.InstanceAlreadyExistsException;
043import javax.management.MBeanRegistrationException;
044import javax.management.MBeanServer;
045import javax.management.MalformedObjectNameException;
046import javax.management.NotCompliantMBeanException;
047import javax.management.ObjectName;
048import org.jgrapes.core.Channel;
049import org.jgrapes.core.Components;
050import org.jgrapes.core.Event;
051import org.jgrapes.core.Manager;
052import org.jgrapes.core.Self;
053import org.jgrapes.core.Subchannel;
054import org.jgrapes.core.annotation.Handler;
055import org.jgrapes.core.events.Error;
056import org.jgrapes.core.events.Start;
057import org.jgrapes.core.events.Stop;
058import org.jgrapes.core.internal.ComponentVertex;
059import org.jgrapes.io.NioHandler;
060import org.jgrapes.io.events.Close;
061import org.jgrapes.io.events.Closed;
062import org.jgrapes.io.events.IOError;
063import org.jgrapes.io.events.Input;
064import org.jgrapes.io.events.NioRegistration;
065import org.jgrapes.io.events.NioRegistration.Registration;
066import org.jgrapes.io.events.Opening;
067import org.jgrapes.io.events.Output;
068import org.jgrapes.io.events.Purge;
069import org.jgrapes.io.util.AvailabilityListener;
070import org.jgrapes.io.util.LinkedIOSubchannel;
071import org.jgrapes.io.util.PermitsPool;
072import org.jgrapes.net.events.Accepted;
073import org.jgrapes.net.events.Ready;
074import org.jgrapes.util.events.ConfigurationUpdate;
075
076/**
077 * Provides a socket server. The server binds to the given address. If the
078 * address is {@code null}, address and port are automatically assigned.
079 * The port may be overwritten by a configuration event
080 * (see {@link #onConfigurationUpdate(ConfigurationUpdate)}).
081 * 
082 * For each established connection, the server creates a new
083 * {@link LinkedIOSubchannel}. The servers basic operation is to
084 * fire {@link Input} (and {@link Closed}) events on the
085 * appropriate subchannel in response to data received from the
086 * network and to handle {@link Output} (and {@link Close}) events 
087 * on the subchannel and forward the information to the network
088 * connection.
089 * 
090 * The server supports limiting the number of concurrent connections
091 * with a {@link PermitsPool}. If such a pool is set as connection
092 * limiter (see {@link #setConnectionLimiter(PermitsPool)}), a
093 * permit is acquired for each new connection attempt. If no more
094 * permits are available, the server sends a {@link Purge} event on
095 * each channel that is purgeable for at least the time span
096 * set with {@link #setMinimalPurgeableTime(long)}. Purgeability 
097 * is derived from the end of record flag of {@link Output} events
098 * (see {@link #onOutput(Output, SocketChannelImpl)}. When using this feature, 
099 * make sure that connections are either short lived or the application
100 * level components support the {@link Purge} event. Else, it may become
101 * impossible to establish new connections.
102 */
103@SuppressWarnings({ "PMD.ExcessiveImports", "PMD.EmptyCatchBlock",
104    "PMD.CouplingBetweenObjects", "PMD.AvoidSynchronizedStatement" })
105public class SocketServer extends SocketConnectionManager
106        implements NioHandler {
107
108    private SocketAddress serverAddress;
109    private ServerSocketChannel serverSocketChannel;
110    private boolean closing;
111    private int backlog;
112    private PermitsPool connLimiter;
113    private Registration registration;
114    private Thread purger;
115    private long minimumPurgeableTime;
116
117    /**
118     * The purger thread.
119     */
120    @SuppressWarnings({ "PMD.PublicMemberInNonPublicType",
121        "PMD.AvoidSynchronizedStatement" })
122    private class Purger extends Thread implements AvailabilityListener {
123
124        private boolean permitsAvailable = true;
125
126        /**
127         * Instantiates a new purger.
128         */
129        public Purger() {
130            setName(Components.simpleObjectName(this));
131        }
132
133        @Override
134        public void availabilityChanged(PermitsPool pool, boolean available) {
135            if (registration == null) {
136                return;
137            }
138            synchronized (this) {
139                permitsAvailable = available;
140                registration.updateInterested(
141                    permitsAvailable ? SelectionKey.OP_ACCEPT : 0);
142                if (!permitsAvailable) {
143                    this.notifyAll();
144                }
145            }
146        }
147
148        @Override
149        @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops",
150            "PMD.CognitiveComplexity" })
151        public void run() {
152            if (connLimiter == null) {
153                return;
154            }
155            try {
156                connLimiter.addListener(this);
157                while (serverSocketChannel.isOpen()) {
158                    synchronized (this) {
159                        while (permitsAvailable) {
160                            wait();
161                        }
162                    }
163                    // Copy to avoid ConcurrentModificationException
164                    List<SocketChannelImpl> candidates;
165                    synchronized (channels) {
166                        candidates = new ArrayList<>(channels);
167                    }
168                    long purgeableSince
169                        = System.currentTimeMillis() - minimumPurgeableTime;
170                    candidates = candidates.stream()
171                        .filter(channel -> channel.isPurgeable()
172                            && channel.purgeableSince() < purgeableSince)
173                        .sorted(new Comparator<>() {
174                            @Override
175                            @SuppressWarnings("PMD.ShortVariable")
176                            public int compare(SocketChannelImpl c1,
177                                    SocketChannelImpl c2) {
178                                if (c1.purgeableSince() < c2
179                                    .purgeableSince()) {
180                                    return 1;
181                                }
182                                if (c1.purgeableSince() > c2
183                                    .purgeableSince()) {
184                                    return -1;
185                                }
186                                return 0;
187                            }
188                        })
189                        .collect(Collectors.toList());
190                    for (SocketChannelImpl channel : candidates) {
191                        // Sorting may have taken time...
192                        if (!channel.isPurgeable()) {
193                            continue;
194                        }
195                        channel.downPipeline().fire(new Purge(), channel);
196                        // Continue only as long as necessary
197                        if (permitsAvailable) {
198                            break;
199                        }
200                    }
201                    sleep(1000);
202                }
203            } catch (InterruptedException e) {
204                // Fall through
205            } finally {
206                connLimiter.removeListener(this);
207            }
208        }
209
210    }
211
212    /**
213     * Creates a new server, using itself as component channel. 
214     */
215    public SocketServer() {
216        this(SELF);
217    }
218
219    /**
220     * Creates a new server using the given channel.
221     * 
222     * @param componentChannel the component's channel
223     */
224    public SocketServer(Channel componentChannel) {
225        super(componentChannel);
226    }
227
228    /**
229     * Sets the address to bind to. If none is set, the address and port
230     * are assigned automatically.
231     * 
232     * @param serverAddress the address to bind to
233     * @return the socket server for easy chaining
234     */
235    public SocketServer setServerAddress(SocketAddress serverAddress) {
236        this.serverAddress = serverAddress;
237        return this;
238    }
239
240    @Override
241    public SocketServer setBufferSize(int size) {
242        super.setBufferSize(size);
243        return this;
244    }
245
246    /**
247     * The component can be configured with events that include
248     * a path (see @link {@link ConfigurationUpdate#paths()})
249     * that matches this components path (see {@link Manager#componentPath()}).
250     * 
251     * The following properties are recognized:
252     * 
253     * `hostname`
254     * : If given, is used as first parameter for 
255     *   {@link InetSocketAddress#InetSocketAddress(String, int)}.
256     * 
257     * `port`
258     * : If given, is used as parameter for 
259     *   {@link InetSocketAddress#InetSocketAddress(String, int)} 
260     *   or {@link InetSocketAddress#InetSocketAddress(int)}, 
261     *   depending on whether a host name is specified. Defaults to "0".
262     *   
263     * `backlog`
264     * : See {@link #setBacklog(int)}.
265     * 
266     * `bufferSize`
267     * : See {@link #setBufferSize(int)}.
268     * 
269     * `maxConnections`
270     * : Calls {@link #setConnectionLimiter} with a
271     *   {@link PermitsPool} of the specified size.
272     * 
273     * `minimalPurgeableTime`
274     * : See {@link #setMinimalPurgeableTime(long)}.
275     * 
276     * @param event the event
277     */
278    @Handler
279    public void onConfigurationUpdate(ConfigurationUpdate event) {
280        event.values(componentPath()).ifPresent(values -> {
281            String hostname = values.get("hostname");
282            if (hostname != null) {
283                setServerAddress(new InetSocketAddress(hostname,
284                    Integer.parseInt(values.getOrDefault("port", "0"))));
285            } else if (values.containsKey("port")) {
286                setServerAddress(new InetSocketAddress(
287                    Integer.parseInt(values.get("port"))));
288            }
289            Optional.ofNullable(values.get("backlog")).ifPresent(
290                value -> setBacklog(Integer.parseInt(value)));
291            Optional.ofNullable(values.get("bufferSize")).ifPresent(
292                value -> setBufferSize(Integer.parseInt(value)));
293            Optional.ofNullable(values.get("maxConnections"))
294                .map(Integer::parseInt).map(PermitsPool::new)
295                .ifPresent(this::setConnectionLimiter);
296            Optional.ofNullable(values.get("minimalPurgeableTime"))
297                .map(Long::parseLong).ifPresent(this::setMinimalPurgeableTime);
298        });
299    }
300
301    /**
302     * Returns the server address. Before starting, the address is the
303     * address set with {@link #setServerAddress(InetSocketAddress)}. After
304     * starting the address is obtained from the created socket.  
305     * 
306     * @return the serverAddress
307     */
308    public SocketAddress serverAddress() {
309        try {
310            return serverSocketChannel == null ? serverAddress
311                : serverSocketChannel.getLocalAddress();
312        } catch (IOException e) {
313            return serverAddress;
314        }
315    }
316
317    /**
318     * Sets the backlog size.
319     * 
320     * @param backlog the backlog to set
321     * @return the socket server for easy chaining
322     */
323    public SocketServer setBacklog(int backlog) {
324        this.backlog = backlog;
325        return this;
326    }
327
328    /**
329     * Return the configured backlog size.
330     *
331     * @return the backlog
332     */
333    public int backlog() {
334        return backlog;
335    }
336
337    /**
338     * Sets a permit "pool". A new connection is created only if a permit
339     * can be obtained from the pool. 
340     * 
341     * A connection limiter must be set before starting the component.
342     * 
343     * @param connectionLimiter the connection pool to set
344     * @return the socket server for easy chaining
345     */
346    public SocketServer setConnectionLimiter(PermitsPool connectionLimiter) {
347        this.connLimiter = connectionLimiter;
348        return this;
349    }
350
351    /**
352     * Returns the connection limiter.
353     *
354     * @return the connection Limiter
355     */
356    public PermitsPool getConnectionLimiter() {
357        return connLimiter;
358    }
359
360    /**
361     * Sets a minimal time that a connection must be purgeable (idle)
362     * before it may be purged.
363     *
364     * @param millis the millis
365     * @return the socket server
366     */
367    public SocketServer setMinimalPurgeableTime(long millis) {
368        this.minimumPurgeableTime = millis;
369        return this;
370    }
371
372    /**
373     * Gets the minimal purgeable time.
374     *
375     * @return the minimal purgeable time
376     */
377    public long getMinimalPurgeableTime() {
378        return minimumPurgeableTime;
379    }
380
381    /**
382     * Starts the server.
383     * 
384     * @param event the start event
385     * @throws IOException if an I/O exception occurred
386     */
387    @Handler
388    public void onStart(Start event) throws IOException {
389        closing = false;
390        if (serverAddress instanceof UnixDomainSocketAddress) {
391            serverSocketChannel
392                = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
393        } else {
394            serverSocketChannel = ServerSocketChannel.open();
395        }
396        serverSocketChannel.bind(serverAddress, backlog);
397        MBeanView.addServer(this);
398        fire(new NioRegistration(this, serverSocketChannel,
399            SelectionKey.OP_ACCEPT, this), BROADCAST);
400    }
401
402    /**
403     * Handles the successful channel registration.
404     *
405     * @param event the event
406     * @throws InterruptedException the interrupted exception
407     * @throws IOException Signals that an I/O exception has occurred.
408     */
409    @Handler(channels = Self.class)
410    @SuppressWarnings("PMD.CompareObjectsWithEquals")
411    public void onRegistered(NioRegistration.Completed event)
412            throws InterruptedException, IOException {
413        NioHandler handler = event.event().handler();
414        if (handler == this) {
415            if (event.event().get() == null) {
416                fire(new Error(event,
417                    "Registration failed, no NioDispatcher?"));
418                return;
419            }
420            registration = event.event().get();
421            purger = (Components.useVirtualThreads() ? Thread.ofVirtual()
422                : Thread.ofPlatform()).start(new Purger());
423            fire(new Ready(serverSocketChannel.getLocalAddress()));
424            return;
425        }
426        if (handler instanceof SocketChannelImpl channel
427            && channels.contains(channel)) {
428            var accepted = new Accepted(channel.nioChannel().getLocalAddress(),
429                channel.nioChannel().getRemoteAddress(), false,
430                Collections.emptyList());
431            var registration = event.event().get();
432            // (1) Opening, (2) Accepted, (3) process input
433            channel.downPipeline().fire(Event.onCompletion(new Opening<Void>(),
434                e -> {
435                    channel.downPipeline().fire(accepted, channel);
436                    channel.registrationComplete(registration);
437                }), channel);
438        }
439    }
440
441    /*
442     * (non-Javadoc)
443     * 
444     * @see org.jgrapes.io.NioSelectable#handleOps(int)
445     */
446    @Override
447    public void handleOps(int ops) {
448        if ((ops & SelectionKey.OP_ACCEPT) == 0 || closing) {
449            return;
450        }
451        synchronized (channels) {
452            if (connLimiter != null && !connLimiter.tryAcquire()) {
453                return;
454            }
455            try {
456                @SuppressWarnings("PMD.CloseResource")
457                SocketChannel socketChannel = serverSocketChannel.accept();
458                if (socketChannel == null) {
459                    // "False alarm"
460                    if (connLimiter != null) {
461                        connLimiter.release();
462                    }
463                    return;
464                }
465                new SocketChannelImpl(null, socketChannel);
466            } catch (IOException e) {
467                fire(new IOError(null, e));
468            }
469        }
470    }
471
472    @Override
473    protected boolean removeChannel(SocketChannelImpl channel) {
474        synchronized (channels) {
475            if (!channels.remove(channel)) {
476                // Closed already
477                return false;
478            }
479            // In case the server is shutting down
480            channels.notifyAll();
481        }
482        if (connLimiter != null) {
483            connLimiter.release();
484        }
485        return true;
486    }
487
488    /**
489     * Shuts down the server or one of the connections to the server.
490     *
491     * @param event the event
492     * @throws IOException if an I/O exception occurred
493     * @throws InterruptedException if the execution was interrupted
494     */
495    @Handler
496    public void onClose(Close event) throws IOException, InterruptedException {
497        boolean closeServer = false;
498        for (Channel channel : event.channels()) {
499            if (channels.contains(channel)) {
500                ((SocketChannelImpl) channel).close();
501                continue;
502            }
503            if (channel instanceof Subchannel) {
504                // Some subchannel that we're not interested in.
505                continue;
506            }
507            // Close event on "main" channel
508            closeServer = true;
509        }
510        if (!closeServer) {
511            // Only connection(s) were to be closed.
512            return;
513        }
514        if (!serverSocketChannel.isOpen()) {
515            // Closed already
516            fire(new Closed<>());
517            return;
518        }
519        synchronized (channels) {
520            closing = true;
521            // Copy to avoid concurrent modification exception
522            Set<SocketChannelImpl> conns = new HashSet<>(channels);
523            for (SocketChannelImpl conn : conns) {
524                conn.close();
525            }
526            while (!channels.isEmpty()) {
527                channels.wait();
528            }
529        }
530        serverSocketChannel.close();
531        purger.interrupt();
532        closing = false;
533        fire(new Closed<>());
534    }
535
536    /**
537     * Shuts down the server by firing a {@link Close} using the
538     * server as channel. Note that this automatically results
539     * in closing all open connections by the runtime system
540     * and thus in {@link Closed} events on all subchannels.
541     * 
542     * @param event the event
543     * @throws InterruptedException 
544     */
545    @Handler(priority = -1000)
546    public void onStop(Stop event) throws InterruptedException {
547        if (closing || !serverSocketChannel.isOpen()) {
548            return;
549        }
550        newEventPipeline().fire(new Close(), this).get();
551    }
552
553    /**
554     * The Interface of the SocketServer MXBean.
555     */
556    public interface SocketServerMXBean {
557
558        /**
559         * The Class ChannelInfo.
560         */
561        class ChannelInfo {
562
563            private final SocketChannelImpl channel;
564
565            /**
566             * Instantiates a new channel info.
567             *
568             * @param channel the channel
569             */
570            public ChannelInfo(SocketChannelImpl channel) {
571                this.channel = channel;
572            }
573
574            /**
575             * Checks if is purgeable.
576             *
577             * @return true, if is purgeable
578             */
579            public boolean isPurgeable() {
580                return channel.isPurgeable();
581            }
582
583            /**
584             * Gets the downstream pool.
585             *
586             * @return the downstream pool
587             */
588            public String getDownstreamPool() {
589                return channel.readBuffers().name();
590            }
591
592            /**
593             * Gets the upstream pool.
594             *
595             * @return the upstream pool
596             */
597            public String getUpstreamPool() {
598                return channel.byteBufferPool().name();
599            }
600        }
601
602        /**
603         * Gets the component path.
604         *
605         * @return the component path
606         */
607        String getComponentPath();
608
609        /**
610         * Gets the channel count.
611         *
612         * @return the channel count
613         */
614        int getChannelCount();
615
616        /**
617         * Gets the channels.
618         *
619         * @return the channels
620         */
621        SortedMap<String, ChannelInfo> getChannels();
622
623    }
624
625    /**
626     * The Class SocketServerInfo.
627     */
628    public static class SocketServerInfo implements SocketServerMXBean {
629
630        private static MBeanServer mbs
631            = ManagementFactory.getPlatformMBeanServer();
632
633        private ObjectName mbeanName;
634        private final WeakReference<SocketServer> serverRef;
635
636        /**
637         * Instantiates a new socket server info.
638         *
639         * @param server the server
640         */
641        @SuppressWarnings({ "PMD.EmptyCatchBlock",
642            "PMD.AvoidCatchingGenericException" })
643        public SocketServerInfo(SocketServer server) {
644            serverRef = new WeakReference<>(server);
645            try {
646                String endPoint = "";
647                if (server.serverAddress instanceof InetSocketAddress addr) {
648                    endPoint = " (" + addr.getHostName() + ":" + addr.getPort()
649                        + ")";
650                } else if (server.serverAddress instanceof UnixDomainSocketAddress addr) {
651                    endPoint = " (" + addr.getPath() + ")";
652                }
653                mbeanName = new ObjectName("org.jgrapes.io:type="
654                    + SocketServer.class.getSimpleName() + ",name="
655                    + ObjectName
656                        .quote(Components.objectName(server) + endPoint));
657            } catch (MalformedObjectNameException e) {
658                // Should not happen
659            }
660            try {
661                mbs.unregisterMBean(mbeanName);
662            } catch (Exception e) {
663                // Just in case, should not work
664            }
665            try {
666                mbs.registerMBean(this, mbeanName);
667            } catch (InstanceAlreadyExistsException | MBeanRegistrationException
668                    | NotCompliantMBeanException e) {
669                // Have to live with that
670            }
671        }
672
673        /**
674         * Server.
675         *
676         * @return the optional
677         */
678        @SuppressWarnings({ "PMD.AvoidCatchingGenericException",
679            "PMD.EmptyCatchBlock" })
680        public Optional<SocketServer> server() {
681            SocketServer server = serverRef.get();
682            if (server == null) {
683                try {
684                    mbs.unregisterMBean(mbeanName);
685                } catch (Exception e) {
686                    // Should work.
687                }
688            }
689            return Optional.ofNullable(server);
690        }
691
692        @Override
693        public String getComponentPath() {
694            return server()
695                .map(ComponentVertex::componentPath).orElse("<removed>");
696        }
697
698        @Override
699        public int getChannelCount() {
700            return server().map(server -> server.channels.size()).orElse(0);
701        }
702
703        @Override
704        @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
705        public SortedMap<String, ChannelInfo> getChannels() {
706            return server().map(server -> {
707                SortedMap<String, ChannelInfo> result = new TreeMap<>();
708                for (SocketChannelImpl channel : server.channels) {
709                    result.put(channel.nioChannel().socket()
710                        .getRemoteSocketAddress().toString(),
711                        new ChannelInfo(channel));
712                }
713                return result;
714            }).orElse(Collections.emptySortedMap());
715        }
716    }
717
718    /**
719     * An MBean interface for getting information about the socket servers
720     * and established connections.
721     */
722    public interface SocketServerSummaryMXBean {
723
724        /**
725         * Gets the connections per server statistics.
726         *
727         * @return the connections per server statistics
728         */
729        IntSummaryStatistics getConnectionsPerServerStatistics();
730
731        /**
732         * Gets the servers.
733         *
734         * @return the servers
735         */
736        Set<SocketServerMXBean> getServers();
737    }
738
739    /**
740     * The MBeanView.
741     */
742    @SuppressWarnings("PMD.PublicMemberInNonPublicType")
743    private static final class MBeanView implements SocketServerSummaryMXBean {
744        private static Set<SocketServerInfo> serverInfos = new HashSet<>();
745
746        /**
747         * Adds the server to the reported servers.
748         *
749         * @param server the server
750         */
751        public static void addServer(SocketServer server) {
752            synchronized (serverInfos) {
753                serverInfos.add(new SocketServerInfo(server));
754            }
755        }
756
757        /**
758         * Returns the infos.
759         *
760         * @return the sets the
761         */
762        private Set<SocketServerInfo> infos() {
763            Set<SocketServerInfo> expired = new HashSet<>();
764            synchronized (serverInfos) {
765                for (SocketServerInfo serverInfo : serverInfos) {
766                    if (!serverInfo.server().isPresent()) {
767                        expired.add(serverInfo);
768                    }
769                }
770                serverInfos.removeAll(expired);
771            }
772            return serverInfos;
773        }
774
775        @SuppressWarnings("unchecked")
776        @Override
777        public Set<SocketServerMXBean> getServers() {
778            return (Set<SocketServerMXBean>) (Object) infos();
779        }
780
781        @Override
782        public IntSummaryStatistics getConnectionsPerServerStatistics() {
783            return infos().stream().map(info -> info.server().get())
784                .filter(ref -> ref != null).collect(
785                    Collectors.summarizingInt(srv -> srv.channels.size()));
786        }
787    }
788
789    static {
790        try {
791            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
792            ObjectName mxbeanName = new ObjectName("org.jgrapes.io:type="
793                + SocketServer.class.getSimpleName() + "s");
794            mbs.registerMBean(new MBeanView(), mxbeanName);
795        } catch (MalformedObjectNameException | InstanceAlreadyExistsException
796                | MBeanRegistrationException | NotCompliantMBeanException e) {
797            // Does not happen
798        }
799    }
800
801}