xitdb 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +16 -0
  3. data/README.md +15 -3
  4. data/docs/benchmarks.md +4 -1
  5. data/docs/core.md +15 -2
  6. data/docs/learning.md +211 -0
  7. data/docs/native-profile-performance.md +254 -0
  8. data/docs/ruby-profile-v1.md +2 -0
  9. data/docs/ruby-profile-v2.md +279 -0
  10. data/docs/ruby-profile-v3.md +53 -0
  11. data/docs/ruby-profile-v4.md +67 -0
  12. data/docs/ruby.md +26 -3
  13. data/examples/indexed_users.rb +3 -0
  14. data/examples/portable.rb +3 -0
  15. data/examples/ruby.rb +2 -0
  16. data/lib/xitdb/collection_declaration.rb +39 -0
  17. data/lib/xitdb/context.rb +154 -8
  18. data/lib/xitdb/conversion/byte_source.rb +112 -0
  19. data/lib/xitdb/conversion.rb +35 -73
  20. data/lib/xitdb/core/array_builder.rb +74 -0
  21. data/lib/xitdb/core/array_list.rb +92 -8
  22. data/lib/xitdb/core/b_tree.rb +127 -19
  23. data/lib/xitdb/core/byte_value.rb +33 -0
  24. data/lib/xitdb/core/bytes/source.rb +59 -0
  25. data/lib/xitdb/core/bytes.rb +54 -58
  26. data/lib/xitdb/core/compaction.rb +49 -7
  27. data/lib/xitdb/core/crc64.rb +8 -1
  28. data/lib/xitdb/core/cursor.rb +108 -18
  29. data/lib/xitdb/core/database.rb +163 -29
  30. data/lib/xitdb/core/file_store.rb +43 -1
  31. data/lib/xitdb/core/format.rb +39 -98
  32. data/lib/xitdb/core/hash_map.rb +119 -17
  33. data/lib/xitdb/core/hasher.rb +33 -2
  34. data/lib/xitdb/core/header.rb +98 -0
  35. data/lib/xitdb/core/linked_array_list.rb +70 -1
  36. data/lib/xitdb/core/memory_store.rb +23 -224
  37. data/lib/xitdb/core/offset_map.rb +22 -1
  38. data/lib/xitdb/core/record.rb +64 -0
  39. data/lib/xitdb/core/replication.rb +108 -25
  40. data/lib/xitdb/core/slot.rb +123 -0
  41. data/lib/xitdb/core/sorted_map/tree.rb +317 -0
  42. data/lib/xitdb/core/sorted_map.rb +78 -256
  43. data/lib/xitdb/core/store.rb +286 -0
  44. data/lib/xitdb/core/transaction.rb +84 -6
  45. data/lib/xitdb/core.rb +12 -0
  46. data/lib/xitdb/database.rb +194 -15
  47. data/lib/xitdb/declarations.rb +33 -33
  48. data/lib/xitdb/errors.rb +15 -0
  49. data/lib/xitdb/history.rb +21 -0
  50. data/lib/xitdb/input_guard.rb +15 -1
  51. data/lib/xitdb/profiles/portable/adapter.rb +380 -0
  52. data/lib/xitdb/profiles/portable.rb +129 -243
  53. data/lib/xitdb/profiles/ruby.rb +206 -24
  54. data/lib/xitdb/revision.rb +17 -0
  55. data/lib/xitdb/ruby/codec.rb +61 -54
  56. data/lib/xitdb/ruby/codec_registry.rb +79 -0
  57. data/lib/xitdb/ruby/containers.rb +355 -82
  58. data/lib/xitdb/ruby/encoded_value.rb +38 -0
  59. data/lib/xitdb/ruby/indexed_page_decoder.rb +72 -0
  60. data/lib/xitdb/ruby/indexed_page_encoder.rb +58 -0
  61. data/lib/xitdb/ruby/input.rb +55 -0
  62. data/lib/xitdb/ruby/key_encoding.rb +43 -5
  63. data/lib/xitdb/ruby/ordered_keys.rb +46 -3
  64. data/lib/xitdb/ruby/packed_array.rb +179 -0
  65. data/lib/xitdb/ruby/packed_map.rb +272 -0
  66. data/lib/xitdb/ruby/packing_state.rb +84 -0
  67. data/lib/xitdb/ruby/page_array.rb +218 -0
  68. data/lib/xitdb/ruby/page_cell.rb +20 -0
  69. data/lib/xitdb/ruby/page_codec.rb +46 -0
  70. data/lib/xitdb/ruby/page_decoder.rb +172 -0
  71. data/lib/xitdb/ruby/page_draft.rb +24 -0
  72. data/lib/xitdb/ruby/page_encoder.rb +149 -0
  73. data/lib/xitdb/ruby/page_reference.rb +26 -0
  74. data/lib/xitdb/ruby/page_row.rb +108 -0
  75. data/lib/xitdb/ruby/pages.rb +94 -0
  76. data/lib/xitdb/ruby/scalars.rb +175 -33
  77. data/lib/xitdb/ruby/wire/reader.rb +138 -0
  78. data/lib/xitdb/ruby/wire.rb +36 -90
  79. data/lib/xitdb/ruby.rb +43 -3
  80. data/lib/xitdb/snapshot.rb +8 -0
  81. data/lib/xitdb/streams/handle.rb +46 -0
  82. data/lib/xitdb/streams/reader.rb +122 -0
  83. data/lib/xitdb/streams/writer.rb +43 -0
  84. data/lib/xitdb/streams.rb +8 -140
  85. data/lib/xitdb/uint.rb +17 -0
  86. data/lib/xitdb/value_walker.rb +86 -16
  87. data/lib/xitdb/version.rb +2 -1
  88. data/lib/xitdb/views/array.rb +94 -74
  89. data/lib/xitdb/views/base.rb +144 -12
  90. data/lib/xitdb/views/linked_array.rb +7 -1
  91. data/lib/xitdb/views/map.rb +71 -3
  92. data/lib/xitdb/views/set.rb +13 -1
  93. data/lib/xitdb/views/slice.rb +101 -0
  94. data/lib/xitdb/views/sorted.rb +25 -37
  95. data/lib/xitdb/views/sorted_map.rb +39 -0
  96. data/lib/xitdb/views/sorted_set.rb +10 -0
  97. data/lib/xitdb.rb +3 -0
  98. data/sig/core.rbs +65 -34
  99. data/sig/public.rbs +24 -19
  100. data/sig/ruby.rbs +260 -42
  101. metadata +42 -1
@@ -2,50 +2,42 @@
2
2
 
3
3
  module XitDB
4
4
  module Core
5
- # Reads and writes inline or external byte payloads.
5
+ # Storage helpers for byte payloads and optional two-byte application format tags.
6
+ #
7
+ # Small zero-free payloads can fit in a slot. Other payloads use an external record with an unsigned 64-bit length.
8
+ # @api private
6
9
  module Bytes
10
+ # Maximum source bytes requested per chunk when appending an external payload.
7
11
  CHUNK_SIZE = 64 * 1024
8
12
 
9
- # A bounded reader for one immutable byte payload.
10
- class Source
11
- attr_reader :size, :format_tag
12
-
13
- def initialize(database, location, size, format_tag, bound)
14
- @database = database
15
- @location = location
16
- @size = size
17
- @format_tag = format_tag
18
- @bound = bound
19
- freeze
20
- end
21
-
22
- def read(position, length)
23
- @database.check_open!
24
- unless position.is_a?(Integer) && length.is_a?(Integer)
25
- raise TypeError, "byte positions and lengths must be Integers"
26
- end
27
- if position.negative? || length.negative? || position + length > size
28
- raise InvalidValueError, "truncated byte payload"
29
- end
30
-
31
- location = @location
32
- if location.is_a?(String)
33
- Format.slice(location, position, length)
34
- else
35
- @database.read_at(location + position, length, bound: @bound)
36
- end
37
- end
38
- end
39
- private_constant :Source
40
-
13
+ # Opens an inline or external byte slot without loading its full payload.
14
+ # @param database [Database] database that owns the stored records
15
+ # @param slot [Slot] stored value or record descriptor
16
+ # @param bound [Integer] exclusive upper byte boundary for reads
17
+ # @return [Source]
18
+ # @raise [InvalidValueError] if slot does not describe bytes
41
19
  def self.open(database, slot, bound:)
42
20
  location, size, format_tag = parse(database, slot, bound)
43
21
  Source.new(database, location, size, format_tag, bound)
44
22
  end
45
23
 
24
+ # Stores bytes in a slot when they fit, or appends an external payload.
25
+ # @param transaction [Transaction] active destination transaction
26
+ # @param size [Integer] number of bytes
27
+ # @param format_tag [String, nil] optional two-byte application format identifier
28
+ # @param prefix [String] bytes to place before the source payload
29
+ # @param representation [Symbol] :automatic for eligible inline values, or :external
30
+ # @return [Slot]
31
+ # @yield [position, length] provides an exact chunk of source bytes
32
+ # @yieldparam position [Integer] byte offset inside the source, excluding prefix
33
+ # @yieldparam length [Integer] exact number of bytes requested
34
+ # @yieldreturn [String] exactly length bytes
35
+ # @raise [EOFError] if the reader is absent or returns too few bytes
36
+ # @raise [ArgumentError] if the format tag, representation, or chunk length is invalid
37
+ # @raise [RangeError] if the total payload exceeds unsigned 64-bit storage
46
38
  def self.append(transaction, size:, format_tag: nil, prefix: "".b, representation: :automatic, &reader)
47
39
  transaction.check_active!
48
- validate_source(size, prefix, representation, format_tag)
40
+ validate_source!(size, prefix, representation, format_tag)
49
41
  format_tag = format_tag&.b
50
42
  total_size = prefix.bytesize + size
51
43
  raise RangeError, "byte payload exceeds unsigned 64-bit size" if total_size >= (1 << 64)
@@ -67,7 +59,8 @@ module XitDB
67
59
  Slot.new(tag: :bytes, value: offset, full: !format_tag.nil?)
68
60
  end
69
61
 
70
- def self.validate_source(size, prefix, representation, format_tag)
62
+ # Checks the source size, prefix, storage mode, and optional format tag.
63
+ def self.validate_source!(size, prefix, representation, format_tag)
71
64
  raise TypeError, "size must be an Integer" unless size.is_a?(Integer)
72
65
  raise ArgumentError, "size must be nonnegative" if size.negative?
73
66
  raise TypeError, "prefix must be a String" unless prefix.is_a?(String)
@@ -77,12 +70,14 @@ module XitDB
77
70
  raise ArgumentError, "format_tag must contain two bytes"
78
71
  end
79
72
 
73
+ # Reads a small payload once when it might fit inside a slot.
80
74
  def self.capture_inline(size, prefix, representation, capacity, &)
81
75
  return nil unless representation == :automatic && prefix.bytesize + size <= capacity
82
76
 
83
77
  prefix.b + (size.zero? ? "".b : read_chunk(0, size, &))
84
78
  end
85
79
 
80
+ # Appends the prefix and source in bounded chunks.
86
81
  def self.append_source(transaction, prefix, size, &)
87
82
  position = 0
88
83
  while position < prefix.bytesize
@@ -97,8 +92,9 @@ module XitDB
97
92
  position += length
98
93
  end
99
94
  end
100
- private_class_method :validate_source, :capture_inline, :append_source
95
+ private_class_method :validate_source!, :capture_inline, :append_source
101
96
 
97
+ # Requests one exact chunk and rejects invalid replies.
102
98
  def self.read_chunk(position, length)
103
99
  chunk = yield(position, length) if block_given?
104
100
  raise EOFError, "byte source ended before its declared size" if chunk.nil?
@@ -110,20 +106,21 @@ module XitDB
110
106
  end
111
107
  private_class_method :read_chunk
112
108
 
109
+ # Finds the payload location, length, and optional two-byte format tag.
113
110
  def self.parse(database, slot, bound)
114
111
  database.check_open!
115
112
  case slot.tag
116
113
  when :short_bytes
117
114
  payload = [slot.value].pack("Q>")
118
- capacity = slot.full ? 6 : 8
115
+ capacity = slot.full? ? 6 : 8
119
116
  data = (Format.slice(payload, 0, capacity).split("\0", 2).first || "".b).freeze
120
- tag = Format.slice(payload, 6, 2).freeze if slot.full
117
+ tag = Format.slice(payload, 6, 2).freeze if slot.full?
121
118
  [data, data.bytesize, tag]
122
119
  when :bytes
123
120
  size = Format.unsigned(database.read_at(slot.value, 8, bound: bound))
124
121
  offset = slot.value + 8
125
- tail = database.read_at(offset + size, slot.full ? 2 : 0, bound: bound)
126
- tag = tail.freeze if slot.full
122
+ tail = database.read_at(offset + size, slot.full? ? 2 : 0, bound: bound)
123
+ tag = tail.freeze if slot.full?
127
124
  [offset, size, tag]
128
125
  else
129
126
  raise InvalidValueError, "slot does not contain bytes"
@@ -131,9 +128,14 @@ module XitDB
131
128
  end
132
129
  private_class_method :parse
133
130
 
134
- # Return inline data or its file offset, without materializing a scalar.
131
+ # Returns untagged inline bytes or an external offset with its byte count.
132
+ # @param database [Database] database that owns the stored records
133
+ # @param slot [Slot] stored value or record descriptor
134
+ # @param bound [Integer] exclusive upper byte boundary for reads
135
+ # @return [Array(String, Integer), Array(Integer, Integer)]
136
+ # @raise [InvalidValueError] if slot is not untagged bytes
135
137
  def self.locate(database, slot, bound:)
136
- unless %i[bytes short_bytes].include?(slot.tag) && !slot.full
138
+ unless %i[bytes short_bytes].include?(slot.tag) && !slot.full?
137
139
  raise InvalidValueError, "stream requires untagged bytes"
138
140
  end
139
141
 
@@ -141,6 +143,13 @@ module XitDB
141
143
  [location.is_a?(String) ? location.dup : location, size]
142
144
  end
143
145
 
146
+ # Copies a declared byte count from an IO-like reader into a slot.
147
+ # @param source [#read] binary reader implementing read(length)
148
+ # @param size [Integer] number of bytes
149
+ # @param database [Database] database that owns the stored records
150
+ # @param transaction [Transaction] active destination transaction
151
+ # @return [Slot]
152
+ # @raise [EOFError] if the source ends before the declared size
144
153
  def self.copy(source, size:, database:, transaction:)
145
154
  if size <= 8
146
155
  bytes = source.read(size)
@@ -161,21 +170,8 @@ module XitDB
161
170
  end
162
171
  end
163
172
  end
164
-
165
- # An immutable byte payload and its optional format tag.
166
- class ByteValue
167
- attr_reader :bytes, :format_tag
168
-
169
- def initialize(bytes, format_tag: nil)
170
- raise TypeError, "bytes must be a String" unless bytes.is_a?(String)
171
- unless format_tag.nil? || (format_tag.is_a?(String) && format_tag.bytesize == 2)
172
- raise ArgumentError, "format_tag must contain two bytes"
173
- end
174
-
175
- @bytes = bytes.b.freeze
176
- @format_tag = format_tag&.b&.freeze
177
- freeze
178
- end
179
- end
180
173
  end
181
174
  end
175
+
176
+ require_relative "bytes/source"
177
+ require_relative "byte_value"
@@ -1,14 +1,26 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "offset_map"
4
+ require_relative "record"
4
5
 
5
6
  module XitDB
6
7
  module Core
7
- # Copies reachable records into a new database.
8
+ # A copier that retains reachable records and remaps their byte offsets.
9
+ #
10
+ # An explicit work stack avoids recursive traversal. The offset table preserves sharing between copied records.
11
+ # @api private
8
12
  class Compaction
13
+ # Slot tags whose value field contains data rather than a record offset.
9
14
  INLINE_TAGS = %i[none uint int float short_bytes].freeze
15
+ # Bytes in a block of sixteen copied slot descriptors.
10
16
  BLOCK_SIZE = 16 * Slot::SIZE
11
17
 
18
+ # Creates a copier bound to one source view and destination transaction.
19
+ # @param source [Database] database containing the source records
20
+ # @param cursor [Cursor] view locating this collection or value
21
+ # @param transaction [Transaction] active destination transaction
22
+ # @param offsets [OffsetMap] lookup table retaining source-to-destination offset mappings
23
+ # @return [Compaction]
12
24
  def initialize(source, cursor, transaction, offsets)
13
25
  @source = source
14
26
  @bound = cursor.bound
@@ -17,6 +29,9 @@ module XitDB
17
29
  @stack = []
18
30
  end
19
31
 
32
+ # Copies a reachable slot graph and rewrites pointers to destination offsets.
33
+ # @param slot [Slot] stored value or record descriptor
34
+ # @return [Slot]
20
35
  def copy(slot)
21
36
  result = remap(slot)
22
37
  @stack.pop&.call until @stack.empty?
@@ -25,10 +40,12 @@ module XitDB
25
40
 
26
41
  private
27
42
 
43
+ # Reads source bytes within the captured view boundary.
28
44
  def read(offset, size)
29
45
  @source.read_at(offset, size, bound: @bound)
30
46
  end
31
47
 
48
+ # Decodes a slot and rejects tags the copier cannot interpret.
32
49
  def parse(bytes)
33
50
  slot = Slot.parse(bytes)
34
51
  raise CorruptionError, "unknown compaction slot tag" unless Slot::TAGS.include?(slot.tag)
@@ -36,12 +53,14 @@ module XitDB
36
53
  slot
37
54
  end
38
55
 
56
+ # Keeps inline values unchanged and rewrites external pointers.
39
57
  def remap(slot)
40
58
  return slot if INLINE_TAGS.include?(slot.tag)
41
59
 
42
- Slot.new(tag: slot.tag, full: slot.full, value: remap_pointer(slot))
60
+ Slot.new(tag: slot.tag, full: slot.full?, value: remap_pointer(slot))
43
61
  end
44
62
 
63
+ # Selects the record layout that determines which child pointers require copying.
45
64
  def remap_pointer(slot)
46
65
  case slot.tag
47
66
  when :bytes then copy_bytes(slot)
@@ -54,17 +73,32 @@ module XitDB
54
73
  when :sorted_map, :sorted_set then reserve(slot.value, 16) do |source, target|
55
74
  tree_header(source, target, true)
56
75
  end
57
- when :kv_pair then reserve_slots(slot.value, @source.header.hash_size + 18,
58
- @source.header.hash_size, 2)
59
- when :sorted_kv_pair then reserve_slots(slot.value, 18, 0, 2)
76
+ when :kv_pair, :sorted_kv_pair then copy_pair(slot)
77
+ when :record then copy_record(slot)
60
78
  else raise CorruptionError, "unknown compaction slot tag"
61
79
  end
62
80
  end
63
81
 
82
+ # Both pair layouts hold two slots after an optional hash prefix.
83
+ def copy_pair(slot)
84
+ start = slot.tag == :kv_pair ? @source.header.hash_size : 0
85
+ reserve_slots(slot.value, start + 18, start, 2)
86
+ end
87
+
88
+ # Checks a bounded record header before reserving and remapping its fields.
89
+ def copy_record(slot)
90
+ _metadata, count = Format.pair(read(slot.value, Record::HEADER_SIZE), "NN")
91
+ raise CorruptionError, "record exceeds field limit" if count > Record::MAX_FIELDS
92
+
93
+ reserve_slots(slot.value, Record::HEADER_SIZE + (count * Slot::SIZE), Record::HEADER_SIZE, count)
94
+ end
95
+
96
+ # Reserves a copied record and schedules child slots for rewriting.
64
97
  def reserve_slots(source, size, start, count)
65
98
  reserve(source, size) { |origin, target| slots(origin, target, start, count) }
66
99
  end
67
100
 
101
+ # Reuses a known offset or reserves storage before scheduling pointer rewrites.
68
102
  def reserve(source, size, cache: true)
69
103
  mapped = @offsets.fetch(source) if cache
70
104
  return mapped if mapped
@@ -76,6 +110,7 @@ module XitDB
76
110
  target
77
111
  end
78
112
 
113
+ # Copies a byte payload in chunks and records its destination offset.
79
114
  def copy_bytes(slot)
80
115
  mapped = @offsets.fetch(slot.value)
81
116
  return mapped if mapped
@@ -91,6 +126,7 @@ module XitDB
91
126
  target
92
127
  end
93
128
 
129
+ # Rewrites child slots in a previously reserved destination record.
94
130
  def slots(source, target, start, count)
95
131
  count.times do |index|
96
132
  offset = start + (index * Slot::SIZE)
@@ -99,6 +135,7 @@ module XitDB
99
135
  end
100
136
  end
101
137
 
138
+ # Copies an array root using only elements inside its visible count.
102
139
  def array_header(source, target)
103
140
  size, pointer = Format.pair(read(source, 16), "Q>Q>")
104
141
  shift = [((size - 1).bit_length - 1) / 4, 0].max
@@ -106,12 +143,14 @@ module XitDB
106
143
  @transaction.write_at(target, [size, mapped].pack("Q>Q>"))
107
144
  end
108
145
 
146
+ # Shares full copied blocks and separately copies partially visible blocks.
109
147
  def array_index(source, size, shift)
110
148
  return reserve_slots(source, BLOCK_SIZE, 0, 16) if size == 1 << ((shift + 1) * 4)
111
149
 
112
150
  reserve(source, BLOCK_SIZE, cache: false) { |origin, target| partial_array(origin, target, size, shift) }
113
151
  end
114
152
 
153
+ # Clears hidden positions and remaps only visible slots in a partial array block.
115
154
  def partial_array(source, target, size, shift)
116
155
  # Partial blocks can be shared by arrays with different visible sizes.
117
156
  # Copy them separately and clear every slot outside this array's size.
@@ -126,7 +165,7 @@ module XitDB
126
165
  else
127
166
  raise CorruptionError, "invalid array branch" unless slot.tag == :index
128
167
 
129
- Slot.new(tag: :index, full: slot.full,
168
+ Slot.new(tag: :index, full: slot.full?,
130
169
  value: array_index(slot.value, [size, child_size].min, shift - 1))
131
170
  end
132
171
  @transaction.write_at(target + (index * Slot::SIZE), mapped.to_bytes)
@@ -134,11 +173,13 @@ module XitDB
134
173
  end
135
174
  end
136
175
 
176
+ # Rewrites a counted tree header to its copied root node.
137
177
  def tree_header(source, target, sorted)
138
178
  size, pointer = Format.pair(read(source, 16), "Q>Q>")
139
179
  @transaction.write_at(target, [size, tree_node(pointer, sorted)].pack("Q>Q>"))
140
180
  end
141
181
 
182
+ # Reserves a tree node according to its kind and sorted layout.
142
183
  def tree_node(source, sorted)
143
184
  mapped = @offsets.fetch(source)
144
185
  return mapped if mapped
@@ -158,11 +199,12 @@ module XitDB
158
199
  end
159
200
  end
160
201
 
202
+ # Rewrites child node pointers and sorted separator slots in a branch.
161
203
  def tree_branch(source, target, sorted)
162
204
  16.times do |index|
163
205
  offset = 2 + (index * Slot::SIZE)
164
206
  slot = parse(read(source + offset, Slot::SIZE))
165
- slot = Slot.new(tag: :index, full: slot.full, value: tree_node(slot.value, sorted)) if slot.tag == :index
207
+ slot = Slot.new(tag: :index, full: slot.full?, value: tree_node(slot.value, sorted)) if slot.tag == :index
166
208
  @transaction.write_at(target + offset, slot.to_bytes)
167
209
  end
168
210
  slots(source, target, 2 + BLOCK_SIZE, 16) if sorted
@@ -2,11 +2,18 @@
2
2
 
3
3
  module XitDB
4
4
  module Core
5
- # Calculates the checksum used by root trailers.
5
+ # The checksum calculation used to detect invalid committed root trailers.
6
+ # @api private
6
7
  module CRC64
8
+ # Unsigned 64-bit mask used to initialize and finish the checksum.
7
9
  MASK = 0xffffffffffffffff
10
+ # Reflected polynomial used by the checksum bit updates.
8
11
  POLYNOMIAL = 0xc96c5795d7870f42
9
12
 
13
+ # Calculates the 64-bit checksum used to validate a committed root trailer.
14
+ # @param bytes [String] binary input bytes
15
+ # @return [Integer]
16
+ # @raise [TypeError] if bytes is not a String
10
17
  def self.call(bytes)
11
18
  raise TypeError, "expected String, got #{bytes.class}" unless bytes.is_a?(String)
12
19
 
@@ -2,10 +2,26 @@
2
2
 
3
3
  module XitDB
4
4
  module Core
5
- # Tracks a bounded collection slot and its ancestor path.
5
+ # A view locating a root value or one nested collection element.
6
+ #
7
+ # Read-only cursors retain a byte boundary. Writable cursors follow copied ancestor paths inside their transaction.
8
+ #
9
+ # Replacing a value invalidates child views. Ending a transaction expires its writable views.
6
10
  class Cursor
11
+ # @!attribute [r] database
12
+ # Database that owns this view.
13
+ # @return [Database]
14
+ # @!attribute [r] transaction
15
+ # Writable transaction, or nil for a read-only view.
16
+ # @return [Transaction, nil]
7
17
  attr_reader :database, :transaction
8
18
 
19
+ # Creates a view of one slot with an explicit read boundary.
20
+ # @param database [Database] database that owns the stored records
21
+ # @param slot [Slot] stored value or record descriptor
22
+ # @param bound [Integer] exclusive upper byte boundary for reads
23
+ # @param transaction [Transaction] active destination transaction
24
+ # @return [Cursor]
9
25
  def initialize(database:, slot:, bound:, transaction: nil)
10
26
  @database = database
11
27
  @slot = slot
@@ -15,14 +31,24 @@ module XitDB
15
31
  @children = ObjectSpace::WeakMap.new
16
32
  end
17
33
 
34
+ # Resolves the current slot through ancestors and checks view validity.
35
+ # @return [Slot]
36
+ # @raise [ExpiredViewError] if this view or an ancestor was replaced, removed, or discarded
37
+ # @raise [ClosedError] if the database is closed
18
38
  def slot
19
39
  database.check_open!
40
+ unless parent
41
+ transaction&.check_cursor!(self)
42
+ raise ExpiredViewError, "cursor ancestor was replaced" unless valid?
43
+
44
+ return local_slot
45
+ end
20
46
  # @type var path: Array[Cursor]
21
47
  path = []
22
48
  ancestor = self
23
49
  loop do
24
50
  transaction&.check_cursor!(ancestor)
25
- raise ExpiredViewError, "cursor ancestor was replaced" unless ancestor.valid
51
+ raise ExpiredViewError, "cursor ancestor was replaced" unless ancestor.valid?
26
52
  break unless ancestor.parent
27
53
 
28
54
  path << ancestor
@@ -40,11 +66,17 @@ module XitDB
40
66
  value
41
67
  end
42
68
 
69
+ # Returns the storage boundary after checking view validity.
70
+ # @return [Integer]
43
71
  def bound
44
72
  slot
45
73
  transaction ? transaction.length : @bound
46
74
  end
47
75
 
76
+ # Replaces this value and invalidates views of its former children.
77
+ # @param slot [Slot] stored value or record descriptor
78
+ # @return [self]
79
+ # @raise [ReadOnlyError] if this cursor has no transaction
48
80
  def replace(slot)
49
81
  database.check_open!
50
82
  raise ReadOnlyError, "cursor is read-only" unless transaction
@@ -58,6 +90,12 @@ module XitDB
58
90
  self
59
91
  end
60
92
 
93
+ # Finds a child by index or encoded key for a collection kind.
94
+ # @param kind [Symbol] requested collection slot tag
95
+ # @param selector [Integer, String] array index or encoded collection key
96
+ # @return [Cursor, nil]
97
+ # @raise [ArgumentError] if kind is unsupported
98
+ # @raise [TypeError] if selector has the wrong type for the collection
61
99
  def child(kind:, selector:)
62
100
  unless %i[array_list linked_array_list sorted_map sorted_set].include?(kind) || HashMap::TAGS.include?(kind)
63
101
  raise ArgumentError, "unsupported child kind: #{kind.inspect}"
@@ -65,17 +103,22 @@ module XitDB
65
103
  return nil if slot.tag == :none
66
104
 
67
105
  if kind == :array_list
68
- ArrayList.new(self).cursor_at(integer_selector(selector))
106
+ ArrayList.new(self).cursor_at(integer_selector!(selector))
69
107
  elsif kind == :linked_array_list
70
- LinkedArrayList.new(self).cursor_at(integer_selector(selector))
108
+ LinkedArrayList.new(self).cursor_at(integer_selector!(selector))
71
109
  elsif %i[sorted_map sorted_set].include?(kind)
72
- SortedMap.new(self).cursor_at(string_selector(selector))
110
+ SortedMap.new(self).cursor_at(string_selector!(selector))
73
111
  else
74
- HashMap.from_cursor(self).cursor_at(string_selector(selector))
112
+ HashMap.from_cursor(self).cursor_at(string_selector!(selector))
75
113
  end
76
114
  end
77
115
 
78
- # Collection updates keep child paths live while replacing copied ancestors.
116
+ # Publishes a copied collection path while retaining valid child views.
117
+ # @param slot [Slot] stored value or record descriptor
118
+ # @param propagate [Boolean] whether to update parent collection paths immediately
119
+ # @return [self]
120
+ # @raise [ReadOnlyError] if this cursor has no transaction
121
+ # @api private
79
122
  def update_collection(slot, propagate: true)
80
123
  transaction = self.transaction
81
124
  raise ReadOnlyError, "cursor is read-only" unless transaction
@@ -94,17 +137,32 @@ module XitDB
94
137
  self
95
138
  end
96
139
 
140
+ # Finds or creates a child view for an array position.
141
+ # @param index [Integer] zero-based element index; supported negative indexes count from the end
142
+ # @param slot [Slot] stored value or record descriptor
143
+ # @return [Cursor]
144
+ # @api private
97
145
  def array_child(index, slot)
98
146
  cached_child(index, slot)
99
147
  end
100
148
 
149
+ # Finds or creates a child view for an encoded collection key.
150
+ # @param hash_bytes [String] precomputed binary digest with the database header hash width
151
+ # @param slot [Slot] stored value or record descriptor
152
+ # @return [Cursor]
153
+ # @api private
101
154
  def hash_child(hash_bytes, slot)
102
155
  cached_child(hash_bytes, slot)
103
156
  end
104
157
 
158
+ # Reuses a valid child view or registers a new one.
159
+ # @param index [Integer, String] array index or encoded collection key
160
+ # @param slot [Slot] stored value or record descriptor
161
+ # @return [Cursor]
162
+ # @api private
105
163
  def cached_child(index, slot)
106
164
  @children.each_pair do |child, selector|
107
- next unless selector == index && child.valid
165
+ next unless selector == index && child.valid?
108
166
 
109
167
  begin
110
168
  child.slot
@@ -124,6 +182,12 @@ module XitDB
124
182
  child
125
183
  end
126
184
 
185
+ # Invalidates selected child views after replacement, removal, or index shifts.
186
+ # @param index [Integer, String, nil] exact child selector to invalidate, or nil for all selectors
187
+ # @param from [Integer, nil] first array index whose views to invalidate
188
+ # @param except [Cursor, nil] child view to keep valid
189
+ # @return [void]
190
+ # @api private
127
191
  def invalidate_children(index: nil, from: nil, except: nil)
128
192
  @children.each_pair do |child, selector|
129
193
  next if child.equal?(except)
@@ -134,55 +198,80 @@ module XitDB
134
198
  end
135
199
  end
136
200
 
137
- # These states are internal transaction snapshots, including invalid views.
201
+ # Captures the local slot and validity flag for rollback.
202
+ # @return [Array(Slot, Boolean)]
203
+ # @api private
138
204
  def checkpoint_state
139
205
  [@slot, @valid]
140
206
  end
141
207
 
208
+ # Restores a saved local slot and validity flag.
209
+ # @param state [Array(Slot, Boolean)] saved slot and validity flag
210
+ # @return [Array(Slot, Boolean)]
211
+ # @api private
142
212
  def restore_checkpoint_state(state)
143
213
  @slot, @valid = state
144
214
  end
145
215
 
216
+ # Reads this cursor's byte value inside its storage boundary.
217
+ # @return [ByteValue]
146
218
  def read_bytes
147
219
  database.read_bytes(slot, bound: bound)
148
220
  end
149
221
 
150
222
  protected
151
223
 
224
+ # Reads a collection slot using a checked selector.
152
225
  def collection_get(selector)
153
226
  target = collection
154
227
  if target.is_a?(ArrayList) || target.is_a?(LinkedArrayList)
155
- target.get(integer_selector(selector))
228
+ target.get(integer_selector!(selector))
156
229
  else
157
- target.get(string_selector(selector))
230
+ target.get(string_selector!(selector))
158
231
  end
159
232
  end
160
233
 
234
+ # Updates a child and forwards ownership and ancestor propagation options.
161
235
  def collection_replace(selector, slot, owner: nil, collection: false, propagate: true)
162
236
  target = self.collection
163
237
  if target.is_a?(ArrayList) || target.is_a?(LinkedArrayList)
164
- target.replace_child(integer_selector(selector), slot, owner: owner, collection: collection,
165
- propagate: propagate)
238
+ target.replace_child(integer_selector!(selector), slot, owner: owner, collection: collection,
239
+ propagate: propagate)
166
240
  else
167
- target.replace_child(string_selector(selector), slot, owner: owner, collection: collection,
168
- propagate: propagate)
241
+ target.replace_child(string_selector!(selector), slot, owner: owner, collection: collection,
242
+ propagate: propagate)
169
243
  end
170
244
  end
171
245
 
172
- def integer_selector(selector)
246
+ # Checks that an array selector is an Integer.
247
+ def integer_selector!(selector)
173
248
  raise TypeError, "array index must be an Integer" unless selector.is_a?(Integer)
174
249
 
175
250
  selector
176
251
  end
177
252
 
178
- def string_selector(selector)
253
+ # Checks that a collection selector is a String.
254
+ def string_selector!(selector)
179
255
  raise TypeError, "collection key must be a String" unless selector.is_a?(String)
180
256
 
181
257
  selector
182
258
  end
183
259
 
184
- attr_reader :parent, :selector, :valid
260
+ # @!attribute [r] parent
261
+ # Ancestor view that contains this element.
262
+ # @return [Cursor, nil]
263
+ # @!attribute [r] selector
264
+ # Index or encoded key locating this child in its parent.
265
+ # @return [Integer, String]
266
+ attr_reader :parent, :selector
267
+
268
+ # Reports whether this view has avoided explicit invalidation.
269
+ # @return [Boolean]
270
+ def valid?
271
+ @valid
272
+ end
185
273
 
274
+ # Chooses the collection reader from the current slot tag.
186
275
  def collection
187
276
  case slot.tag
188
277
  when :array_list then ArrayList.new(self)
@@ -193,6 +282,7 @@ module XitDB
193
282
  end
194
283
  end
195
284
 
285
+ # Returns the saved slot without resolving the ancestor path.
196
286
  def local_slot
197
287
  @slot
198
288
  end