-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathConnectionOptions.php
651 lines (554 loc) · 19.8 KB
/
ConnectionOptions.php
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
<?php
/**
* ArangoDB PHP client: connection options
*
* @package ArangoDBClient
* @author Jan Steemann
* @copyright Copyright 2012, triagens GmbH, Cologne, Germany
*/
namespace ArangoDBClient;
/**
* Simple container class for connection options.
*
* This class also provides the default values for the connection
* options and will perform a simple validation of them.<br>
* It provides array access to its members.<br>
* <br>
*
* @package ArangoDBClient
* @since 0.2
*/
class ConnectionOptions extends OptionHelper
{
/**
* The index into the endpoints array that we will connect to (or are currently
* connected to). This index will be increased in case the currently connected
* server tells us there is a different leader. We will then simply connect
* to the new leader, adjusting this index. If we don't know the new leader
* we will try the next server from the list of endpoints until we find the leader
* or have tried to often
*
* @var int
*/
private $_currentEndpointIndex = 0;
/**
* Optional Memcached instance for endpoints caching
*
* @var Memcached
*/
private $_cache = null;
/**
* Endpoint string index constant
*/
const OPTION_ENDPOINT = 'endpoint';
/**
* Host name string index constant (deprecated, use endpoint instead)
*/
const OPTION_HOST = 'host';
/**
* Port number index constant (deprecated, use endpoint instead)
*/
const OPTION_PORT = 'port';
/**
* Timeout value index constant
* @deprecated superseded by OPTION_CONNECT_TIMEOUT and OPTION_REQUEST_TIMEOUT
*/
const OPTION_TIMEOUT = 'timeout';
/**
* Connect timeout value index constant
*/
const OPTION_CONNECT_TIMEOUT = 'connectTimeout';
/**
* Request timeout value index constant
*/
const OPTION_REQUEST_TIMEOUT = 'requestTimeout';
/**
* Number of servers tried in case of failover
* if set to 0, then an unlimited amount of servers will be tried
*/
const OPTION_FAILOVER_TRIES = 'failoverTries';
/**
* Max amount of time (in seconds) that is spent waiting on failover
*/
const OPTION_FAILOVER_TIMEOUT = 'failoverTimeout';
/**
* Trace function index constant
*/
const OPTION_TRACE = 'trace';
/**
* "verify certificates" index constant
*/
const OPTION_VERIFY_CERT = 'verifyCert';
/**
* "verify certificate host name" index constant
*/
const OPTION_VERIFY_CERT_NAME = 'verifyCertName';
/**
* "allow self-signed" index constant
*/
const OPTION_ALLOW_SELF_SIGNED = 'allowSelfSigned';
/**
* "caFile" index constant
*/
const OPTION_CA_FILE = 'caFile';
/**
* ciphers allowed to be used in SSL
*/
const OPTION_CIPHERS = 'ciphers';
/**
* Enhanced trace
*/
const OPTION_ENHANCED_TRACE = 'enhancedTrace';
/**
* "Create collections if they don't exist" index constant
*/
const OPTION_CREATE = 'createCollection';
/**
* Update revision constant
*/
const OPTION_REVISION = 'rev';
/**
* Update policy index constant
*/
const OPTION_UPDATE_POLICY = 'policy';
/**
* Update keepNull constant
*/
const OPTION_UPDATE_KEEPNULL = 'keepNull';
/**
* Replace policy index constant
*/
const OPTION_REPLACE_POLICY = 'policy';
/**
* Delete policy index constant
*/
const OPTION_DELETE_POLICY = 'policy';
/**
* Wait for sync index constant
*/
const OPTION_WAIT_SYNC = 'waitForSync';
/**
* Limit index constant
*/
const OPTION_LIMIT = 'limit';
/**
* Skip index constant
*/
const OPTION_SKIP = 'skip';
/**
* Batch size index constant
*/
const OPTION_BATCHSIZE = 'batchSize';
/**
* Wait for sync index constant
*/
const OPTION_IS_SYSTEM = 'isSystem';
/**
* Authentication JWT
*/
const OPTION_AUTH_JWT = 'Jwt';
/**
* Authentication user name
*/
const OPTION_AUTH_USER = 'AuthUser';
/**
* Authentication password
*/
const OPTION_AUTH_PASSWD = 'AuthPasswd';
/**
* Authentication type
*/
const OPTION_AUTH_TYPE = 'AuthType';
/**
* Connection
*/
const OPTION_CONNECTION = 'Connection';
/**
* Reconnect flag
*/
const OPTION_RECONNECT = 'Reconnect';
/**
* Batch flag
*/
const OPTION_BATCH = 'Batch';
/**
* Batchpart flag
*/
const OPTION_BATCHPART = 'BatchPart';
/**
* Database flag
*/
const OPTION_DATABASE = 'database';
/**
* UTF-8 CHeck Flag
*/
const OPTION_CHECK_UTF8_CONFORM = 'CheckUtf8Conform';
/**
* Entry for memcached servers array
*/
const OPTION_MEMCACHED_SERVERS = 'memcachedServers';
/**
* Entry for memcached options array
*/
const OPTION_MEMCACHED_OPTIONS = 'memcachedOptions';
/**
* Entry for memcached endpoints key
*/
const OPTION_MEMCACHED_ENDPOINTS_KEY = 'memcachedEndpointsKey';
/**
* Entry for memcached persistend id
*/
const OPTION_MEMCACHED_PERSISTENT_ID = 'memcachedPersistentId';
/**
* Entry for memcached cache ttl
*/
const OPTION_MEMCACHED_TTL = 'memcachedTtl';
/**
* Entry for notification callback
*/
const OPTION_NOTIFY_CALLBACK = 'notifyCallback';
/**
* Set defaults, use options provided by client and validate them
*
* @param array $options - initial options
*
* @throws \ArangoDBClient\ClientException
*/
final protected function init(array $options) {
$this->values = array_merge(self::getDefaults(), $options);
if (isset($this->values[self::OPTION_ENDPOINT]) &&
!is_array($this->values[self::OPTION_ENDPOINT])) {
$this->values[self::OPTION_ENDPOINT] = [ $this->values[self::OPTION_ENDPOINT] ];
}
$this->loadOptionsFromCache();
}
/**
* Get all options
*
* @return array - all options as an array
*/
public function getAll()
{
return $this->values;
}
/**
* Set and validate a specific option, necessary for ArrayAccess
*
* @throws Exception
*
* @param string $offset - name of option
* @param mixed $value - value for option
*
* @return void
*/
public function offsetSet($offset, $value)
{
$this->values[$offset] = $value;
if ($offset === self::OPTION_CONNECT_TIMEOUT || $offset === self::OPTION_REQUEST_TIMEOUT) {
// special handling for OPTION_TIMEOUT: it will be removed once
// a more specialized option is used
unset($this->values[self::OPTION_TIMEOUT]);
}
$this->validate();
}
/**
* Get the current endpoint to use
*
* @return string - Endpoint string to connect to
*/
public function getCurrentEndpoint()
{
assert(is_array($this->values[self::OPTION_ENDPOINT]));
return $this->values[self::OPTION_ENDPOINT][$this->_currentEndpointIndex];
}
/**
* Whether or not we have multiple endpoints to connect to
*
* @return bool - true if we have more than one endpoint to connect to
*/
public function haveMultipleEndpoints()
{
assert(is_array($this->values[self::OPTION_ENDPOINT]));
return count($this->values[self::OPTION_ENDPOINT]) > 1;
}
/**
* Add a new endpoint to the list of endpoints
* if the endpoint is already in the list, it will not be added again
* as a side-effect, this method will modify _currentEndpointIndex
*
* @param string $endpoint - the endpoint to add
*
* @return void
*/
public function addEndpoint($endpoint)
{
if (!is_string($endpoint) || !Endpoint::isValid($endpoint)) {
throw new ClientException(sprintf("invalid endpoint specification '%s'", $endpoint));
}
$endpoint = Endpoint::normalize($endpoint);
$normalized = Endpoint::normalizeHostname($endpoint);
assert(is_array($this->values[self::OPTION_ENDPOINT]));
$found = false;
foreach ($this->values[self::OPTION_ENDPOINT] as $key => $value) {
if ($normalized === Endpoint::normalizeHostname($value)) {
$this->_currentEndpointIndex = $key;
$found = true;
break;
}
}
if ($found === false) {
// a new endpoint we have not seen before
$this->values[self::OPTION_ENDPOINT][] = $endpoint;
$this->_currentEndpointIndex = count($this->values[self::OPTION_ENDPOINT]) - 1;
}
$this->storeOptionsInCache();
}
/**
* Return the next endpoint from the list of endpoints
* As a side-effect this function switches to a new endpoint
*
* @return string - the next endpoint
*/
public function nextEndpoint()
{
assert(is_array($this->values[self::OPTION_ENDPOINT]));
$endpoints = $this->values[self::OPTION_ENDPOINT];
$numberOfEndpoints = count($endpoints);
$this->_currentEndpointIndex++;
if ($this->_currentEndpointIndex >= $numberOfEndpoints) {
$this->_currentEndpointIndex = 0;
}
$endpoint = $endpoints[$this->_currentEndpointIndex];
if ($numberOfEndpoints > 1) {
$this->storeOptionsInCache();
}
return $endpoint;
}
/**
* Get the default values for the options
*
* @return array - array of default connection options
*/
private static function getDefaults()
{
return [
self::OPTION_ENDPOINT => [ ],
self::OPTION_HOST => null,
self::OPTION_PORT => DefaultValues::DEFAULT_PORT,
self::OPTION_FAILOVER_TRIES => DefaultValues::DEFAULT_FAILOVER_TRIES,
self::OPTION_FAILOVER_TIMEOUT => DefaultValues::DEFAULT_FAILOVER_TIMEOUT,
self::OPTION_CONNECT_TIMEOUT => DefaultValues::DEFAULT_CONNECT_TIMEOUT,
self::OPTION_REQUEST_TIMEOUT => DefaultValues::DEFAULT_REQUEST_TIMEOUT,
self::OPTION_MEMCACHED_PERSISTENT_ID => 'arangodb-php-pool',
self::OPTION_MEMCACHED_OPTIONS => [ ],
self::OPTION_MEMCACHED_ENDPOINTS_KEY => 'arangodb-php-endpoints',
self::OPTION_MEMCACHED_TTL => 600,
self::OPTION_CREATE => DefaultValues::DEFAULT_CREATE,
self::OPTION_UPDATE_POLICY => DefaultValues::DEFAULT_UPDATE_POLICY,
self::OPTION_REPLACE_POLICY => DefaultValues::DEFAULT_REPLACE_POLICY,
self::OPTION_DELETE_POLICY => DefaultValues::DEFAULT_DELETE_POLICY,
self::OPTION_REVISION => null,
self::OPTION_WAIT_SYNC => DefaultValues::DEFAULT_WAIT_SYNC,
self::OPTION_BATCHSIZE => null,
self::OPTION_IS_SYSTEM => false,
self::OPTION_CONNECTION => DefaultValues::DEFAULT_CONNECTION,
self::OPTION_TRACE => null,
self::OPTION_ENHANCED_TRACE => false,
self::OPTION_VERIFY_CERT => DefaultValues::DEFAULT_VERIFY_CERT,
self::OPTION_VERIFY_CERT_NAME => DefaultValues::DEFAULT_VERIFY_CERT_NAME,
self::OPTION_ALLOW_SELF_SIGNED => DefaultValues::DEFAULT_ALLOW_SELF_SIGNED,
self::OPTION_CA_FILE => null,
self::OPTION_CIPHERS => DefaultValues::DEFAULT_CIPHERS,
self::OPTION_AUTH_USER => null,
self::OPTION_AUTH_PASSWD => null,
self::OPTION_AUTH_TYPE => DefaultValues::DEFAULT_AUTH_TYPE,
self::OPTION_RECONNECT => false,
self::OPTION_BATCH => false,
self::OPTION_BATCHPART => false,
self::OPTION_DATABASE => '_system',
self::OPTION_CHECK_UTF8_CONFORM => DefaultValues::DEFAULT_CHECK_UTF8_CONFORM,
self::OPTION_NOTIFY_CALLBACK => function ($message) {}
];
}
/**
* Return the supported authorization types
*
* @return array - array with supported authorization types
*/
private static function getSupportedAuthTypes()
{
return ['Basic', 'Bearer'];
}
/**
* Return the supported connection types
*
* @return array - array with supported connection types
*/
private static function getSupportedConnectionTypes()
{
return ['Close', 'Keep-Alive'];
}
/**
* Validate the options
*
* @throws ClientException
* @return void - will throw if an invalid option value is found
*/
final protected function validate()
{
if (isset($this->values[self::OPTION_HOST]) && !is_string($this->values[self::OPTION_HOST])) {
throw new ClientException('host should be a string');
}
if (isset($this->values[self::OPTION_PORT]) && !is_int($this->values[self::OPTION_PORT])) {
throw new ClientException('port should be an integer');
}
// can use either endpoint or host/port
if (isset($this->values[self::OPTION_HOST], $this->values[self::OPTION_ENDPOINT])) {
throw new ClientException('must not specify both host and endpoint');
}
if (isset($this->values[self::OPTION_HOST]) && !isset($this->values[self::OPTION_ENDPOINT])) {
// upgrade host/port to an endpoint
$this->values[self::OPTION_ENDPOINT] = [ 'tcp://' . $this->values[self::OPTION_HOST] . ':' . $this->values[self::OPTION_PORT] ];
unset($this->values[self::OPTION_HOST]);
}
if (!is_array($this->values[self::OPTION_ENDPOINT])) {
// make sure that we always have an array of endpoints
$this->values[self::OPTION_ENDPOINT] = [ $this->values[self::OPTION_ENDPOINT] ];
}
assert(is_array($this->values[self::OPTION_ENDPOINT]));
foreach ($this->values[self::OPTION_ENDPOINT] as $key => $value) {
$this->values[self::OPTION_ENDPOINT][$key] = Endpoint::normalize($value);
}
if (count($this->values[self::OPTION_ENDPOINT]) > 1) {
// when we have more than a single endpoint, we must always use the reconnect option
$this->values[ConnectionOptions::OPTION_RECONNECT] = true;
}
// validate endpoint
$ep = $this->getCurrentEndpoint();
if (!Endpoint::isValid($ep)) {
throw new ClientException(sprintf("invalid endpoint specification '%s'", $ep));
}
$type = Endpoint::getType($ep);
if ($type === Endpoint::TYPE_UNIX) {
// must set port to 0 for UNIX domain sockets
$this->values[self::OPTION_PORT] = 0;
} elseif ($type === Endpoint::TYPE_SSL) {
// must set port to 0 for SSL connections
$this->values[self::OPTION_PORT] = 0;
} else {
if (preg_match("/:(\d+)$/", $ep, $match)) {
// get port number from endpoint, to not confuse developers when dumping
// connection details
$this->values[self::OPTION_PORT] = (int) $match[1];
}
}
if (isset($this->values[self::OPTION_AUTH_TYPE]) && !in_array(
$this->values[self::OPTION_AUTH_TYPE],
self::getSupportedAuthTypes(), true
)
) {
throw new ClientException('unsupported authorization method');
}
if (isset($this->values[self::OPTION_CONNECTION]) && !in_array(
$this->values[self::OPTION_CONNECTION],
self::getSupportedConnectionTypes(), true
)
) {
throw new ClientException(
sprintf(
"unsupported connection value '%s'",
$this->values[self::OPTION_CONNECTION]
)
);
}
if (isset($this->values[self::OPTION_TIMEOUT])) {
// propagate values from OPTION_TIMOEUT into OPTION_CONNECT_TIMEOUT and OPTION_REQUEST_TIMEOUT
$this->values[self::OPTION_CONNECT_TIMEOUT] = (float) $this->values[self::OPTION_TIMEOUT];
$this->values[self::OPTION_REQUEST_TIMEOUT] = (float) $this->values[self::OPTION_TIMEOUT];
}
UpdatePolicy::validate($this->values[self::OPTION_UPDATE_POLICY]);
UpdatePolicy::validate($this->values[self::OPTION_REPLACE_POLICY]);
UpdatePolicy::validate($this->values[self::OPTION_DELETE_POLICY]);
}
/**
* load and merge connection options from optional Memcached cache into
* ihe current settings
*
* @return void
*/
private function loadOptionsFromCache()
{
$cache = $this->getEndpointsCache();
if ($cache === null) {
return;
}
$endpoints = $cache->get($this->values[self::OPTION_MEMCACHED_ENDPOINTS_KEY]);
if ($endpoints) {
$this->values[self::OPTION_ENDPOINT] = $endpoints;
if (!is_array($this->values[self::OPTION_ENDPOINT])) {
$this->values[self::OPTION_ENDPOINT] = [ $this->values[self::OPTION_ENDPOINT] ];
}
}
}
/**
* store the updated options in the optional Memcached cache
*
* @return void
*/
private function storeOptionsInCache()
{
$endpoints = $this->values[self::OPTION_ENDPOINT];
$numberOfEndpoints = count($endpoints);
if ($numberOfEndpoints <= 1) {
return;
}
// now try to store the updated values in the cache
$cache = $this->getEndpointsCache();
if ($cache === null) {
return;
}
$update = [ $endpoints[$this->_currentEndpointIndex] ];
for ($i = 0; $i < $numberOfEndpoints; ++$i) {
if ($i !== $this->_currentEndpointIndex) {
$update[] = $endpoints[$i];
}
}
$ttl = (int) $this->values[self::OPTION_MEMCACHED_TTL];
$cache->set($this->values[self::OPTION_MEMCACHED_ENDPOINTS_KEY], $update, $ttl);
}
/**
* Initialize and return a memcached cache instance,
* if option "memcachedServers" is set
*
* @return Memcached - memcached server instance if configured or null if not
*/
private function getEndpointsCache()
{
if ($this->_cache === null) {
if (!isset($this->values[self::OPTION_MEMCACHED_SERVERS])) {
return null;
}
if (!class_exists('Memcached', false)) {
return null;
}
$servers = $this->values[self::OPTION_MEMCACHED_SERVERS];
if (!is_array($servers)) {
throw new ClientException('Invalid memcached servers list. should be an array of servers');
}
$cache = new \Memcached(self::OPTION_MEMCACHED_PERSISTENT_ID);
if (empty($cache->getServerList())) {
$cache->addServers($servers);
}
if (isset($this->values[self::OPTION_MEMCACHED_OPTIONS])) {
$options = $this->values[self::OPTION_MEMCACHED_OPTIONS];
if (!is_array($options)) {
throw new ClientException('Invalid memcached options list. should be an array of options');
}
$cache->setOptions($options);
}
$this->_cache = $cache;
}
return $this->_cache;
}
}
class_alias(ConnectionOptions::class, '\triagens\ArangoDb\ConnectionOptions');