- Notifications
You must be signed in to change notification settings - Fork 255
/
Copy pathsession.h
489 lines (374 loc) · 11.6 KB
/
session.h
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
/*
* Copyright (c) 2015, 2024, Oracle and/or its affiliates.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0, as
* published by the Free Software Foundation.
*
* This program is designed to work with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms, as
* designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an additional
* permission to link the program and your derivative works with the
* separately licensed software that they have either included with
* the program or referenced in the documentation.
*
* Without limiting anything contained in the foregoing, this file,
* which is part of Connector/C++, is also subject to the
* Universal FOSS Exception, version 1.0, a copy of which can be found at
* https://oss.oracle.com/licenses/universal-foss-exception.
*
* This program 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, version 2.0, for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MYSQLX_COMMON_SESSION_INT_H
#defineMYSQLX_COMMON_SESSION_INT_H
/*
Internal implementations for public DevAPI classes.
*/
#include"common.h"
#include<mysql/cdk.h>
PUSH_SYS_WARNINGS
#include<chrono>
#include<list>
#include<mutex>
#include<condition_variable>
#include<mutex>
POP_SYS_WARNINGS
namespacemysqlx {
namespaceimpl {
namespacecommon {
using duration = std::chrono::milliseconds;
using system_clock = std::chrono::system_clock;
using time_point = std::chrono::time_point<system_clock>;
/*
Session pooling
*/
/*
Abstract interface used to clean up a session before it is closed.
Also has methods to aquire lock and try_lock, so that Session pool can clean
on multi thread environment.
*/
structSession_cleanup
{
virtualvoidcleanup() = 0;
virtual std::unique_lock<std::recursive_mutex> lock() const = 0;
virtual std::unique_lock<std::recursive_mutex> try_lock() const = 0;
};
/*
Wraps a shared pointer to a CDK session that was created and is managed
by a session pool.
Pooled_session acts as an asynchronous operation. After construction one has
to wait until it is completed -- only then the session is available.
*/
classPooled_session
: public cdk::foundation::api::Async_op<void>
, public std::shared_ptr<cdk::Session>
{
Session_pool_shared m_sess_pool;
time_point m_deadline;
Session_cleanup *m_cleanup = nullptr;
public:
/*
Get a session from the given pool, registering a cleanup handler to be
called if the pool decides to close this session.
*/
Pooled_session(Session_pool_shared &pool, Session_cleanup *cleanup = nullptr);
Pooled_session(cdk::ds::Multi_source &ds);
~Pooled_session() override;
boolis_completed() constoverride;
booldo_cont() override;
voiddo_wait() override;
voiddo_cancel() override;
const cdk::foundation::api::Event_info* get_event_info() constoverride;
voidrelease();
private:
friendclassSession_pool;
};
} // common
} // impl
MYSQLX_ABI_BEGIN(2,0)
namespacecommon {
using impl::common::duration;
using impl::common::time_point;
using impl::common::system_clock;
using impl::common::Pooled_session;
using impl::common::Session_cleanup;
/*
Note: This class must be defined inside ABI namespace to preserve ABI
compatibility (its name is used in public API)
*/
classSession_pool
{
public:
Session_pool(cdk::ds::Multi_source &ds);
~Session_pool();
voidclose();
voidset_pool_opts(Settings_impl &opts);
voidset_pooling(bool x)
{
m_pool_enable = x;
}
voidset_size(size_t sz)
{
assert(sz > 0);
m_max = sz;
}
voidset_timeout(uint64_t ms)
{
if (!check_num_limits<int64_t>(ms))
common::throw_error("Timeout value too big!");
m_timeout = duration(static_cast<int64_t>(ms));
}
voidset_time_to_live(uint64_t ms)
{
if (!check_num_limits<int64_t>(ms))
common::throw_error("MaxIdleTime value too big!");
m_time_to_live = duration(static_cast<int64_t>(ms));
}
protected:
voidrelease_session(std::shared_ptr<cdk::Session> &sess);
/*
Returns Session if possible (available). Throws error if the pool is closed.
If cleanup handler is given, it will be called in case this session needs
to be closed while in use (for example, when pool is closed).
*/
std::shared_ptr<cdk::Session> get_session(Session_cleanup* = nullptr);
/*
Return an available session from the pool (not currently in use) if such session
can be found. If `apply_block_list` is true then sessions whose endpoints are on
the balck-list are not considered. On success, installs given cleanup handler for
the returned session. Returns null pointer if good session could not be found in
the pool.
*/
std::shared_ptr<cdk::Session>
get_pooled_session(bool apply_block_list, std::default_random_engine&, Session_cleanup*);
/*
Try re-using a session that is in the pool. If this fails for whatever reason,
the session is removed from the pool, it's connection endpoint is put on the
block list and a null pointer is returned. In case of success, the given cleanup
handler is installed for the session and the session is returned by the method.
Note: The session passed as the first argument should be taken from the pool.
*/
std::shared_ptr<cdk::Session>
try_session(std::shared_ptr<cdk::Session> &sess,
Session_cleanup* = nullptr);
voidtime_to_live_cleanup();
cdk::ds::Multi_source m_ds;
bool m_pool_enable = true;
bool m_pool_closed = false;
size_t m_max = 25;
duration m_timeout = std::chrono::minutes(10);
duration m_time_to_live = std::chrono::minutes(10);
classBlock_list
{
std::map<size_t, time_point> m_list;
// The Block List timeout is fixed at 60s
const duration m_timeout = std::chrono::seconds(60);
public:
/*
Add an endpoint to a block list.
If the endpoint is already block-listed the timeout is extended.
*/
voidadd(size_t id)
{
m_list[id] = system_clock::now() + m_timeout;
}
voidremove(size_t id)
{
m_list.erase(id);
}
boolis_block_listed(size_t id)
{
if (m_list.find(id) == m_list.end())
returnfalse;
time_point deadline = m_list[id];
if (system_clock::now() < deadline)
returntrue;
// Remove end-point from the list
m_list.erase(id);
returnfalse;
}
~Block_list()
{
m_list.clear();
}
};
Block_list m_block_list;
structSess_data {
time_point m_deadline;
Session_cleanup *m_cleanup;
};
std::map<cdk::shared_ptr<cdk::Session>, Sess_data> m_pool;
std::recursive_mutex m_pool_mutex;
std::mutex m_reelase_mutex;
std::condition_variable m_release_cond;
friend Pooled_session;
};
/*
Internal implementation for Session objects.
Note: This class must be defined inside ABI namespace to preserve ABI
compatibility (its name is used in public API)
TODO: Add transaction methods here?
*/
classSession_impl
: public Session_cleanup
{
public:
using string = cdk::string;
Pooled_session m_sess;
string m_default_db;
std::set<uint32_t> m_stmt_id;
std::set<uint32_t> m_stmt_id_cleanup;
size_t m_max_pstmt = std::numeric_limits<size_t>::max();
std::recursive_mutex m_mutex;
Session_impl(Session_pool_shared &pool)
: m_sess(pool, this)
{
m_sess.wait();
if (m_sess->get_default_schema())
m_default_db = *m_sess->get_default_schema();
if (!m_sess->is_valid())
m_sess->get_error().rethrow();
}
Session_impl(cdk::ds::Multi_source &ms)
: m_sess(ms)
{
if (m_sess->get_default_schema())
m_default_db = *m_sess->get_default_schema();
if (!m_sess->is_valid())
m_sess->get_error().rethrow();
}
Result_impl *m_current_result = nullptr;
virtual~Session_impl()
{
/*
There should be no registered results when session implementation is
deleted because:
- each result has a shared pointer to session implementation,
- session implementation is deleted only when the last result referring
to it is deleted
- results de-register themselves before being destroyed.
*/
assert(!m_current_result);
// TODO: rollback an on-going transaction, if any?
}
/*
Result objects should register itself with the session and de-register
when all result data is consumed (this is also the case when result object
is deleted).
*/
voidregister_result(Result_impl *result)
{
assert(!m_current_result);
m_current_result = result;
}
voidderegister_result(Result_impl *result)
{
if (result == m_current_result)
m_current_result = nullptr;
}
/*
Prepare session for sending new command. This caches the current result,
if one is registered with session.
*/
voidprepare_for_cmd();
unsignedlong m_savepoint = 0;
unsignedlongnext_savepoint()
{
return ++m_savepoint;
}
/*
Return a non-used prepared statement id. If possible, re-uses previously
allocated ids that are no longer in use.
Returns 0 if prepared statements are not available at the moment.
*/
uint32_tcreate_stmt_id()
{
/*
If server doesn't support PS or or we reached server max PS (value set on
m_max_pstmt when a error occur on prepare), it will return 0, so no PS
possible.
*/
if (m_sess->has_prepared_statements().state() == cdk::option_t::NO ||
m_stmt_id.size() >= m_max_pstmt)
return0;
uint32_t val = 1;
if (!m_stmt_id_cleanup.empty())
{
//Use one that was freed
val = *m_stmt_id_cleanup.begin();
m_stmt_id.insert(val);
m_stmt_id_cleanup.erase(m_stmt_id_cleanup.begin());
//And clean up the others!
clean_up_stmt_id();
}
elseif (m_stmt_id.empty())
{
m_stmt_id.insert(val);
}
else
{
val = (*m_stmt_id.rbegin()) + 1;
m_stmt_id.insert(val);
}
return val;
}
/*
To be called when given PS id is no longer used.
*/
voidrelease_stmt_id(uint32_t id)
{
m_stmt_id.erase(id);
m_stmt_id_cleanup.insert(id);
}
/*
To be called when, while trying to use given PS, we have detected that the
server can not handle more PS.
*/
voiderror_stmt_id(uint32_t id)
{
m_stmt_id.erase(id);
m_max_pstmt = m_stmt_id.size();
}
/*
Send commands to server to deallocate PS ids that are no longer in use.
*/
voidclean_up_stmt_id()
{
if (m_stmt_id_cleanup.empty())
return;
m_sess->set_has_prepared_statements(true);
for (auto id : m_stmt_id_cleanup)
{
cdk::Reply(m_sess->prepared_deallocate(id)).wait();
}
m_stmt_id_cleanup.clear();
}
voidrelease();
/*
Implement Session_cleanup
*/
voidcleanup() override
{
prepare_for_cmd();
}
std::unique_lock<std::recursive_mutex> lock() constoverride {
return std::unique_lock<std::recursive_mutex>(
const_cast<Session_impl *>(this)->m_mutex);
}
std::unique_lock<std::recursive_mutex> try_lock() constoverride {
return std::unique_lock<std::recursive_mutex>(
const_cast<Session_impl *>(this)->m_mutex, std::try_to_lock);
}
};
} // common
MYSQLX_ABI_END(2,0)
} // mysqlx namespace
#endif