fdb 5.1.5
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/LICENSE +207 -0
- data/lib/fdb.rb +71 -0
- data/lib/fdbdirectory.rb +689 -0
- data/lib/fdbimpl.rb +1017 -0
- data/lib/fdblocality.rb +83 -0
- data/lib/fdboptions.rb +129 -0
- data/lib/fdbsubspace.rb +71 -0
- data/lib/fdbtuple.rb +307 -0
- metadata +71 -0
data/lib/fdblocality.rb
ADDED
@@ -0,0 +1,83 @@
|
|
1
|
+
#encoding: BINARY
|
2
|
+
|
3
|
+
#
|
4
|
+
# fdblocality.rb
|
5
|
+
#
|
6
|
+
# This source file is part of the FoundationDB open source project
|
7
|
+
#
|
8
|
+
# Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
|
9
|
+
#
|
10
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11
|
+
# you may not use this file except in compliance with the License.
|
12
|
+
# You may obtain a copy of the License at
|
13
|
+
#
|
14
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15
|
+
#
|
16
|
+
# Unless required by applicable law or agreed to in writing, software
|
17
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19
|
+
# See the License for the specific language governing permissions and
|
20
|
+
# limitations under the License.
|
21
|
+
#
|
22
|
+
|
23
|
+
# FoundationDB Ruby API
|
24
|
+
|
25
|
+
# Documentation for this API can be found at
|
26
|
+
# https://www.foundationdb.org/documentation/api-ruby.html
|
27
|
+
|
28
|
+
module FDB
|
29
|
+
module Locality
|
30
|
+
def self.get_addresses_for_key(db_or_tr, key)
|
31
|
+
key = FDB.key_to_bytes(key)
|
32
|
+
db_or_tr.transact do |tr|
|
33
|
+
FutureStringArray.new(FDBC.fdb_transaction_get_addresses_for_key(tr.tpointer, key, key.bytesize))
|
34
|
+
end
|
35
|
+
end
|
36
|
+
|
37
|
+
def self.get_boundary_keys(db_or_tr, bkey, ekey)
|
38
|
+
bkey = FDB.key_to_bytes(bkey).dup.force_encoding('BINARY')
|
39
|
+
ekey = FDB.key_to_bytes(ekey).dup.force_encoding('BINARY')
|
40
|
+
|
41
|
+
if db_or_tr.is_a? Transaction
|
42
|
+
tr = db_or_tr.db.create_transaction
|
43
|
+
tr.set_read_version db_or_tr.get_read_version
|
44
|
+
else
|
45
|
+
tr = db_or_tr.create_transaction
|
46
|
+
end
|
47
|
+
|
48
|
+
tr.options.set_read_system_keys
|
49
|
+
tr.options.set_lock_aware
|
50
|
+
lastbkey = bkey
|
51
|
+
kvs = tr.snapshot.get_range("\xff/keyServers/"+bkey, "\xff/keyServers/"+ekey)
|
52
|
+
|
53
|
+
y = Enumerator.new do |yielder|
|
54
|
+
_tr = tr
|
55
|
+
_bkey = bkey
|
56
|
+
_ekey = ekey
|
57
|
+
_lastbkey = lastbkey
|
58
|
+
_kvs = kvs
|
59
|
+
while _bkey < _ekey
|
60
|
+
begin
|
61
|
+
_kvs.each do |kv|
|
62
|
+
yielder.yield kv.key.byteslice(13..-1)
|
63
|
+
_bkey = kv.key.byteslice(13..-1) + "\x00"
|
64
|
+
end
|
65
|
+
_bkey = _ekey
|
66
|
+
rescue FDB::Error => e
|
67
|
+
if e.code == 1007 and _bkey != _lastbkey # if we get a past_version and *something* has happened, then we are no longer transactional
|
68
|
+
_tr = _tr.db.create_transaction
|
69
|
+
else
|
70
|
+
_tr.on_error(e).wait
|
71
|
+
end
|
72
|
+
# we either created a new transaction or (implicitly) reset the one we had...
|
73
|
+
_tr.options.set_read_system_keys
|
74
|
+
_lastbkey = _bkey
|
75
|
+
_kvs = _tr.snapshot.get_range("\xff/keyServers/" + _bkey, "\xff/keyServers/" + _ekey)
|
76
|
+
end
|
77
|
+
end
|
78
|
+
end
|
79
|
+
|
80
|
+
return y
|
81
|
+
end
|
82
|
+
end
|
83
|
+
end
|
data/lib/fdboptions.rb
ADDED
@@ -0,0 +1,129 @@
|
|
1
|
+
# FoundationDB Ruby API
|
2
|
+
# Copyright (c) 2013-2017 Apple Inc.
|
3
|
+
|
4
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
5
|
+
# of this software and associated documentation files (the "Software"), to deal
|
6
|
+
# in the Software without restriction, including without limitation the rights
|
7
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
8
|
+
# copies of the Software, and to permit persons to whom the Software is
|
9
|
+
# furnished to do so, subject to the following conditions:
|
10
|
+
|
11
|
+
# The above copyright notice and this permission notice shall be included in
|
12
|
+
# all copies or substantial portions of the Software.
|
13
|
+
|
14
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
15
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
16
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
17
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
18
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
19
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
20
|
+
# THE SOFTWARE.
|
21
|
+
|
22
|
+
# Documentation for this API can be found at
|
23
|
+
# https://www.foundationdb.org/documentation/api-ruby.html
|
24
|
+
|
25
|
+
module FDB
|
26
|
+
@@NetworkOption = {
|
27
|
+
"LOCAL_ADDRESS" => [10, "Deprecated", '', "IP:PORT"],
|
28
|
+
"CLUSTER_FILE" => [20, "Deprecated", '', "path to cluster file"],
|
29
|
+
"TRACE_ENABLE" => [30, "Enables trace output to a file in a directory of the clients choosing", '', "path to output directory (or NULL for current working directory)"],
|
30
|
+
"TRACE_ROLL_SIZE" => [31, "Sets the maximum size in bytes of a single trace output file. This value should be in the range ``[0, INT64_MAX]``. If the value is set to 0, there is no limit on individual file size. The default is a maximum size of 10,485,760 bytes.", 0, "max size of a single trace output file"],
|
31
|
+
"TRACE_MAX_LOGS_SIZE" => [32, "Sets the maximum size of all the trace output files put together. This value should be in the range ``[0, INT64_MAX]``. If the value is set to 0, there is no limit on the total size of the files. The default is a maximum size of 104,857,600 bytes. If the default roll size is used, this means that a maximum of 10 trace files will be written at a time.", 0, "max total size of trace files"],
|
32
|
+
"TRACE_LOG_GROUP" => [33, "Sets the 'logGroup' attribute with the specified value for all events in the trace output files. The default log group is 'default'.", '', "value of the logGroup attribute"],
|
33
|
+
"KNOB" => [40, "Set internal tuning or debugging knobs", '', "knob_name=knob_value"],
|
34
|
+
"TLS_PLUGIN" => [41, "Set the TLS plugin to load. This option, if used, must be set before any other TLS options", '', "file path or linker-resolved name"],
|
35
|
+
"TLS_CERT_BYTES" => [42, "Set the certificate chain", '', "certificates"],
|
36
|
+
"TLS_CERT_PATH" => [43, "Set the file from which to load the certificate chain", '', "file path"],
|
37
|
+
"TLS_KEY_BYTES" => [45, "Set the private key corresponding to your own certificate", '', "key"],
|
38
|
+
"TLS_KEY_PATH" => [46, "Set the file from which to load the private key corresponding to your own certificate", '', "file path"],
|
39
|
+
"TLS_VERIFY_PEERS" => [47, "Set the peer certificate field verification criteria", '', "verification pattern"],
|
40
|
+
"BUGGIFY_ENABLE" => [48, "", nil, nil],
|
41
|
+
"BUGGIFY_DISABLE" => [49, "", nil, nil],
|
42
|
+
"BUGGIFY_SECTION_ACTIVATED_PROBABILITY" => [50, "Set the probability of a BUGGIFY section being active for the current execution. Only applies to code paths first traversed AFTER this option is changed.", 0, "probability expressed as a percentage between 0 and 100"],
|
43
|
+
"BUGGIFY_SECTION_FIRED_PROBABILITY" => [51, "Set the probability of an active BUGGIFY section being fired", 0, "probability expressed as a percentage between 0 and 100"],
|
44
|
+
"DISABLE_MULTI_VERSION_CLIENT_API" => [60, "Disables the multi-version client API and instead uses the local client directly. Must be set before setting up the network.", nil, nil],
|
45
|
+
"CALLBACKS_ON_EXTERNAL_THREADS" => [61, "If set, callbacks from external client libraries can be called from threads created by the FoundationDB client library. Otherwise, callbacks will be called from either the thread used to add the callback or the network thread. Setting this option can improve performance when connected using an external client, but may not be safe to use in all environments. Must be set before setting up the network. WARNING: This feature is considered experimental at this time. ", nil, nil],
|
46
|
+
"EXTERNAL_CLIENT_LIBRARY" => [62, "Adds an external client library for use by the multi-version client API. Must be set before setting up the network.", '', "path to client library"],
|
47
|
+
"EXTERNAL_CLIENT_DIRECTORY" => [63, "Searches the specified path for dynamic libraries and adds them to the list of client libraries for use by the multi-version client API. Must be set before setting up the network.", '', "path to directory containing client libraries"],
|
48
|
+
"DISABLE_LOCAL_CLIENT" => [64, "Prevents connections through the local client, allowing only connections through externally loaded client libraries. Intended primarily for testing.", nil, nil],
|
49
|
+
"DISABLE_CLIENT_STATISTICS_LOGGING" => [70, "Disables logging of client statistics, such as sampled transaction activity.", nil, nil],
|
50
|
+
"ENABLE_SLOW_TASK_PROFILING" => [71, "Enables debugging feature to perform slow task profiling. Requires trace logging to be enabled. WARNING: this feature is not recommended for use in production.", nil, nil],
|
51
|
+
}
|
52
|
+
|
53
|
+
@@ClusterOption = {
|
54
|
+
|
55
|
+
}
|
56
|
+
|
57
|
+
@@DatabaseOption = {
|
58
|
+
"LOCATION_CACHE_SIZE" => [10, "Set the size of the client location cache. Raising this value can boost performance in very large databases where clients access data in a near-random pattern. Defaults to 100000.", 0, "Max location cache entries"],
|
59
|
+
"MAX_WATCHES" => [20, "Set the maximum number of watches allowed to be outstanding on a database connection. Increasing this number could result in increased resource usage. Reducing this number will not cancel any outstanding watches. Defaults to 10000 and cannot be larger than 1000000.", 0, "Max outstanding watches"],
|
60
|
+
"MACHINE_ID" => [21, "Specify the machine ID that was passed to fdbserver processes running on the same machine as this client, for better location-aware load balancing.", '', "Hexadecimal ID"],
|
61
|
+
"DATACENTER_ID" => [22, "Specify the datacenter ID that was passed to fdbserver processes running in the same datacenter as this client, for better location-aware load balancing.", '', "Hexadecimal ID"],
|
62
|
+
}
|
63
|
+
|
64
|
+
@@TransactionOption = {
|
65
|
+
"CAUSAL_WRITE_RISKY" => [10, "The transaction, if not self-conflicting, may be committed a second time after commit succeeds, in the event of a fault", nil, nil],
|
66
|
+
"CAUSAL_READ_RISKY" => [20, "The read version will be committed, and usually will be the latest committed, but might not be the latest committed in the event of a fault or partition", nil, nil],
|
67
|
+
"CAUSAL_READ_DISABLE" => [21, "", nil, nil],
|
68
|
+
"NEXT_WRITE_NO_WRITE_CONFLICT_RANGE" => [30, "The next write performed on this transaction will not generate a write conflict range. As a result, other transactions which read the key(s) being modified by the next write will not conflict with this transaction. Care needs to be taken when using this option on a transaction that is shared between multiple threads. When setting this option, write conflict ranges will be disabled on the next write operation, regardless of what thread it is on.", nil, nil],
|
69
|
+
"COMMIT_ON_FIRST_PROXY" => [40, "Committing this transaction will bypass the normal load balancing across proxies and go directly to the specifically nominated 'first proxy'.", nil, nil],
|
70
|
+
"CHECK_WRITES_ENABLE" => [50, "", nil, nil],
|
71
|
+
"READ_YOUR_WRITES_DISABLE" => [51, "Reads performed by a transaction will not see any prior mutations that occured in that transaction, instead seeing the value which was in the database at the transaction's read version. This option may provide a small performance benefit for the client, but also disables a number of client-side optimizations which are beneficial for transactions which tend to read and write the same keys within a single transaction.", nil, nil],
|
72
|
+
"READ_AHEAD_DISABLE" => [52, "Disables read-ahead caching for range reads. Under normal operation, a transaction will read extra rows from the database into cache if range reads are used to page through a series of data one row at a time (i.e. if a range read with a one row limit is followed by another one row range read starting immediately after the result of the first).", nil, nil],
|
73
|
+
"DURABILITY_DATACENTER" => [110, "", nil, nil],
|
74
|
+
"DURABILITY_RISKY" => [120, "", nil, nil],
|
75
|
+
"DURABILITY_DEV_NULL_IS_WEB_SCALE" => [130, "", nil, nil],
|
76
|
+
"PRIORITY_SYSTEM_IMMEDIATE" => [200, "Specifies that this transaction should be treated as highest priority and that lower priority transactions should block behind this one. Use is discouraged outside of low-level tools", nil, nil],
|
77
|
+
"PRIORITY_BATCH" => [201, "Specifies that this transaction should be treated as low priority and that default priority transactions should be processed first. Useful for doing batch work simultaneously with latency-sensitive work", nil, nil],
|
78
|
+
"INITIALIZE_NEW_DATABASE" => [300, "This is a write-only transaction which sets the initial configuration. This option is designed for use by database system tools only.", nil, nil],
|
79
|
+
"ACCESS_SYSTEM_KEYS" => [301, "Allows this transaction to read and modify system keys (those that start with the byte 0xFF)", nil, nil],
|
80
|
+
"READ_SYSTEM_KEYS" => [302, "Allows this transaction to read system keys (those that start with the byte 0xFF)", nil, nil],
|
81
|
+
"DEBUG_DUMP" => [400, "", nil, nil],
|
82
|
+
"DEBUG_RETRY_LOGGING" => [401, "", '', "Optional transaction name"],
|
83
|
+
"TRANSACTION_LOGGING_ENABLE" => [402, "Enables tracing for this transaction and logs results to the client trace logs. Client trace logging must be enabled to get log output.", '', "String identifier to be used in the logs when tracing this transaction. The identifier must not exceed 100 characters."],
|
84
|
+
"TIMEOUT" => [500, "Set a timeout in milliseconds which, when elapsed, will cause the transaction automatically to be cancelled. Valid parameter values are ``[0, INT_MAX]``. If set to 0, will disable all timeouts. All pending and any future uses of the transaction will throw an exception. The transaction can be used again after it is reset. Like all transaction options, a timeout must be reset after a call to onError. This behavior allows the user to make the timeout dynamic.", 0, "value in milliseconds of timeout"],
|
85
|
+
"RETRY_LIMIT" => [501, "Set a maximum number of retries after which additional calls to onError will throw the most recently seen error code. Valid parameter values are ``[-1, INT_MAX]``. If set to -1, will disable the retry limit. Like all transaction options, the retry limit must be reset after a call to onError. This behavior allows the user to make the retry limit dynamic.", 0, "number of times to retry"],
|
86
|
+
"MAX_RETRY_DELAY" => [502, "Set the maximum amount of backoff delay incurred in the call to onError if the error is retryable. Defaults to 1000 ms. Valid parameter values are ``[0, INT_MAX]``. Like all transaction options, the maximum retry delay must be reset after a call to onError. If the maximum retry delay is less than the current retry delay of the transaction, then the current retry delay will be clamped to the maximum retry delay.", 0, "value in milliseconds of maximum delay"],
|
87
|
+
"SNAPSHOT_RYW_ENABLE" => [600, "Snapshot read operations will see the results of writes done in the same transaction.", nil, nil],
|
88
|
+
"SNAPSHOT_RYW_DISABLE" => [601, "Snapshot read operations will not see the results of writes done in the same transaction.", nil, nil],
|
89
|
+
"LOCK_AWARE" => [700, "The transaction can read and write to locked databases, and is resposible for checking that it took the lock.", nil, nil],
|
90
|
+
"USED_DURING_COMMIT_PROTECTION_DISABLE" => [701, "By default, operations that are performed on a transaction while it is being committed will not only fail themselves, but they will attempt to fail other in-flight operations (such as the commit) as well. This behavior is intended to help developers discover situations where operations could be unintentionally executed after the transaction has been reset. Setting this option removes that protection, causing only the offending operation to fail.", nil, nil],
|
91
|
+
"READ_LOCK_AWARE" => [702, "The transaction can read from locked databases.", nil, nil],
|
92
|
+
}
|
93
|
+
|
94
|
+
@@StreamingMode = {
|
95
|
+
"WANT_ALL" => [-2, "Client intends to consume the entire range and would like it all transferred as early as possible.", nil, nil],
|
96
|
+
"ITERATOR" => [-1, "The default. The client doesn't know how much of the range it is likely to used and wants different performance concerns to be balanced. Only a small portion of data is transferred to the client initially (in order to minimize costs if the client doesn't read the entire range), and as the caller iterates over more items in the range larger batches will be transferred in order to minimize latency.", nil, nil],
|
97
|
+
"EXACT" => [0, "Infrequently used. The client has passed a specific row limit and wants that many rows delivered in a single batch. Because of iterator operation in client drivers make request batches transparent to the user, consider ``WANT_ALL`` StreamingMode instead. A row limit must be specified if this mode is used.", nil, nil],
|
98
|
+
"SMALL" => [1, "Infrequently used. Transfer data in batches small enough to not be much more expensive than reading individual rows, to minimize cost if iteration stops early.", nil, nil],
|
99
|
+
"MEDIUM" => [2, "Infrequently used. Transfer data in batches sized in between small and large.", nil, nil],
|
100
|
+
"LARGE" => [3, "Infrequently used. Transfer data in batches large enough to be, in a high-concurrency environment, nearly as efficient as possible. If the client stops iteration early, some disk and network bandwidth may be wasted. The batch size may still be too small to allow a single client to get high throughput from the database, so if that is what you need consider the SERIAL StreamingMode.", nil, nil],
|
101
|
+
"SERIAL" => [4, "Transfer data in batches large enough that an individual client can get reasonable read bandwidth from the database. If the client stops iteration early, considerable disk and network bandwidth may be wasted.", nil, nil],
|
102
|
+
}
|
103
|
+
|
104
|
+
@@MutationType = {
|
105
|
+
"ADD" => [2, "Performs an addition of little-endian integers. If the existing value in the database is not present or shorter than ``param``, it is first extended to the length of ``param`` with zero bytes. If ``param`` is shorter than the existing value in the database, the existing value is truncated to match the length of ``param``. The integers to be added must be stored in a little-endian representation. They can be signed in two's complement representation or unsigned. You can add to an integer at a known offset in the value by prepending the appropriate number of zero bytes to ``param`` and padding with zero bytes to match the length of the value. However, this offset technique requires that you know the addition will not cause the integer field within the value to overflow.", '', "addend"],
|
106
|
+
"AND" => [6, "Deprecated", '', "value with which to perform bitwise and"],
|
107
|
+
"BIT_AND" => [6, "Performs a bitwise ``and`` operation. If the existing value in the database is not present, then ``param`` is stored in the database. If the existing value in the database is shorter than ``param``, it is first extended to the length of ``param`` with zero bytes. If ``param`` is shorter than the existing value in the database, the existing value is truncated to match the length of ``param``.", '', "value with which to perform bitwise and"],
|
108
|
+
"OR" => [7, "Deprecated", '', "value with which to perform bitwise or"],
|
109
|
+
"BIT_OR" => [7, "Performs a bitwise ``or`` operation. If the existing value in the database is not present or shorter than ``param``, it is first extended to the length of ``param`` with zero bytes. If ``param`` is shorter than the existing value in the database, the existing value is truncated to match the length of ``param``.", '', "value with which to perform bitwise or"],
|
110
|
+
"XOR" => [8, "Deprecated", '', "value with which to perform bitwise xor"],
|
111
|
+
"BIT_XOR" => [8, "Performs a bitwise ``xor`` operation. If the existing value in the database is not present or shorter than ``param``, it is first extended to the length of ``param`` with zero bytes. If ``param`` is shorter than the existing value in the database, the existing value is truncated to match the length of ``param``.", '', "value with which to perform bitwise xor"],
|
112
|
+
"MAX" => [12, "Performs a little-endian comparison of byte strings. If the existing value in the database is not present or shorter than ``param``, it is first extended to the length of ``param`` with zero bytes. If ``param`` is shorter than the existing value in the database, the existing value is truncated to match the length of ``param``. The larger of the two values is then stored in the database.", '', "value to check against database value"],
|
113
|
+
"MIN" => [13, "Performs a little-endian comparison of byte strings. If the existing value in the database is not present, then ``param`` is stored in the database. If the existing value in the database is shorter than ``param``, it is first extended to the length of ``param`` with zero bytes. If ``param`` is shorter than the existing value in the database, the existing value is truncated to match the length of ``param``. The smaller of the two values is then stored in the database.", '', "value to check against database value"],
|
114
|
+
"SET_VERSIONSTAMPED_KEY" => [14, "Transforms ``key`` using a versionstamp for the transaction. Sets the transformed key in the database to ``param``. A versionstamp is a 10 byte, unique, monotonically (but not sequentially) increasing value for each committed transaction. The first 8 bytes are the committed version of the database. The last 2 bytes are monotonic in the serialization order for transactions. WARNING: At this time versionstamps are compatible with the Tuple layer only in the Java and Python bindings. Note that this implies versionstamped keys may not be used with the Subspace and Directory layers except in those languages.", '', "value to which to set the transformed key"],
|
115
|
+
"SET_VERSIONSTAMPED_VALUE" => [15, "Transforms ``param`` using a versionstamp for the transaction. Sets ``key`` in the database to the transformed parameter. A versionstamp is a 10 byte, unique, monotonically (but not sequentially) increasing value for each committed transaction. The first 8 bytes are the committed version of the database. The last 2 bytes are monotonic in the serialization order for transactions. WARNING: At this time versionstamped values are not compatible with the Tuple layer.", '', "value to versionstamp and set"],
|
116
|
+
"BYTE_MIN" => [16, "Performs lexicographic comparison of byte strings. If the existing value in the database is not present, then ``param`` is stored. Otherwise the smaller of the two values is then stored in the database.", '', "value to check against database value"],
|
117
|
+
"BYTE_MAX" => [17, "Performs lexicographic comparison of byte strings. If the existing value in the database is not present, then ``param`` is stored. Otherwise the larger of the two values is then stored in the database.", '', "value to check against database value"],
|
118
|
+
}
|
119
|
+
|
120
|
+
@@ConflictRangeType = {
|
121
|
+
"READ" => [0, "Used to add a read conflict range", nil, nil],
|
122
|
+
"WRITE" => [1, "Used to add a write conflict range", nil, nil],
|
123
|
+
}
|
124
|
+
|
125
|
+
@@ErrorPredicate = {
|
126
|
+
|
127
|
+
}
|
128
|
+
|
129
|
+
end
|
data/lib/fdbsubspace.rb
ADDED
@@ -0,0 +1,71 @@
|
|
1
|
+
#encoding: BINARY
|
2
|
+
|
3
|
+
#
|
4
|
+
# fdbsubspace.rb
|
5
|
+
#
|
6
|
+
# This source file is part of the FoundationDB open source project
|
7
|
+
#
|
8
|
+
# Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
|
9
|
+
#
|
10
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11
|
+
# you may not use this file except in compliance with the License.
|
12
|
+
# You may obtain a copy of the License at
|
13
|
+
#
|
14
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15
|
+
#
|
16
|
+
# Unless required by applicable law or agreed to in writing, software
|
17
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19
|
+
# See the License for the specific language governing permissions and
|
20
|
+
# limitations under the License.
|
21
|
+
#
|
22
|
+
|
23
|
+
# FoundationDB Ruby API
|
24
|
+
|
25
|
+
# Documentation for this API can be found at
|
26
|
+
# https://www.foundationdb.org/documentation/api-ruby.html
|
27
|
+
|
28
|
+
require_relative 'fdbtuple'
|
29
|
+
|
30
|
+
module FDB
|
31
|
+
class Subspace
|
32
|
+
def initialize(prefix_tuple=[], raw_prefix='')
|
33
|
+
@raw_prefix = raw_prefix.dup.force_encoding('BINARY') + FDB::Tuple.pack(prefix_tuple)
|
34
|
+
end
|
35
|
+
attr_reader :raw_prefix
|
36
|
+
|
37
|
+
def [](name)
|
38
|
+
Subspace.new([name], @raw_prefix)
|
39
|
+
end
|
40
|
+
|
41
|
+
def key
|
42
|
+
@raw_prefix
|
43
|
+
end
|
44
|
+
|
45
|
+
def pack(tuple)
|
46
|
+
@raw_prefix + FDB::Tuple.pack(tuple)
|
47
|
+
end
|
48
|
+
|
49
|
+
def unpack(key)
|
50
|
+
raise ArgumentError, 'Cannot unpack key that is not in subspace.' if not contains? key
|
51
|
+
FDB::Tuple.unpack(key[@raw_prefix.length..-1])
|
52
|
+
end
|
53
|
+
|
54
|
+
def range(tuple=[])
|
55
|
+
rng = FDB::Tuple.range(tuple)
|
56
|
+
[@raw_prefix + rng[0], @raw_prefix + rng[1]]
|
57
|
+
end
|
58
|
+
|
59
|
+
def contains?(key)
|
60
|
+
key.start_with? @raw_prefix
|
61
|
+
end
|
62
|
+
|
63
|
+
def as_foundationdb_key
|
64
|
+
key
|
65
|
+
end
|
66
|
+
|
67
|
+
def subspace(tuple)
|
68
|
+
Subspace.new(tuple, @raw_prefix)
|
69
|
+
end
|
70
|
+
end
|
71
|
+
end
|
data/lib/fdbtuple.rb
ADDED
@@ -0,0 +1,307 @@
|
|
1
|
+
#encoding: BINARY
|
2
|
+
|
3
|
+
#
|
4
|
+
# fdbtuple.rb
|
5
|
+
#
|
6
|
+
# This source file is part of the FoundationDB open source project
|
7
|
+
#
|
8
|
+
# Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
|
9
|
+
#
|
10
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11
|
+
# you may not use this file except in compliance with the License.
|
12
|
+
# You may obtain a copy of the License at
|
13
|
+
#
|
14
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15
|
+
#
|
16
|
+
# Unless required by applicable law or agreed to in writing, software
|
17
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19
|
+
# See the License for the specific language governing permissions and
|
20
|
+
# limitations under the License.
|
21
|
+
#
|
22
|
+
|
23
|
+
# FoundationDB Ruby API
|
24
|
+
|
25
|
+
# Documentation for this API can be found at
|
26
|
+
# https://www.foundationdb.org/documentation/api-ruby.html
|
27
|
+
|
28
|
+
module FDB
|
29
|
+
module Tuple
|
30
|
+
@@size_limits = (0..8).map {|x| (1 << (x*8)) - 1}
|
31
|
+
|
32
|
+
# Type codes
|
33
|
+
@@NULL_CODE = 0x00
|
34
|
+
@@BYTES_CODE = 0x01
|
35
|
+
@@STRING_CODE = 0x02
|
36
|
+
@@NESTED_CODE = 0x05
|
37
|
+
@@INT_ZERO_CODE = 0x14
|
38
|
+
@@POS_INT_END = 0x1c
|
39
|
+
@@NEG_INT_START = 0x0c
|
40
|
+
@@FLOAT_CODE = 0x20
|
41
|
+
@@DOUBLE_CODE = 0x21
|
42
|
+
@@FALSE_CODE = 0x26
|
43
|
+
@@TRUE_CODE = 0x27
|
44
|
+
@@UUID_CODE = 0x30
|
45
|
+
|
46
|
+
class UUID
|
47
|
+
def initialize(data)
|
48
|
+
if data.length != 16
|
49
|
+
raise Error.new(2268) # invalid_uuid_size
|
50
|
+
end
|
51
|
+
@data=data.slice(0,16)
|
52
|
+
end
|
53
|
+
def data
|
54
|
+
@data
|
55
|
+
end
|
56
|
+
def <=> (other)
|
57
|
+
self.data <=> other.data
|
58
|
+
end
|
59
|
+
def to_s
|
60
|
+
self.data.each_byte.map { |b| b.to_s(16) } .join
|
61
|
+
end
|
62
|
+
end
|
63
|
+
|
64
|
+
class SingleFloat
|
65
|
+
def initialize(value)
|
66
|
+
if value.kind_of? Float
|
67
|
+
@value=value
|
68
|
+
elsif value.kind_of? Integer
|
69
|
+
@value=value.to_f
|
70
|
+
else
|
71
|
+
raise ArgumentError, "Invalid value type for SingleFloat: " + value.class.name
|
72
|
+
end
|
73
|
+
@value=value
|
74
|
+
end
|
75
|
+
def value
|
76
|
+
@value
|
77
|
+
end
|
78
|
+
def <=> (other)
|
79
|
+
Tuple._compare_floats(self.value, other.value, false)
|
80
|
+
end
|
81
|
+
def to_s
|
82
|
+
self.value.to_s
|
83
|
+
end
|
84
|
+
end
|
85
|
+
|
86
|
+
def self.find_terminator(v, pos)
|
87
|
+
while true
|
88
|
+
pos = v.index("\x00", pos)
|
89
|
+
if !pos
|
90
|
+
return v.length
|
91
|
+
elsif pos+1 == v.length || v[pos+1] != "\xff"
|
92
|
+
return pos
|
93
|
+
end
|
94
|
+
pos += 2
|
95
|
+
end
|
96
|
+
end
|
97
|
+
private_class_method :find_terminator
|
98
|
+
|
99
|
+
def self.float_adjust(v, pos, length, encode)
|
100
|
+
if (encode and v[pos].ord & 0x80 != 0x00) or (not encode and v[pos].ord & 0x80 == 0x00)
|
101
|
+
v.slice(pos, length).chars.map { |b| (b.ord ^ 0xff).chr } .join
|
102
|
+
else
|
103
|
+
ret = v.slice(pos, length)
|
104
|
+
ret[0] = (ret[0].ord ^ 0x80).chr
|
105
|
+
ret
|
106
|
+
end
|
107
|
+
end
|
108
|
+
private_class_method :float_adjust
|
109
|
+
|
110
|
+
def self.decode(v, pos)
|
111
|
+
code = v.getbyte(pos)
|
112
|
+
if code == @@NULL_CODE
|
113
|
+
[nil, pos+1]
|
114
|
+
elsif code == @@BYTES_CODE
|
115
|
+
epos = find_terminator(v, pos+1)
|
116
|
+
[v.slice(pos+1, epos-pos-1).gsub("\x00\xFF", "\x00"), epos+1]
|
117
|
+
elsif code == @@STRING_CODE
|
118
|
+
epos = find_terminator(v, pos+1)
|
119
|
+
[v.slice(pos+1, epos-pos-1).gsub("\x00\xFF", "\x00").force_encoding("UTF-8"), epos+1]
|
120
|
+
elsif code >= @@INT_ZERO_CODE && code <= @@POS_INT_END
|
121
|
+
n = code - @@INT_ZERO_CODE
|
122
|
+
[("\x00" * (8-n) + v.slice(pos+1, n)).unpack("Q>")[0], pos+n+1]
|
123
|
+
elsif code >= @@NEG_INT_START and code < @@INT_ZERO_CODE
|
124
|
+
n = @@INT_ZERO_CODE - code
|
125
|
+
[("\x00" * (8-n) + v.slice(pos+1, n)).unpack("Q>")[0]-@@size_limits[n], pos+n+1]
|
126
|
+
elsif code == @@FALSE_CODE
|
127
|
+
[false, pos+1]
|
128
|
+
elsif code == @@TRUE_CODE
|
129
|
+
[true, pos+1]
|
130
|
+
elsif code == @@FLOAT_CODE
|
131
|
+
[SingleFloat.new(float_adjust(v, pos+1, 4, false).unpack("g")[0]), pos+5]
|
132
|
+
elsif code == @@DOUBLE_CODE
|
133
|
+
[float_adjust(v, pos+1, 8, false).unpack("G")[0], pos+9]
|
134
|
+
elsif code == @@UUID_CODE
|
135
|
+
[UUID.new(v.slice(pos+1, 16)), pos+17]
|
136
|
+
elsif code == @@NESTED_CODE
|
137
|
+
epos = pos+1
|
138
|
+
nested = []
|
139
|
+
while epos < v.length
|
140
|
+
if v.getbyte(epos) == @@NULL_CODE
|
141
|
+
if epos+1 < v.length and v.getbyte(epos+1) == 0xFF
|
142
|
+
nested << nil
|
143
|
+
epos += 2
|
144
|
+
else
|
145
|
+
break
|
146
|
+
end
|
147
|
+
else
|
148
|
+
r, epos = decode(v, epos)
|
149
|
+
nested << r
|
150
|
+
end
|
151
|
+
end
|
152
|
+
[nested, epos+1]
|
153
|
+
else
|
154
|
+
raise "Unknown data type in DB: " + code.ord.to_s
|
155
|
+
end
|
156
|
+
end
|
157
|
+
private_class_method :decode
|
158
|
+
|
159
|
+
def self.bisect_left(list, item)
|
160
|
+
count = 0
|
161
|
+
list.each{|i|
|
162
|
+
return count if i >= item
|
163
|
+
count += 1
|
164
|
+
}
|
165
|
+
nil
|
166
|
+
end
|
167
|
+
private_class_method :bisect_left
|
168
|
+
|
169
|
+
def self.encode(v, nested=false)
|
170
|
+
if v.nil?
|
171
|
+
if nested
|
172
|
+
"\x00\xFF"
|
173
|
+
else
|
174
|
+
@@NULL_CODE.chr
|
175
|
+
end
|
176
|
+
elsif v.kind_of? String
|
177
|
+
if v.encoding == Encoding::BINARY || v.encoding == Encoding::ASCII
|
178
|
+
@@BYTES_CODE.chr + v.gsub("\x00", "\x00\xFF") + 0.chr
|
179
|
+
elsif v.encoding == Encoding::UTF_8
|
180
|
+
@@STRING_CODE.chr + v.dup.force_encoding("BINARY").gsub("\x00", "\x00\xFF") + 0.chr
|
181
|
+
else
|
182
|
+
raise ArgumentError, "unsupported encoding #{v.encoding.name}"
|
183
|
+
end
|
184
|
+
elsif v.kind_of? Integer
|
185
|
+
raise RangeError, "value outside inclusive range -2**64+1 to 2**64-1" if v < -2**64+1 || v > 2**64-1
|
186
|
+
if v == 0
|
187
|
+
@@INT_ZERO_CODE.chr
|
188
|
+
elsif v > 0
|
189
|
+
n = bisect_left( @@size_limits, v )
|
190
|
+
(20+n).chr + [v].pack("Q>").slice(8-n, n)
|
191
|
+
else
|
192
|
+
n = bisect_left( @@size_limits, -v )
|
193
|
+
(20-n).chr + [@@size_limits[n]+v].pack("Q>").slice(8-n, n)
|
194
|
+
end
|
195
|
+
elsif v.kind_of? TrueClass
|
196
|
+
@@TRUE_CODE.chr
|
197
|
+
elsif v.kind_of? FalseClass
|
198
|
+
@@FALSE_CODE.chr
|
199
|
+
elsif v.kind_of? SingleFloat
|
200
|
+
@@FLOAT_CODE.chr + float_adjust([v.value].pack("g"), 0, 4, true)
|
201
|
+
elsif v.kind_of? Float
|
202
|
+
@@DOUBLE_CODE.chr + float_adjust([v].pack("G"), 0, 8, true)
|
203
|
+
elsif v.kind_of? UUID
|
204
|
+
@@UUID_CODE.chr + v.data
|
205
|
+
elsif v.kind_of? Array
|
206
|
+
@@NESTED_CODE.chr + (v.map { |el| encode(el, true).force_encoding("BINARY") }).join + 0.chr
|
207
|
+
else
|
208
|
+
raise ArgumentError, "unsupported type #{v.class}"
|
209
|
+
end
|
210
|
+
end
|
211
|
+
private_class_method :encode
|
212
|
+
|
213
|
+
def self.pack(t)
|
214
|
+
(t.each_with_index.map {|el, i|
|
215
|
+
begin
|
216
|
+
(encode el).force_encoding("BINARY")
|
217
|
+
rescue
|
218
|
+
raise $!, "#{$!} at index #{i}", $!.backtrace
|
219
|
+
end
|
220
|
+
}).join
|
221
|
+
end
|
222
|
+
|
223
|
+
def self.unpack(key)
|
224
|
+
key = key.dup.force_encoding("BINARY")
|
225
|
+
pos = 0
|
226
|
+
res = []
|
227
|
+
while pos < key.length
|
228
|
+
r, pos = decode(key, pos)
|
229
|
+
res << r
|
230
|
+
end
|
231
|
+
res
|
232
|
+
end
|
233
|
+
|
234
|
+
def self.range(tuple=[])
|
235
|
+
p = pack(tuple)
|
236
|
+
[p+"\x00", p+"\xFF"]
|
237
|
+
end
|
238
|
+
|
239
|
+
def self._code_for(v)
|
240
|
+
if v.nil?
|
241
|
+
@@NULL_CODE
|
242
|
+
elsif v.kind_of? String
|
243
|
+
if v.encoding == Encoding::BINARY || v.encoding == Encoding::ASCII
|
244
|
+
@@BYTES_CODE
|
245
|
+
elsif v.encoding == Encoding::UTF_8
|
246
|
+
@@STRING_CODE
|
247
|
+
else
|
248
|
+
raise ArgumentError, "unsupported encoding #{v.encoding.name}"
|
249
|
+
end
|
250
|
+
elsif v.kind_of? Integer
|
251
|
+
@@INT_ZERO_CODE
|
252
|
+
elsif v.kind_of? TrueClass
|
253
|
+
@@TRUE_CODE
|
254
|
+
elsif v.kind_of? FalseClass
|
255
|
+
@@FALSE_CODE
|
256
|
+
elsif v.kind_of? SingleFloat
|
257
|
+
@@FLOAT_CODE
|
258
|
+
elsif v.kind_of? Float
|
259
|
+
@@DOUBLE_CODE
|
260
|
+
elsif v.kind_of? UUID
|
261
|
+
@@UUID_CODE
|
262
|
+
elsif v.kind_of? Array
|
263
|
+
@@NESTED_CODE
|
264
|
+
else
|
265
|
+
raise ArgumentError, "unsupported type #{v.class}"
|
266
|
+
end
|
267
|
+
end
|
268
|
+
|
269
|
+
def self._compare_floats(f1, f2, is_double)
|
270
|
+
# This converts the floats to their byte representation and then
|
271
|
+
# does the comparison. Why?
|
272
|
+
# 1) NaN comparison - Ruby doesn't really do this
|
273
|
+
# 2) -0.0 == 0.0 in Ruby but not in our representation
|
274
|
+
# It would be better to just take the floats and compare them, but
|
275
|
+
# this way handles the edge cases correctly.
|
276
|
+
b1 = float_adjust([f1].pack(is_double ? ">G" : ">g"), 0, (is_double ? 8 : 4), true)
|
277
|
+
b2 = float_adjust([f2].pack(is_double ? ">G" : ">g"), 0, (is_double ? 8 : 4), true)
|
278
|
+
b1 <=> b2
|
279
|
+
end
|
280
|
+
|
281
|
+
def self._compare_elems(v1, v2)
|
282
|
+
c1 = _code_for(v1)
|
283
|
+
c2 = _code_for(v2)
|
284
|
+
return c1 <=> c2 unless c1 == c2
|
285
|
+
|
286
|
+
if c1 == @@NULL_CODE
|
287
|
+
0
|
288
|
+
elsif c1 == @@DOUBLE_CODE
|
289
|
+
_compare_floats(v1, v2, true)
|
290
|
+
elsif c1 == @@NESTED_CODE
|
291
|
+
compare(v1, v2) # recurse
|
292
|
+
else
|
293
|
+
v1 <=> v2
|
294
|
+
end
|
295
|
+
end
|
296
|
+
|
297
|
+
def self.compare(tuple1, tuple2)
|
298
|
+
i = 0
|
299
|
+
while i < tuple1.length && i < tuple2.length
|
300
|
+
c = self._compare_elems(tuple1[i], tuple2[i])
|
301
|
+
return c unless c == 0
|
302
|
+
i += 1
|
303
|
+
end
|
304
|
+
tuple1.length <=> tuple2.length
|
305
|
+
end
|
306
|
+
end
|
307
|
+
end
|