Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a5ebe70b979e38744e1ff8578d5c8a0e9f8098f1 (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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
//========================================================================
//Copyright 2011-2012 Mort Bay Consulting Pty. Ltd.
//------------------------------------------------------------------------
//All rights reserved. This program and the accompanying materials
//are made available under the terms of the Eclipse Public License v1.0
//and Apache License v2.0 which accompanies this distribution.
//The Eclipse Public License is available at
//http://www.eclipse.org/legal/epl-v10.html
//The Apache License v2.0 is available at
//http://www.opensource.org/licenses/apache2.0.php
//You may elect to redistribute this code under either of these licenses.
//========================================================================

package org.eclipse.jetty.spdy;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.InterruptedByTimeoutException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.spdy.api.ByteBufferDataInfo;
import org.eclipse.jetty.spdy.api.DataInfo;
import org.eclipse.jetty.spdy.api.GoAwayInfo;
import org.eclipse.jetty.spdy.api.PingInfo;
import org.eclipse.jetty.spdy.api.RstInfo;
import org.eclipse.jetty.spdy.api.SPDYException;
import org.eclipse.jetty.spdy.api.Session;
import org.eclipse.jetty.spdy.api.SessionFrameListener;
import org.eclipse.jetty.spdy.api.SessionStatus;
import org.eclipse.jetty.spdy.api.Settings;
import org.eclipse.jetty.spdy.api.SettingsInfo;
import org.eclipse.jetty.spdy.api.Stream;
import org.eclipse.jetty.spdy.api.StreamFrameListener;
import org.eclipse.jetty.spdy.api.StreamStatus;
import org.eclipse.jetty.spdy.api.SynInfo;
import org.eclipse.jetty.spdy.frames.ControlFrame;
import org.eclipse.jetty.spdy.frames.ControlFrameType;
import org.eclipse.jetty.spdy.frames.CredentialFrame;
import org.eclipse.jetty.spdy.frames.DataFrame;
import org.eclipse.jetty.spdy.frames.GoAwayFrame;
import org.eclipse.jetty.spdy.frames.HeadersFrame;
import org.eclipse.jetty.spdy.frames.PingFrame;
import org.eclipse.jetty.spdy.frames.RstStreamFrame;
import org.eclipse.jetty.spdy.frames.SettingsFrame;
import org.eclipse.jetty.spdy.frames.SynReplyFrame;
import org.eclipse.jetty.spdy.frames.SynStreamFrame;
import org.eclipse.jetty.spdy.frames.WindowUpdateFrame;
import org.eclipse.jetty.spdy.generator.Generator;
import org.eclipse.jetty.spdy.parser.Parser;
import org.eclipse.jetty.util.Atomics;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.component.AggregateLifeCycle;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

public class StandardSession implements ISession, Parser.Listener, Callback<StandardSession.FrameBytes>, Dumpable
{
    private static final Logger logger = Log.getLogger(Session.class);
    private static final ThreadLocal<Integer> handlerInvocations = new ThreadLocal<Integer>()
    {
        @Override
        protected Integer initialValue()
        {
            return 0;
        }
    };

    private final Map<String, Object> attributes = new ConcurrentHashMap<>();
    private final List<Listener> listeners = new CopyOnWriteArrayList<>();
    private final ConcurrentMap<Integer, IStream> streams = new ConcurrentHashMap<>();
    private final LinkedList<FrameBytes> queue = new LinkedList<>();
    private final ByteBufferPool bufferPool;
    private final Executor threadPool;
    private final ScheduledExecutorService scheduler;
    private final short version;
    private final Controller<FrameBytes> controller;
    private final IdleListener idleListener;
    private final AtomicInteger streamIds;
    private final AtomicInteger pingIds;
    private final SessionFrameListener listener;
    private final Generator generator;
    private final AtomicBoolean goAwaySent = new AtomicBoolean();
    private final AtomicBoolean goAwayReceived = new AtomicBoolean();
    private final AtomicInteger lastStreamId = new AtomicInteger();
    private final FlowControlStrategy flowControlStrategy;
    private boolean flushing;
    private Throwable failure;

    public StandardSession(short version, ByteBufferPool bufferPool, Executor threadPool, ScheduledExecutorService scheduler,
            Controller<FrameBytes> controller, IdleListener idleListener, int initialStreamId, SessionFrameListener listener,
            Generator generator, FlowControlStrategy flowControlStrategy)
    {
        this.version = version;
        this.bufferPool = bufferPool;
        this.threadPool = threadPool;
        this.scheduler = scheduler;
        this.controller = controller;
        this.idleListener = idleListener;
        this.streamIds = new AtomicInteger(initialStreamId);
        this.pingIds = new AtomicInteger(initialStreamId);
        this.listener = listener;
        this.generator = generator;
        this.flowControlStrategy = flowControlStrategy;
    }

    @Override
    public short getVersion()
    {
        return version;
    }

    @Override
    public void addListener(Listener listener)
    {
        listeners.add(listener);
    }

    @Override
    public void removeListener(Listener listener)
    {
        listeners.remove(listener);
    }

    @Override
    public Future<Stream> syn(SynInfo synInfo, StreamFrameListener listener)
    {
        Promise<Stream> result = new Promise<>();
        syn(synInfo,listener,0,TimeUnit.MILLISECONDS,result);
        return result;
    }

    @Override
    public void syn(SynInfo synInfo, StreamFrameListener listener, long timeout, TimeUnit unit, Callback<Stream> callback)
    {
        // Synchronization is necessary.
        // SPEC v3, 2.3.1 requires that the stream creation be monotonically crescent
        // so we cannot allow thread1 to create stream1 and thread2 create stream3 and
        // have stream3 hit the network before stream1, not only to comply with the spec
        // but also because the compression context for the headers would be wrong, as the
        // frame with a compression history will come before the first compressed frame.
        int associatedStreamId = 0;
        if (synInfo instanceof PushSynInfo)
            associatedStreamId = ((PushSynInfo)synInfo).getAssociatedStreamId();

        synchronized (this)
        {
            int streamId = streamIds.getAndAdd(2);
            // TODO: for SPDYv3 we need to support the "slot" argument
            SynStreamFrame synStream = new SynStreamFrame(version, synInfo.getFlags(), streamId, associatedStreamId, synInfo.getPriority(), (short)0, synInfo.getHeaders());
            IStream stream = createStream(synStream, listener, true);
            generateAndEnqueueControlFrame(stream, synStream, timeout, unit, callback, stream);
        }
        flush();
    }

    @Override
    public Future<Void> rst(RstInfo rstInfo)
    {
        Promise<Void> result = new Promise<>();
        rst(rstInfo,0,TimeUnit.MILLISECONDS,result);
        return result;
    }

    @Override
    public void rst(RstInfo rstInfo, long timeout, TimeUnit unit, Callback<Void> callback)
    {
        // SPEC v3, 2.2.2
        if (goAwaySent.get())
        {
            complete(callback,null);
        }
        else
        {
            int streamId = rstInfo.getStreamId();
            IStream stream = streams.get(streamId);
            RstStreamFrame frame = new RstStreamFrame(version,streamId,rstInfo.getStreamStatus().getCode(version));
            control(stream,frame,timeout,unit,callback,null);
            if (stream != null)
            {
                stream.process(frame);
                removeStream(stream);
            }
        }
    }

    @Override
    public Future<Void> settings(SettingsInfo settingsInfo)
    {
        Promise<Void> result = new Promise<>();
        settings(settingsInfo,0,TimeUnit.MILLISECONDS,result);
        return result;
    }

    @Override
    public void settings(SettingsInfo settingsInfo, long timeout, TimeUnit unit, Callback<Void> callback)
    {
        SettingsFrame frame = new SettingsFrame(version,settingsInfo.getFlags(),settingsInfo.getSettings());
        control(null, frame, timeout, unit, callback, null);
    }

    @Override
    public Future<PingInfo> ping()
    {
        Promise<PingInfo> result = new Promise<>();
        ping(0, TimeUnit.MILLISECONDS, result);
        return result;
    }

    @Override
    public void ping(long timeout, TimeUnit unit, Callback<PingInfo> callback)
    {
        int pingId = pingIds.getAndAdd(2);
        PingInfo pingInfo = new PingInfo(pingId);
        PingFrame frame = new PingFrame(version,pingId);
        control(null,frame,timeout,unit,callback,pingInfo);
    }

    @Override
    public Future<Void> goAway()
    {
        return goAway(SessionStatus.OK);
    }

    private Future<Void> goAway(SessionStatus sessionStatus)
    {
        Promise<Void> result = new Promise<>();
        goAway(sessionStatus, 0, TimeUnit.MILLISECONDS, result);
        return result;
    }

    @Override
    public void goAway(long timeout, TimeUnit unit, Callback<Void> callback)
    {
        goAway(SessionStatus.OK, timeout, unit, callback);
    }

    private void goAway(SessionStatus sessionStatus, long timeout, TimeUnit unit, Callback<Void> callback)
    {
        new Exception().printStackTrace();
        if (goAwaySent.compareAndSet(false,true))
        {
            if (!goAwayReceived.get())
            {
                GoAwayFrame frame = new GoAwayFrame(version,lastStreamId.get(),sessionStatus.getCode());
                control(null,frame,timeout,unit,callback,null);
                return;
            }
        }
        complete(callback, null);
    }

    @Override
    public Set<Stream> getStreams()
    {
        Set<Stream> result = new HashSet<>();
        result.addAll(streams.values());
        return result;
    }

    @Override
    public IStream getStream(int streamId)
    {
        return streams.get(streamId);
    }

    @Override
    public Object getAttribute(String key)
    {
        return attributes.get(key);
    }

    @Override
    public void setAttribute(String key, Object value)
    {
        attributes.put(key, value);
    }

    @Override
    public Object removeAttribute(String key)
    {
        return attributes.remove(key);
    }

    @Override
    public void onControlFrame(ControlFrame frame)
    {
        notifyIdle(idleListener, false);
        try
        {
            logger.debug("Processing {}", frame);

            if (goAwaySent.get())
            {
                logger.debug("Skipped processing of {}", frame);
                return;
            }

            switch (frame.getType())
            {
                case SYN_STREAM:
                {
                    onSyn((SynStreamFrame)frame);
                    break;
                }
                case SYN_REPLY:
                {
                    onReply((SynReplyFrame)frame);
                    break;
                }
                case RST_STREAM:
                {
                    onRst((RstStreamFrame)frame);
                    break;
                }
                case SETTINGS:
                {
                    onSettings((SettingsFrame)frame);
                    break;
                }
                case NOOP:
                {
                    // Just ignore it
                    break;
                }
                case PING:
                {
                    onPing((PingFrame)frame);
                    break;
                }
                case GO_AWAY:
                {
                    onGoAway((GoAwayFrame)frame);
                    break;
                }
                case HEADERS:
                {
                    onHeaders((HeadersFrame)frame);
                    break;
                }
                case WINDOW_UPDATE:
                {
                    onWindowUpdate((WindowUpdateFrame)frame);
                    break;
                }
                case CREDENTIAL:
                {
                    onCredential((CredentialFrame)frame);
                    break;
                }
                default:
                {
                    throw new IllegalStateException();
                }
            }
        }
        finally
        {
            notifyIdle(idleListener, true);
        }
    }

    @Override
    public void onDataFrame(DataFrame frame, ByteBuffer data)
    {
        notifyIdle(idleListener, false);
        try
        {
            logger.debug("Processing {}, {} data bytes", frame, data.remaining());

            if (goAwaySent.get())
            {
                logger.debug("Skipped processing of {}", frame);
                return;
            }

            int streamId = frame.getStreamId();
            IStream stream = streams.get(streamId);
            if (stream == null)
            {
                RstInfo rstInfo = new RstInfo(streamId, StreamStatus.INVALID_STREAM);
                logger.debug("Unknown stream {}", rstInfo);
                rst(rstInfo);
            }
            else
            {
                processData(stream, frame, data);
            }
        }
        finally
        {
            notifyIdle(idleListener, true);
        }
    }

    private void notifyIdle(IdleListener listener, boolean idle)
    {
        if (listener != null)
            listener.onIdle(idle);
    }

    private void processData(final IStream stream, DataFrame frame, ByteBuffer data)
    {
        ByteBufferDataInfo dataInfo = new ByteBufferDataInfo(data, frame.isClose(), frame.isCompress())
        {
            @Override
            public void consume(int delta)
            {
                super.consume(delta);
                flowControlStrategy.onDataConsumed(StandardSession.this, stream, this, delta);
            }
        };
        flowControlStrategy.onDataReceived(this, stream, dataInfo);
        stream.process(dataInfo);
        if (stream.isClosed())
            removeStream(stream);
    }

    @Override
    public void onStreamException(StreamException x)
    {
        notifyOnException(listener, x);
        rst(new RstInfo(x.getStreamId(),x.getStreamStatus()));
    }

    @Override
    public void onSessionException(SessionException x)
    {
        Throwable cause = x.getCause();
        notifyOnException(listener,cause == null?x:cause);
        goAway(x.getSessionStatus());
    }

    private void onSyn(SynStreamFrame frame)
    {
        IStream stream = createStream(frame, null, false);
        if (stream != null)
            processSyn(listener, stream, frame);
    }

    private void processSyn(SessionFrameListener listener, IStream stream, SynStreamFrame frame)
    {
        stream.process(frame);
        // Update the last stream id before calling the application (which may send a GO_AWAY)
        updateLastStreamId(stream);
        SynInfo synInfo = new SynInfo(frame.getHeaders(),frame.isClose(),frame.getPriority());
        StreamFrameListener streamListener = notifyOnSyn(listener,stream,synInfo);
        stream.setStreamFrameListener(streamListener);
        flush();
        // The onSyn() listener may have sent a frame that closed the stream
        if (stream.isClosed())
            removeStream(stream);
    }

    private IStream createStream(SynStreamFrame frame, StreamFrameListener listener, boolean local)
    {
        IStream stream = newStream(frame);
        stream.updateCloseState(frame.isClose(), local);
        stream.setStreamFrameListener(listener);

        if (stream.isUnidirectional())
        {
            // Unidirectional streams are implicitly half closed
            stream.updateCloseState(true, !local);
            if (!stream.isClosed())
                stream.getAssociatedStream().associate(stream);
        }

        int streamId = stream.getId();
        if (streams.putIfAbsent(streamId, stream) != null)
        {
            if (local)
                throw new IllegalStateException("Duplicate stream id " + streamId);
            RstInfo rstInfo = new RstInfo(streamId, StreamStatus.PROTOCOL_ERROR);
            logger.debug("Duplicate stream, {}", rstInfo);
            rst(rstInfo);
            return null;
        }
        else
        {
            logger.debug("Created {}", stream);
            if (local)
                notifyStreamCreated(stream);
            return stream;
        }
    }

    private IStream newStream(SynStreamFrame frame)
    {
        IStream associatedStream = streams.get(frame.getAssociatedStreamId());
        IStream stream = new StandardStream(frame.getStreamId(), frame.getPriority(), this, associatedStream);
        flowControlStrategy.onNewStream(this, stream);
        return stream;
    }

    private void notifyStreamCreated(IStream stream)
    {
        for (Listener listener : listeners)
        {
            if (listener instanceof StreamListener)
            {
                try
                {
                    ((StreamListener)listener).onStreamCreated(stream);
                }
                catch (Exception x)
                {
                    logger.info("Exception while notifying listener " + listener, x);
                }
                catch (Error x)
                {
                    logger.info("Exception while notifying listener " + listener, x);
                    throw x;
                }
            }
        }
    }

    private void removeStream(IStream stream)
    {
        if (stream.isUnidirectional())
            stream.getAssociatedStream().disassociate(stream);

        IStream removed = streams.remove(stream.getId());
        if (removed != null)
            assert removed == stream;

        logger.debug("Removed {}", stream);
        notifyStreamClosed(stream);
    }

    private void notifyStreamClosed(IStream stream)
    {
        for (Listener listener : listeners)
        {
            if (listener instanceof StreamListener)
            {
                try
                {
                    ((StreamListener)listener).onStreamClosed(stream);
                }
                catch (Exception x)
                {
                    logger.info("Exception while notifying listener " + listener, x);
                }
                catch (Error x)
                {
                    logger.info("Exception while notifying listener " + listener, x);
                    throw x;
                }
            }
        }
    }

    private void onReply(SynReplyFrame frame)
    {
        int streamId = frame.getStreamId();
        IStream stream = streams.get(streamId);
        if (stream == null)
        {
            RstInfo rstInfo = new RstInfo(streamId,StreamStatus.INVALID_STREAM);
            logger.debug("Unknown stream {}",rstInfo);
            rst(rstInfo);
        }
        else
        {
            processReply(stream,frame);
        }
    }

    private void processReply(IStream stream, SynReplyFrame frame)
    {
        stream.process(frame);
        if (stream.isClosed())
            removeStream(stream);
    }

    private void onRst(RstStreamFrame frame)
    {
        IStream stream = streams.get(frame.getStreamId());

        if (stream != null)
            stream.process(frame);

        RstInfo rstInfo = new RstInfo(frame.getStreamId(),StreamStatus.from(frame.getVersion(),frame.getStatusCode()));
        notifyOnRst(listener, rstInfo);
        flush();

        if (stream != null)
            removeStream(stream);
    }

    private void onSettings(SettingsFrame frame)
    {
        Settings.Setting windowSizeSetting = frame.getSettings().get(Settings.ID.INITIAL_WINDOW_SIZE);
        if (windowSizeSetting != null)
        {
            int windowSize = windowSizeSetting.value();
            setWindowSize(windowSize);
            logger.debug("Updated session window size to {}", windowSize);
        }
        SettingsInfo settingsInfo = new SettingsInfo(frame.getSettings(), frame.isClearPersisted());
        notifyOnSettings(listener, settingsInfo);
        flush();
    }

    private void onPing(PingFrame frame)
    {
        int pingId = frame.getPingId();
        if (pingId % 2 == pingIds.get() % 2)
        {
            PingInfo pingInfo = new PingInfo(frame.getPingId());
            notifyOnPing(listener, pingInfo);
            flush();
        }
        else
        {
            control(null, frame, 0, TimeUnit.MILLISECONDS, null, null);
        }
    }

    private void onGoAway(GoAwayFrame frame)
    {
        if (goAwayReceived.compareAndSet(false, true))
        {
            GoAwayInfo goAwayInfo = new GoAwayInfo(frame.getLastStreamId(),SessionStatus.from(frame.getStatusCode()));
            notifyOnGoAway(listener,goAwayInfo);
            flush();
            // SPDY does not require to send back a response to a GO_AWAY.
            // We notified the application of the last good stream id,
            // tried our best to flush remaining data, and close.
            close();
        }
    }

    private void onHeaders(HeadersFrame frame)
    {
        int streamId = frame.getStreamId();
        IStream stream = streams.get(streamId);
        if (stream == null)
        {
            RstInfo rstInfo = new RstInfo(streamId,StreamStatus.INVALID_STREAM);
            logger.debug("Unknown stream, {}",rstInfo);
            rst(rstInfo);
        }
        else
        {
            processHeaders(stream,frame);
        }
    }

    private void processHeaders(IStream stream, HeadersFrame frame)
    {
        stream.process(frame);
        if (stream.isClosed())
            removeStream(stream);
    }

    private void onWindowUpdate(WindowUpdateFrame frame)
    {
        int streamId = frame.getStreamId();
        IStream stream = streams.get(streamId);
        flowControlStrategy.onWindowUpdate(this, stream, frame.getWindowDelta());
        flush();
    }

    private void onCredential(CredentialFrame frame)
    {
        logger.warn("{} frame not yet supported", ControlFrameType.CREDENTIAL);
        flush();
    }

    protected void close()
    {
        // Check for null to support tests
        if (controller != null)
            controller.close(false);
    }

    private void notifyOnException(SessionFrameListener listener, Throwable x)
    {
        try
        {
            if (listener != null)
            {
                logger.debug("Invoking callback with {} on listener {}",x,listener);
                listener.onException(x);
            }
        }
        catch (Exception xx)
        {
            logger.info("Exception while notifying listener " + listener, xx);
        }
        catch (Error xx)
        {
            logger.info("Exception while notifying listener " + listener, xx);
            throw xx;
        }
    }

    private StreamFrameListener notifyOnSyn(SessionFrameListener listener, Stream stream, SynInfo synInfo)
    {
        try
        {
            if (listener == null)
                return null;
            logger.debug("Invoking callback with {} on listener {}",synInfo,listener);
            return listener.onSyn(stream,synInfo);
        }
        catch (Exception x)
        {
            logger.info("Exception while notifying listener " + listener,x);
            return null;
        }
        catch (Error x)
        {
            logger.info("Exception while notifying listener " + listener, x);
            throw x;
        }
    }

    private void notifyOnRst(SessionFrameListener listener, RstInfo rstInfo)
    {
        try
        {
            if (listener != null)
            {
                logger.debug("Invoking callback with {} on listener {}",rstInfo,listener);
                listener.onRst(this,rstInfo);
            }
        }
        catch (Exception x)
        {
            logger.info("Exception while notifying listener " + listener, x);
        }
        catch (Error x)
        {
            logger.info("Exception while notifying listener " + listener, x);
            throw x;
        }
    }

    private void notifyOnSettings(SessionFrameListener listener, SettingsInfo settingsInfo)
    {
        try
        {
            if (listener != null)
            {
                logger.debug("Invoking callback with {} on listener {}",settingsInfo,listener);
                listener.onSettings(this, settingsInfo);
            }
        }
        catch (Exception x)
        {
            logger.info("Exception while notifying listener " + listener, x);
        }
        catch (Error x)
        {
            logger.info("Exception while notifying listener " + listener, x);
            throw x;
        }
    }

    private void notifyOnPing(SessionFrameListener listener, PingInfo pingInfo)
    {
        try
        {
            if (listener != null)
            {
                logger.debug("Invoking callback with {} on listener {}",pingInfo,listener);
                listener.onPing(this, pingInfo);
            }
        }
        catch (Exception x)
        {
            logger.info("Exception while notifying listener " + listener, x);
        }
        catch (Error x)
        {
            logger.info("Exception while notifying listener " + listener, x);
            throw x;
        }
    }

    private void notifyOnGoAway(SessionFrameListener listener, GoAwayInfo goAwayInfo)
    {
        try
        {
            if (listener != null)
            {
                logger.debug("Invoking callback with {} on listener {}",goAwayInfo,listener);
                listener.onGoAway(this, goAwayInfo);
            }
        }
        catch (Exception x)
        {
            logger.info("Exception while notifying listener " + listener, x);
        }
        catch (Error x)
        {
            logger.info("Exception while notifying listener " + listener, x);
            throw x;
        }
    }


    @Override
    public <C> void control(IStream stream, ControlFrame frame, long timeout, TimeUnit unit, Callback<C> callback, C context)
    {
        generateAndEnqueueControlFrame(stream,frame,timeout,unit,callback,context);
        flush();
    }

    private <C> void generateAndEnqueueControlFrame(IStream stream, ControlFrame frame, long timeout, TimeUnit unit, Callback<C> callback, C context)
    {
        try
        {
            // Synchronization is necessary, since we may have concurrent replies
            // and those needs to be generated and enqueued atomically in order
            // to maintain a correct compression context
            synchronized (this)
            {
                ByteBuffer buffer = generator.control(frame);
                logger.debug("Queuing {} on {}", frame, stream);
                ControlFrameBytes<C> frameBytes = new ControlFrameBytes<>(stream, callback, context, frame, buffer);
                if (timeout > 0)
                    frameBytes.task = scheduler.schedule(frameBytes, timeout, unit);

                // Special handling for PING frames, they must be sent as soon as possible
                if (ControlFrameType.PING == frame.getType())
                    prepend(frameBytes);
                else
                    append(frameBytes);
            }
        }
        catch (Exception x)
        {
            notifyCallbackFailed(callback, context, x);
        }
    }

    private void updateLastStreamId(IStream stream)
    {
        int streamId = stream.getId();
        if (streamId % 2 != streamIds.get() % 2)
            Atomics.updateMax(lastStreamId, streamId);
    }

    @Override
    public <C> void data(IStream stream, DataInfo dataInfo, long timeout, TimeUnit unit, Callback<C> callback, C context)
    {
        logger.debug("Queuing {} on {}",dataInfo,stream);
        DataFrameBytes<C> frameBytes = new DataFrameBytes<>(stream,callback,context,dataInfo);
        if (timeout > 0)
            frameBytes.task = scheduler.schedule(frameBytes,timeout,unit);
        append(frameBytes);
        flush();
    }

    private void execute(Runnable task)
    {
        threadPool.execute(task);
    }

    @Override
    public void flush()
    {
        FrameBytes frameBytes = null;
        ByteBuffer buffer = null;
        synchronized (queue)
        {
            if (flushing || queue.isEmpty())
                return;

            Set<IStream> stalledStreams = null;
            for (int i = 0; i < queue.size(); ++i)
            {
                frameBytes = queue.get(i);

                IStream stream = frameBytes.getStream();
                if (stream != null && stalledStreams != null && stalledStreams.contains(stream))
                    continue;

                buffer = frameBytes.getByteBuffer();
                if (buffer != null)
                {
                    queue.remove(i);
                    if (stream != null && stream.isReset())
                    {
                        frameBytes.fail(new StreamException(stream.getId(),StreamStatus.INVALID_STREAM));
                        return;
                    }
                    break;
                }

                if (stalledStreams == null)
                    stalledStreams = new HashSet<>();
                if (stream != null)
                    stalledStreams.add(stream);

                logger.debug("Flush stalled for {}, {} frame(s) in queue",frameBytes,queue.size());
            }

            if (buffer == null)
                return;

            flushing = true;
            logger.debug("Flushing {}, {} frame(s) in queue",frameBytes,queue.size());
        }
        write(buffer,this,frameBytes);
    }

    private void append(FrameBytes frameBytes)
    {
        Throwable failure;
        synchronized (queue)
        {
            failure = this.failure;
            if (failure == null)
            {
                int index = queue.size();
                while (index > 0)
                {
                    FrameBytes element = queue.get(index - 1);
                    if (element.compareTo(frameBytes) >= 0)
                        break;
                    --index;
                }
                queue.add(index,frameBytes);
            }
        }

        if (failure != null)
            frameBytes.fail(new SPDYException(failure));
    }

    private void prepend(FrameBytes frameBytes)
    {
        Throwable failure;
        synchronized (queue)
        {
            failure = this.failure;
            if (failure == null)
            {
                int index = 0;
                while (index < queue.size())
                {
                    FrameBytes element = queue.get(index);
                    if (element.compareTo(frameBytes) <= 0)
                        break;
                    ++index;
                }
                queue.add(index,frameBytes);
            }
        }

        if (failure != null)
            frameBytes.fail(new SPDYException(failure));
    }

    @Override
    public void completed(FrameBytes frameBytes)
    {
        synchronized (queue)
        {
            logger.debug("Completed write of {}, {} frame(s) in queue",frameBytes,queue.size());
            flushing = false;
        }
        frameBytes.complete();
    }

    @Override
    public void failed(FrameBytes frameBytes, Throwable x)
    {
        List<FrameBytes> frameBytesToFail = new ArrayList<>();
        frameBytesToFail.add(frameBytes);

        synchronized (queue)
        {
            failure = x;
            String logMessage = String.format("Failed write of %s, failing all %d frame(s) in queue",frameBytes,queue.size());
            logger.debug(logMessage,x);
            frameBytesToFail.addAll(queue);
            queue.clear();
            flushing = false;
        }

        for (FrameBytes fb : frameBytesToFail)
            fb.fail(x);
    }

    protected void write(ByteBuffer buffer, Callback<FrameBytes> callback, FrameBytes frameBytes)
    {
        if (controller != null)
        {
            logger.debug("Writing {} frame bytes of {}",buffer.remaining(),frameBytes);
            controller.write(buffer,callback,frameBytes);
        }
    }

    private <C> void complete(final Callback<C> callback, final C context)
    {
        // Applications may send and queue up a lot of frames and
        // if we call Callback.completed() only synchronously we risk
        // starvation (for the last frames sent) and stack overflow.
        // Therefore every some invocation, we dispatch to a new thread
        Integer invocations = handlerInvocations.get();
        if (invocations >= 4)
        {
            execute(new Runnable()
            {
                @Override
                public void run()
                {
                    if (callback != null)
                        notifyCallbackCompleted(callback, context);
                    flush();
                }
            });
        }
        else
        {
            handlerInvocations.set(invocations + 1);
            try
            {
                if (callback != null)
                    notifyCallbackCompleted(callback, context);
                flush();
            }
            finally
            {
                handlerInvocations.set(invocations);
            }
        }
    }

    private <C> void notifyCallbackCompleted(Callback<C> callback, C context)
    {
        try
        {
            callback.completed(context);
        }
        catch (Exception x)
        {
            logger.info("Exception while notifying callback " + callback, x);
        }
        catch (Error x)
        {
            logger.info("Exception while notifying callback " + callback, x);
            throw x;
        }
    }

    private <C> void notifyCallbackFailed(Callback<C> callback, C context, Throwable x)
    {
        try
        {
            if (callback != null)
                callback.failed(context, x);
        }
        catch (Exception xx)
        {
            logger.info("Exception while notifying callback " + callback, xx);
        }
        catch (Error xx)
        {
            logger.info("Exception while notifying callback " + callback, xx);
            throw xx;
        }
    }

    public int getWindowSize()
    {
        return flowControlStrategy.getWindowSize(this);
    }

    public void setWindowSize(int initialWindowSize)
    {
        flowControlStrategy.setWindowSize(this, initialWindowSize);
    }

    public String toString()
    {
        return String.format("%s@%x{v%d,queuSize=%d,windowSize=%d,streams=%d}", getClass().getSimpleName(), hashCode(), version, queue.size(), getWindowSize(), streams.size());
    }
    
    
    @Override
    public String dump()
    {
        return AggregateLifeCycle.dump(this);
    }

    @Override
    public void dump(Appendable out, String indent) throws IOException
    {
        AggregateLifeCycle.dumpObject(out,this);
        AggregateLifeCycle.dump(out,indent,Collections.singletonList(controller),streams.values());
    }



    public interface FrameBytes extends Comparable<FrameBytes>
    {
        public IStream getStream();

        public abstract ByteBuffer getByteBuffer();

        public abstract void complete();

        public abstract void fail(Throwable throwable);
    }

    private abstract class AbstractFrameBytes<C> implements FrameBytes, Runnable
    {
        private final IStream stream;
        private final Callback<C> callback;
        private final C context;
        protected volatile ScheduledFuture<?> task;

        protected AbstractFrameBytes(IStream stream, Callback<C> callback, C context)
        {
            this.stream = stream;
            this.callback = callback;
            this.context = context;
        }

        @Override
        public IStream getStream()
        {
            return stream;
        }

        @Override
        public int compareTo(FrameBytes that)
        {
            // FrameBytes may have or not have a related stream (for example, PING do not have a related stream)
            // FrameBytes without related streams have higher priority
            IStream thisStream = getStream();
            IStream thatStream = that.getStream();
            if (thisStream == null)
                return thatStream == null ? 0 : -1;
            if (thatStream == null)
                return 1;
            // If this.stream.priority > that.stream.priority => this.stream has less priority than that.stream
            return thatStream.getPriority() - thisStream.getPriority();
        }

        @Override
        public void complete()
        {
            cancelTask();
            StandardSession.this.complete(callback,context);
        }

        @Override
        public void fail(Throwable x)
        {
            cancelTask();
            notifyCallbackFailed(callback, context, x);
            StandardSession.this.flush();
        }

        private void cancelTask()
        {
            ScheduledFuture<?> task = this.task;
            if (task != null)
                task.cancel(false);
        }

        @Override
        public void run()
        {
            close();
            fail(new InterruptedByTimeoutException());
        }
    }

    private class ControlFrameBytes<C> extends AbstractFrameBytes<C>
    {
        private final ControlFrame frame;
        private final ByteBuffer buffer;

        private ControlFrameBytes(IStream stream, Callback<C> callback, C context, ControlFrame frame, ByteBuffer buffer)
        {
            super(stream,callback,context);
            this.frame = frame;
            this.buffer = buffer;
        }

        @Override
        public ByteBuffer getByteBuffer()
        {
            return buffer;
        }

        @Override
        public void complete()
        {
            bufferPool.release(buffer);

            super.complete();

            if (frame.getType() == ControlFrameType.GO_AWAY)
            {
                // After sending a GO_AWAY we need to hard close the connection.
                // Recipients will know the last good stream id and act accordingly.
                close();
            }
            IStream stream = getStream();
            if (stream != null && stream.isClosed())
                removeStream(stream);
        }

        @Override
        public String toString()
        {
            return frame.toString();
        }
    }

    private class DataFrameBytes<C> extends AbstractFrameBytes<C>
    {
        private final DataInfo dataInfo;
        private int size;
        private volatile ByteBuffer buffer;

        private DataFrameBytes(IStream stream, Callback<C> handler, C context, DataInfo dataInfo)
        {
            super(stream,handler,context);
            this.dataInfo = dataInfo;
        }

        @Override
        public ByteBuffer getByteBuffer()
        {
            try
            {
                IStream stream = getStream();
                int windowSize = stream.getWindowSize();
                if (windowSize <= 0)
                    return null;

                size = dataInfo.available();
                if (size > windowSize)
                    size = windowSize;

                buffer = generator.data(stream.getId(),size,dataInfo);
                return buffer;
            }
            catch (Throwable x)
            {
                fail(x);
                return null;
            }
        }

        @Override
        public void complete()
        {
            bufferPool.release(buffer);
            IStream stream = getStream();
            flowControlStrategy.updateWindow(StandardSession.this, stream, -size);
            if (dataInfo.available() > 0)
            {
                // We have written a frame out of this DataInfo, but there is more to write.
                // We need to keep the correct ordering of frames, to avoid that another
                // DataInfo for the same stream is written before this one is finished.
                prepend(this);
                flush();
            }
            else
            {
                super.complete();
                stream.updateCloseState(dataInfo.isClose(),true);
                if (stream.isClosed())
                    removeStream(stream);
            }
        }

        @Override
        public String toString()
        {
            return String.format("DATA bytes @%x available=%d consumed=%d on %s",dataInfo.hashCode(),dataInfo.available(),dataInfo.consumed(),getStream());
        }
    }
}

Back to the top