18
18
*/
19
19
20
20
import Session from './session' ;
21
+ import { Pool } from './internal/pool' ;
21
22
import { connect } from "./internal/connector" ;
22
23
23
24
/**
@@ -37,24 +38,74 @@ class Driver {
37
38
this . _openSessions = { } ;
38
39
this . _sessionIdGenerator = 0 ;
39
40
this . _token = token || { } ;
41
+ this . _pool = new Pool (
42
+ this . _createConnection . bind ( this ) ,
43
+ this . _destroyConnection . bind ( this ) ,
44
+ this . _validateConnection . bind ( this )
45
+ ) ;
40
46
}
41
47
42
48
/**
43
- * Create and return new session
44
- * @return {Session } new session.
49
+ * Create a new connection instance.
50
+ * @return {Connection } new connector-api session instance, a low level session API.
51
+ * @access private
45
52
*/
46
- session ( ) {
53
+ _createConnection ( release ) {
47
54
let sessionId = this . _sessionIdGenerator ++ ;
48
55
let conn = connect ( this . _url ) ;
49
56
conn . initialize ( this . _userAgent , this . _token ) ;
50
- let _driver = this ;
51
- let _session = new Session ( conn , ( ) => {
52
- // On close of session, remove it from the list of open sessions
53
- delete _driver . _openSessions [ sessionId ] ;
54
- } ) ;
57
+ conn . _id = sessionId ;
58
+ conn . _release = ( ) => release ( conn ) ;
59
+
60
+ this . _openSessions [ sessionId ] = conn ;
61
+ return conn ;
62
+ }
63
+
64
+ /**
65
+ * Check that a connection is usable
66
+ * @return {boolean } true if the connection is open
67
+ * @access private
68
+ **/
69
+ _validateConnection ( conn ) {
70
+ return conn . isOpen ( ) ;
71
+ }
72
+
73
+ /**
74
+ * Dispose of a live session, closing any associated resources.
75
+ * @return {Session } new session.
76
+ * @access private
77
+ */
78
+ _destroyConnection ( conn ) {
79
+ delete this . _openSessions [ conn . _id ] ;
80
+ conn . close ( ) ;
81
+ }
82
+
83
+ /**
84
+ * Create and return new session
85
+ * @return {Session } new session.
86
+ */
87
+ session ( ) {
88
+ let conn = this . _pool . acquire ( ) ;
89
+ return new Session ( conn , ( cb ) => {
90
+ // This gets called on Session#close(), and is where we return
91
+ // the pooled 'connection' instance.
92
+
93
+ // We don't pool Session instances, to avoid users using the Session
94
+ // after they've called close. The `Session` object is just a thin
95
+ // wrapper around Connection anyway, so it makes little difference.
55
96
56
- this . _openSessions [ sessionId ] = _session ;
57
- return _session ;
97
+ // Queue up a 'reset', to ensure the next user gets a clean
98
+ // session to work with. No need to flush, this will get sent
99
+ // along with whatever the next thing the user wants to do with
100
+ // this session ends up being, so we save the network round trip.
101
+ conn . reset ( ) ;
102
+
103
+ // Return connection to the pool
104
+ conn . _release ( ) ;
105
+
106
+ // Call user callback
107
+ if ( cb ) { cb ( ) ; }
108
+ } ) ;
58
109
}
59
110
60
111
/**
0 commit comments