1 /*
2  * MsgTrans - Message Transport Framework for DLang. Based on TCP, WebSocket, UDP transmission protocol.
3  *
4  * Copyright (C) 2019 HuntLabs
5  *
6  * Website: https://www.msgtrans.org
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module msgtrans.DefaultSessionManager;
13 
14 import msgtrans.channel.TransportSession;
15 import msgtrans.SessionManager;
16 
17 import hunt.collection.List;
18 import hunt.collection.ArrayList;
19 import hunt.Exceptions;
20 import hunt.logging.ConsoleLogger;
21 
22 import core.atomic;
23 import core.sync.mutex;
24 import std.array;
25 
26 // private shared ulong _serverSessionId = 0;
27 private shared ulong _clientSessionId = 0;
28 
29 // ulong nextServerSessionId() {
30 //     return atomicOp!("+=")(_serverSessionId, 1);
31 // }
32 
33 ulong nextClientSessionId() {
34     return atomicOp!("+=")(_clientSessionId, 1);
35 }
36 
37 /**
38  *
39  */
40 class DefaultSessionManager : SessionManager {
41     private shared ulong _serverSessionId = 0;
42 
43     private {
44         TransportSession[ulong] _sessions;
45         Mutex _locker;
46     }
47 
48     this() {
49         _locker = new Mutex();
50     }
51 
52     ulong generateId() {
53         return atomicOp!("+=")(_serverSessionId, 1);
54     }
55 
56     TransportSession get(ulong id) {
57         _locker.lock();
58         scope (exit)
59             _locker.unlock();
60         return _sessions.get(id, null);
61     }
62 
63     TransportSession[] getAll() {
64         return _sessions.byValue.array();
65     }
66 
67     void add(TransportSession session) {
68         assert(session !is null);
69 
70         _locker.lock();
71         scope (exit)
72             _locker.unlock();
73         _sessions[session.id()] = session;
74     }
75 
76     void remove(ulong id) {
77         _locker.lock();
78         scope (exit)
79             _locker.unlock();
80 
81         _sessions.remove(id);
82     }
83 
84     void remove(TransportSession session) {
85         assert(session !is null);
86 
87         remove(session.id());
88     }
89 
90     void clear() {
91         _locker.lock();
92         scope (exit)
93             _locker.unlock();
94 
95         _sessions.clear();
96     }
97 
98     bool exists(uint id) {
99         auto itemPtr = id in _sessions;
100 
101         return itemPtr !is null;
102     }
103 }