001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2023 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 
013 * License for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License 
016 * along with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.io.util;
020
021import java.util.HashSet;
022import java.util.Set;
023import java.util.concurrent.ExecutorService;
024import org.jgrapes.core.Channel;
025import org.jgrapes.core.Component;
026import org.jgrapes.core.Components;
027import org.jgrapes.core.Event;
028import org.jgrapes.core.EventPipeline;
029import org.jgrapes.core.Manager;
030import org.jgrapes.core.Subchannel;
031import org.jgrapes.core.annotation.Handler;
032import org.jgrapes.core.annotation.HandlerDefinition.ChannelReplacements;
033import org.jgrapes.core.events.Stop;
034import org.jgrapes.io.events.Close;
035
036/**
037 * A base class for components that manage {@link Subchannel}s representing
038 * some kind of connection to a server or service.
039 *
040 * @param <C> the type of the managed connections
041 */
042@SuppressWarnings("PMD.AvoidSynchronizedStatement")
043public abstract class ConnectionManager<
044        C extends ConnectionManager<C>.Connection>
045        extends Component {
046
047    protected final Set<C> connections = new HashSet<>();
048    private ExecutorService executorService;
049
050    /**
051     * Creates a new component base with its channel set to
052     * itself.
053     */
054    public ConnectionManager() {
055        super();
056    }
057
058    /**
059     * Creates a new component base with its channel set to the given 
060     * channel. As a special case {@link Channel#SELF} can be
061     * passed to the constructor to make the component use itself
062     * as channel. The special value is necessary as you 
063     * obviously cannot pass an object to be constructed to its 
064     * constructor.
065     *
066     * @param componentChannel the channel that the component's
067     * handlers listen on by default and that 
068     * {@link Manager#fire(Event, Channel...)} sends the event to
069     */
070    @SuppressWarnings("PMD.LooseCoupling")
071    public ConnectionManager(Channel componentChannel,
072            ChannelReplacements channelReplacements) {
073        super(componentChannel, channelReplacements);
074    }
075
076    /**
077     * Creates a new component base like 
078     * {@link Component#Component(Channel)} but with channel mappings 
079     * for {@link Handler} annotations.
080     *
081     * @param componentChannel the channel that the component's
082     * handlers listen on by default and that 
083     * {@link Manager#fire(Event, Channel...)} sends the event to
084     */
085    public ConnectionManager(Channel componentChannel) {
086        super(componentChannel);
087    }
088
089    /**
090     * If connections are event generators, register the component as
091     * generator upon the creation of the first connection and unregister
092     * it when closing the last one.  
093     *
094     * @return true, if connections generate
095     */
096    protected abstract boolean connectionsGenerate();
097
098    /**
099     * Sets an executor service to be used by the downstream event 
100     * pipelines. Setting this to an executor service with a limited 
101     * number of threads allows to control the maximum load caused 
102     * by events generated by this component.
103     * 
104     * @param executorService the executorService to set
105     * @return the connection manager for easy chaining
106     * @see Manager#newEventPipeline(ExecutorService)
107     */
108    public ConnectionManager<C>
109            setExecutorService(ExecutorService executorService) {
110        this.executorService = executorService;
111        return this;
112    }
113
114    /**
115     * Returns the executor service.
116     *
117     * @return the executorService
118     */
119    public ExecutorService executorService() {
120        if (executorService == null) {
121            return Components.defaultExecutorService();
122        }
123        return executorService;
124    }
125
126    /**
127     * Closes all connections.
128     * 
129     * @param event the event
130     */
131    @Handler
132    public void onStop(Stop event) {
133        while (true) {
134            C connection;
135            synchronized (connections) {
136                var itr = connections.iterator();
137                if (!itr.hasNext()) {
138                    return;
139                }
140                connection = itr.next();
141            }
142            connection.close();
143        }
144    }
145
146    /**
147     * Closes the given connection.
148     *
149     * @param event the event
150     * @param connection the connection
151     */
152    @Handler
153    public void onClose(Close event, C connection) {
154        synchronized (this) {
155            if (connections.contains(connection)) {
156                connection.close();
157            }
158        }
159    }
160
161    /**
162     * The base class for the connections managed by this component.
163     */
164    public class Connection extends Subchannel.DefaultSubchannel {
165
166        private final EventPipeline downPipeline;
167
168        /**
169         * @param mainChannel
170         */
171        @SuppressWarnings({ "unchecked",
172            "PMD.ConstructorCallsOverridableMethod" })
173        public Connection(Channel mainChannel) {
174            super(mainChannel);
175            synchronized (ConnectionManager.this) {
176                if (connections.isEmpty() && connectionsGenerate()) {
177                    registerAsGenerator();
178                }
179                connections.add((C) this);
180            }
181            if (executorService == null) {
182                downPipeline = newEventPipeline();
183            } else {
184                downPipeline = newEventPipeline(executorService);
185            }
186        }
187
188        /**
189         * Gets the down pipeline.
190         *
191         * @return the downPipeline
192         */
193        public EventPipeline downPipeline() {
194            return downPipeline;
195        }
196
197        /**
198         * Closes the connection. If the last connection is closed
199         * and the component is a generator (see 
200         * {@link ConnectionManager#connectionsGenerate()), the component
201         * is unregistered as generator.
202         */
203        public void close() {
204            synchronized (this) {
205                connections.remove(this);
206                if (connections.isEmpty() && connectionsGenerate()) {
207                    unregisterAsGenerator();
208                }
209            }
210        }
211
212    }
213}