aboutsummaryrefslogtreecommitdiff
path: root/src/org/gnunet/requests/RequestQueue.java
blob: 6f7102d638ee7e79c86c646c7539de6960b6a0c8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/*
 This file is part of GNUnet.
 (C) 2011, 2012 Christian Grothoff (and other contributing authors)

 GNUnet is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published
 by the Free Software Foundation; either version 3, or (at your
 option) any later version.

 GNUnet is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GNUnet; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 Boston, MA 02111-1307, USA.
 */

package org.gnunet.requests;

import org.gnunet.util.*;

import java.util.LinkedList;

/**
 * Generic queues for Requests to be sent to the service.
 */
public class RequestQueue {

    /**
     * Requests to be transmitted to the service.
     */
    private final LinkedList<Request> requestsAwaitingTransmit = new LinkedList<Request>();

    /**
     * Persistent requests. Will be informed about reconnect / destroy events even
     * if already transmitted. Have to be canceled manually.
     */
    private final LinkedList<Request> persistentRequests = new LinkedList<Request>();

    /**
     * List of all requests from requestAwaitingTransmit and persistentRequest, containing no duplicates.
     */
    private final LinkedList<Request> allRequests = new LinkedList<Request>();

    /**
     * The designated receiver for all messages.
     */
    private MessageReceiver receiver;

    /**
     * The active transmit request handle, if any.
     */
    private Cancelable currentTransmit;

    /**
     * Current receive handler.
     */
    private Cancelable currentReceive;

    /**
     * True if we should not send further requests until queue is unclogged.
     */
    private boolean clogged = false;

    private boolean destroyed = false;
    private final Client client;

    public RequestQueue(Client client, MessageReceiver receiver) {
        this.client = client;
        this.receiver = receiver;
    }

    /**
     * Handle next request.
     */
    private void handleNextTransmit() {

        if (clogged) {
            return;
        }

        // return if we are already transmitting something
        if (currentTransmit != null) {
            return;
        }

        final Request request = requestsAwaitingTransmit.poll();
        if (request == null) {
            handleReceive();
            return;
        }

        AbsoluteTime deadline = request.getDeadline();
        if (deadline == null) {
            throw new AssertionError("getDeadline() must return a non-null AbsoluteTime");
        }

        currentTransmit = client.notifyTransmitReady(deadline.getRemaining(), true, 0, new MessageTransmitter() {
            @Override
            public void transmit(Connection.MessageSink sink) {
                currentTransmit = null;

                try {
                    request.transmit(sink);
                } finally {
                    handleReceive();
                    handleNextTransmit();
                }
            }

            @Override
            public void handleError() {
                throw new AssertionError("not implemented");
            }
        });
    }

    /**
     * Continue receiving if necessary.
     */
    private void handleReceive() {
        if (currentReceive != null || destroyed || !client.isConnected()) {
            return;
        }
        currentReceive = client.receive(RelativeTime.FOREVER, new MessageReceiver() {
            @Override
            public void process(GnunetMessage.Body msg) {
                currentReceive = null;

                try {
                    receiver.process(msg);
                } finally {
                    handleNextTransmit();
                    handleReceive();
                }
            }

            @Override
            public void handleError() {
                receiver.handleError();
            }
        });
    }

    /**
     * Add a request to the end of the queue.
     *
     * @param request request to be added
     * @return a handle to cancel the request
     */
    public Cancelable add(final Request request) {
        allRequests.add(request);
        requestsAwaitingTransmit.add(request);
        handleNextTransmit();

        return new Cancelable() {
            @Override
            public void cancel() {
                RequestQueue.this.requestsAwaitingTransmit.remove(request);
                RequestQueue.this.persistentRequests.remove(request);
                RequestQueue.this.allRequests.remove(request);
                request.onCancel(!requestsAwaitingTransmit.contains(request));
            }
        };
    }


    /**
     * Add a request so that it will get notified about reconnect/destroy events,
     * even if it already has been transmitted.
     */
    public Cancelable addPersistent(final Request request) {
        persistentRequests.add(request);
        return add(request);
    }


    /**
     * Add a request to the front of the queue, this request will be sent as
     * the next message (if not preempted by another sendNext).
     *
     * @param request request to be sent next
     * @return a handle to cancel the request
     */
    public Cancelable sendNext(final Request request) {
        requestsAwaitingTransmit.addFirst(request);
        handleNextTransmit();
        // todo: should this really return Cancelable? When do we want to cancel a request added by sendNext?
        return new Cancelable() {
            @Override
            public void cancel() {
                RequestQueue.this.requestsAwaitingTransmit.remove(request);
                RequestQueue.this.persistentRequests.remove(request);
                RequestQueue.this.allRequests.remove(request);
                request.onCancel(!requestsAwaitingTransmit.contains(request));
            }
        };
    }

    /**
     * Reconnect the client and notify all pending request of the reconnect.
     */
    public void reconnect() {
        client.reconnect();
        currentReceive = null;
        currentTransmit = null;

        final LinkedList<Request> remove = new LinkedList<Request>();


        for (Request r : allRequests) {
            boolean keep = r.onReconnect();
            if (!keep) {
                remove.add(r);
            } else {
                // retransmit an apparently persistent request.
                if (!requestsAwaitingTransmit.contains(r)) {
                    requestsAwaitingTransmit.add(r);
                }
            }
        }
        requestsAwaitingTransmit.removeAll(remove);
        persistentRequests.removeAll(remove);
        allRequests.removeAll(remove);

        // only transmit, receive should only be called after the first transmit
        handleNextTransmit();
    }

    /**
     * Notify all request of the shutdown. Does not actually destroy the connection.
     */
    public void shutdown() {
        final LinkedList<Request> remove = new LinkedList<Request>();

        for (Request r : allRequests) {
            boolean keep = r.onDestroy();
            if (!keep) {
                remove.add(r);
            } else {
                // retransmit an apparently persistent request.
                if (!requestsAwaitingTransmit.contains(r)) {
                    requestsAwaitingTransmit.add(r);
                }
            }
        }
        requestsAwaitingTransmit.removeAll(remove);
        persistentRequests.removeAll(remove);
        allRequests.removeAll(remove);

        handleNextTransmit();
        handleReceive();
    }

    /**
     * Cancel all requests and destroy the connection.
     */
    public void destroy() {
        destroyed = true;
        allRequests.clear();
        persistentRequests.clear();
        requestsAwaitingTransmit.clear();
        if (currentTransmit != null) {
            currentTransmit.cancel();
        }
        if (currentReceive != null) {
            currentReceive.cancel();
        }
    }

    /**
     * Allow no further requests to be transmitted until the queue is unclogged.
     */
    public void clog() {
        if (clogged) {
            throw new AssertionError("double clog");
        }
        clogged = true;
    }

    /**
     * Unclog the queue, must have been previously clogged.
     */
    public void unclog() {
        if (!clogged) {
            throw new AssertionError("unclogg before clog");
        }
        clogged = false;
        handleNextTransmit();
    }
}