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
@@ -6,21 +6,47 @@ require_relative "replication"
6
6
 
7
7
  module XitDB
8
8
  module Core
9
- # Coordinates core storage, transactions, and committed roots.
9
+ # The advanced API for binary storage, root slots, and atomic transactions.
10
+ #
11
+ # Most applications use XitDB::Database, which converts Ruby values to slots.
12
+ #
13
+ # Each commit appends records and a checked root trailer, then publishes the new root.
14
+ #
15
+ # Read-only root cursors retain their original byte boundary while later transactions append data.
16
+ #
17
+ # @example Store a scalar root through the advanced API
18
+ # database = XitDB::Core::Database.memory
19
+ # database.transaction { |root| root.replace(XitDB::Core::Slot.uint(7)) }
20
+ # database.root_cursor.slot.value # => 7
21
+ # database.close
10
22
  class Database
11
23
  include Replication
12
24
 
13
- ROOT_OFFSET = 20
14
- DATA_OFFSET = 37
25
+ # Bytes in a root trailer: slot, commit identifier, and checksum.
15
26
  TRAILER_SIZE = 25
16
- MINIMUM_SIZE = 62
27
+ # Smallest possible complete database, using the version 2 root header.
28
+ MINIMUM_SIZE = 57
17
29
 
30
+ # @!attribute [r] header
31
+ # Validated immutable file profile.
32
+ # @return [Header]
18
33
  attr_reader :header
19
34
 
20
- def self.open(path, readonly: false, **)
35
+ # Opens a database file and closes it after an optional block.
36
+ # @param path [String] database file path
37
+ # @param readonly [Boolean] whether to reject writes
38
+ # @param format_version [Integer] file format version used when creating a file
39
+ # Additional keyword options are forwarded to {#initialize}.
40
+ # @return [Database, Object]
41
+ # @yield [database] uses the database before automatic close
42
+ # @yieldparam database [Database] opened database
43
+ # @yieldreturn [Object] result returned by open when a block is supplied
44
+ # @see #initialize
45
+ def self.open(path, readonly: false, format_version: Header::VERSION, **)
46
+ Header.validate_version!(format_version)
21
47
  store = FileStore.open(path, readonly: readonly)
22
48
  begin
23
- database = new(store: store, **)
49
+ database = new(store: store, format_version: format_version, **)
24
50
  rescue Exception # rubocop:disable Lint/RescueException -- Cleanup must also preserve nonstandard exceptions.
25
51
  store.send(:close_unreturned)
26
52
  raise
@@ -34,22 +60,47 @@ module XitDB
34
60
  end
35
61
  end
36
62
 
63
+ # Creates an empty database that stores all bytes in memory.
64
+ # @param hash_size [Integer] number of bytes in each stored digest
65
+ # @param hash_id [String] four-byte hash algorithm identifier
66
+ # @param file_id [Integer, nil] unsigned 64-bit file identifier; nil uses the stored value or creation default
67
+ # @return [Database]
37
68
  def self.memory(hash_size: 20, hash_id: "sha1", file_id: nil)
38
69
  new(store: MemoryStore.new, hash_size: hash_size, hash_id: hash_id, file_id: file_id)
39
70
  end
40
71
 
72
+ # Creates an open database from a complete replication stream.
73
+ # @param to [String] destination file path, which must be empty or absent
74
+ # @param source_io [#read] binary reader implementing read(length)
75
+ # @param length [Integer] number of bytes
76
+ # @return [Database]
77
+ # @see Replication.copy_replica
41
78
  def self.copy_replica(to:, source_io:, length:)
42
79
  Replication.copy_replica(to: to, source_io: source_io, length: length)
43
80
  end
44
81
 
82
+ # Validates an existing store or initializes an empty writable store.
83
+ # @param store [MemoryStore, FileStore] underlying byte storage
84
+ # @param hash_size [Integer, nil] number of bytes in each stored digest; nil uses the stored value or creation
85
+ # default
86
+ # @param hash_id [String, nil] four-byte hash algorithm identifier; nil uses the stored value or creation default
87
+ # @param file_id [Integer, nil] unsigned 64-bit file identifier; nil uses the stored value or creation default
88
+ # @param lock_timeout [Float] maximum wait for the exclusive writer lock, in seconds
89
+ # @param initialize_empty [Boolean] whether an empty writable store may be initialized
90
+ # @param require_empty [Boolean] whether opening must reject a nonempty store
91
+ # @param format_version [Integer] file format version used only when creating a database
92
+ # @return [Database]
93
+ # @raise [CorruptionError] if the header, root, or existing empty store is invalid
94
+ # @raise [ProfileMismatchError] if supplied profile fields differ from the stored header
95
+ # @raise [ArgumentError] if require_empty is true and the store contains data
45
96
  def initialize(store:, hash_size: nil, hash_id: nil, file_id: nil, lock_timeout: 5.0, initialize_empty: true,
46
- require_empty: false)
97
+ require_empty: false, format_version: Header::VERSION)
47
98
  @store = store
48
99
  @lock_timeout = lock_timeout
49
100
  @needs_reopen = false
50
101
  @transaction = nil
51
102
  initialize_file = lambda do
52
- prepare_file(hash_size, hash_id, file_id, initialize_empty, require_empty)
103
+ prepare_file(hash_size, hash_id, file_id, initialize_empty, require_empty, format_version)
53
104
  end
54
105
  if store.readonly?
55
106
  initialize_file.call
@@ -60,36 +111,62 @@ module XitDB
60
111
  raise CorruptionError, e.message
61
112
  end
62
113
 
114
+ # Closes the store after active operations and writers finish.
115
+ # @return [void]
63
116
  def close
64
117
  @store.close
65
118
  end
66
119
 
120
+ # Tests whether the underlying store is closed.
121
+ # @return [Boolean]
67
122
  def closed?
68
123
  @store.closed?
69
124
  end
70
125
 
126
+ # Keeps storage open throughout a multi-call operation.
127
+ # @return [Object]
128
+ # @yield runs while database close waits
129
+ # @yieldreturn [Object] result returned to the caller
130
+ # @api private
71
131
  def with_operation(&)
72
132
  @store.with_operation(&)
73
133
  end
74
134
 
135
+ # Returns the identity used to detect shared underlying storage.
136
+ # @return [Object, Array<Integer>]
75
137
  def storage_identity
76
138
  check_open!
77
139
  @store.storage_identity
78
140
  end
79
141
 
142
+ # Tests whether a storage failure requires reopening before another write.
143
+ # @return [Boolean]
80
144
  def needs_reopen?
81
145
  @needs_reopen
82
146
  end
83
147
 
148
+ # Rejects operations after the database closes.
149
+ # @return [void]
150
+ # @raise [ClosedError] if the database has been closed
151
+ # @api private
84
152
  def check_open!
85
153
  raise ClosedError, "database is closed" if closed?
86
154
  end
87
155
 
156
+ # Returns the byte boundary of the last validated committed root.
157
+ # @return [Integer]
88
158
  def committed_size
89
159
  committed_state.first
90
160
  end
91
161
 
92
- def compact(to:)
162
+ # Copies the current reachable value to an empty target with a new file identifier.
163
+ # @param to [String] destination file path, which must be empty or absent
164
+ # @param format_version [Integer] file format version of the destination
165
+ # @return [Database]
166
+ # @note An array-list root is treated as history; only its latest element is retained.
167
+ # @raise [ArgumentError] if the target is nonempty or identifies the source file
168
+ def compact(to:, format_version: Header::VERSION)
169
+ Header.validate_version!(format_version)
93
170
  with_operation do
94
171
  # @type var offsets_for_cleanup: OffsetMap?
95
172
  offsets_for_cleanup = nil
@@ -106,7 +183,7 @@ module XitDB
106
183
  file_id = random_id
107
184
  file_id = random_id while file_id == header.file_id
108
185
  target = Database.new(store: store, hash_id: header.hash_id, hash_size: header.hash_size, file_id: file_id,
109
- lock_timeout: @lock_timeout, require_empty: true)
186
+ lock_timeout: @lock_timeout, require_empty: true, format_version: format_version)
110
187
  target_for_cleanup = target
111
188
  offsets = OffsetMap.new
112
189
  offsets_for_cleanup = offsets
@@ -124,11 +201,22 @@ module XitDB
124
201
  end
125
202
  end
126
203
 
204
+ # Creates a read-only view of the last validated committed root.
205
+ # @return [Cursor]
127
206
  def root_cursor
128
207
  size, slot = committed_state
129
208
  Cursor.new(database: self, slot: slot, bound: size)
130
209
  end
131
210
 
211
+ # Runs a writable root block, then commits and returns a fresh read-only root.
212
+ # @return [Cursor]
213
+ # @yield [root] changes the transaction-owned root
214
+ # @yieldparam root [Cursor] writable root, valid only inside the block
215
+ # @yieldreturn [Object] ignored; changes to root determine the committed value
216
+ # @raise [BusyError] if the writer lock cannot be acquired in time
217
+ # @raise [TransactionStateError] if writes require reopening or a nested writer is attempted
218
+ # @raise [CommitError] if storage fails; inspect its outcome before retrying
219
+ # @note Exceptions and nonlocal exits from the block do not publish its root.
132
220
  def transaction
133
221
  check_open!
134
222
  raise TransactionStateError, "database requires reopening" if @needs_reopen
@@ -166,6 +254,7 @@ module XitDB
166
254
  handle_transaction_error(e, callback_error, callback_completed, outcome || :not_committed)
167
255
  end
168
256
 
257
+ # Preserves caller failures and reports storage failures with their commit outcome.
169
258
  def handle_transaction_error(error, callback_error, callback_completed, outcome)
170
259
  if callback_error && !error.equal?(callback_error)
171
260
  @needs_reopen = true
@@ -178,14 +267,27 @@ module XitDB
178
267
  end
179
268
  private :handle_transaction_error
180
269
 
181
- def bytes(data, format_tag: nil)
182
- transaction = active_transaction
270
+ # Allocates a byte value inside the active transaction.
271
+ # @param data [String] payload bytes
272
+ # @param format_tag [String, nil] optional two-byte application format identifier
273
+ # @param prefix [String] owned bytes prepended without joining the full payload
274
+ # @return [Slot]
275
+ # @raise [TransactionStateError] if no active transaction exists
276
+ def bytes(data, format_tag: nil, prefix: "".b)
277
+ transaction = active_transaction!
183
278
  value = ByteValue.new(data, format_tag: format_tag)
184
- Bytes.append(transaction, size: value.bytes.bytesize, format_tag: value.format_tag) do |position, length|
279
+ prefix = ByteValue.new(prefix).bytes
280
+ Bytes.append(transaction, size: value.bytes.bytesize, format_tag: value.format_tag,
281
+ prefix: prefix) do |position, length|
185
282
  Format.slice(value.bytes, position, length)
186
283
  end
187
284
  end
188
285
 
286
+ # Loads a byte slot and its optional format tag inside a read boundary.
287
+ # @param slot [Slot] stored value or record descriptor
288
+ # @param bound [Integer, nil] exclusive upper byte boundary for reads; nil uses committed_size
289
+ # @return [ByteValue]
290
+ # @raise [InvalidValueError] if slot does not contain bytes
189
291
  def read_bytes(slot, bound: nil)
190
292
  check_open!
191
293
  bound ||= committed_size
@@ -193,6 +295,12 @@ module XitDB
193
295
  ByteValue.new(source.read(0, source.size), format_tag: source.format_tag)
194
296
  end
195
297
 
298
+ # Reads allocated data inside a checked database boundary.
299
+ # @param offset [Integer] absolute byte offset
300
+ # @param size [Integer] number of bytes
301
+ # @param bound [Integer] exclusive upper byte boundary for reads
302
+ # @return [String]
303
+ # @raise [CorruptionError] if the range is outside stored object data or its bound
196
304
  def read_at(offset, size, bound:)
197
305
  check_open!
198
306
  check_range!(offset, size, bound)
@@ -203,10 +311,11 @@ module XitDB
203
311
 
204
312
  private
205
313
 
314
+ # Checks target ownership and publishes a copied root, retaining the history container when present.
206
315
  def copy_compacted_root(target, store, file_id, source, slot, history, offsets)
207
316
  target.transaction do |root|
208
317
  current = Header.parse(store.read_at(0, Header::SIZE))
209
- unless current.file_id == file_id && root.bound == MINIMUM_SIZE && root.slot.empty?
318
+ unless current.file_id == file_id && root.bound == current.data_offset + TRAILER_SIZE && root.slot.empty?
210
319
  raise ArgumentError, "compaction target changed before copying"
211
320
  end
212
321
 
@@ -222,6 +331,7 @@ module XitDB
222
331
  end
223
332
  end
224
333
 
334
+ # Closes scratch resources and restores an unpublished empty target when safe.
225
335
  def cleanup_compaction(store, target, offsets, published)
226
336
  begin
227
337
  offsets&.close
@@ -232,6 +342,7 @@ module XitDB
232
342
  store.send(:close_unreturned)
233
343
  end
234
344
 
345
+ # Expires writable views and removes uncommitted data when rollback remains safe.
235
346
  def finish_transaction(transaction, size, outcome, callback_completed, pending_error)
236
347
  transaction.expire!
237
348
  @transaction = nil
@@ -248,32 +359,36 @@ module XitDB
248
359
  end
249
360
  end
250
361
 
251
- def prepare_file(hash_size, hash_id, file_id, initialize_empty, require_empty)
362
+ # Checks profile compatibility or initializes an allowed empty store.
363
+ def prepare_file(hash_size, hash_id, file_id, initialize_empty, require_empty, format_version)
252
364
  raise ArgumentError, "compaction target must be empty" if require_empty && !@store.empty?
253
365
 
254
366
  if @store.empty?
255
367
  raise CorruptionError, "empty read-only database" if @store.readonly?
256
368
  raise CorruptionError, "existing empty database" unless initialize_empty
257
369
 
258
- initialize_empty_file(hash_size, hash_id, file_id, require_empty)
370
+ initialize_empty_file(hash_size, hash_id, file_id, require_empty, format_version)
259
371
  else
260
372
  @header = Header.parse(@store.read_at(0, Header::SIZE))
261
- check_header(:hash_size, hash_size, @header.hash_size)
262
- check_header(:hash_id, hash_id, @header.hash_id)
263
- check_header(:file_id, file_id, @header.file_id)
373
+ check_header!(:hash_size, hash_size, @header.hash_size)
374
+ check_header!(:hash_id, hash_id, @header.hash_id)
375
+ check_header!(:file_id, file_id, @header.file_id)
264
376
  committed_state
265
377
  end
266
378
  end
267
379
 
268
- def initialize_empty_file(hash_size, hash_id, file_id, require_empty)
269
- @header = Header.new(hash_size: hash_size || 20, hash_id: hash_id || "sha1", file_id: file_id || random_id)
270
- @store.write_at(0, @header.to_bytes + ("\0".b * 17))
380
+ # Writes the format header and publishes the initial empty root.
381
+ def initialize_empty_file(hash_size, hash_id, file_id, require_empty, format_version)
382
+ @header = Header.new(hash_size: hash_size || 20, hash_id: hash_id || "sha1", file_id: file_id || random_id,
383
+ version: format_version)
384
+ @store.write_at(0, @header.to_bytes + ("\0".b * (@header.data_offset - Header::SIZE)))
271
385
  publish(Slot.new, 0)
272
386
  rescue Exception # rubocop:disable Lint/RescueException -- Cleanup must also preserve nonstandard exceptions.
273
387
  reset_failed_initialization(require_empty)
274
388
  raise
275
389
  end
276
390
 
391
+ # Truncates a failed private target while its initialization lock is held.
277
392
  def reset_failed_initialization(require_empty)
278
393
  # The exclusive initialization lock still owns this empty target.
279
394
  @store.truncate(0) if require_empty && !@needs_reopen
@@ -281,16 +396,19 @@ module XitDB
281
396
  nil
282
397
  end
283
398
 
284
- def check_header(name, expected, actual)
399
+ # Rejects a requested profile value that differs from the file header.
400
+ def check_header!(name, expected, actual)
285
401
  return if expected.nil? || expected == actual
286
402
 
287
403
  raise ProfileMismatchError, "#{name} does not match the database header"
288
404
  end
289
405
 
406
+ # Closes a database handle that failed before it could be returned.
290
407
  def close_unreturned
291
408
  @store.send(:close_unreturned)
292
409
  end
293
410
 
411
+ # Restores an unpublished target only while its file generation and empty root still match.
294
412
  def restore_empty_target
295
413
  return if needs_reopen?
296
414
 
@@ -299,7 +417,7 @@ module XitDB
299
417
  next unless current.file_id == header.file_id
300
418
 
301
419
  size, slot = committed_state
302
- @store.truncate(0) if size == MINIMUM_SIZE && slot.empty?
420
+ @store.truncate(0) if size == current.data_offset + TRAILER_SIZE && slot.empty?
303
421
  end
304
422
  rescue Exception # rubocop:disable Lint/RescueException -- Cleanup must also preserve nonstandard exceptions.
305
423
  # Cleanup must preserve the original failure or nonlocal exit. A new
@@ -309,7 +427,8 @@ module XitDB
309
427
 
310
428
  protected :restore_empty_target
311
429
 
312
- def active_transaction
430
+ # Returns the active transaction after checking thread ownership.
431
+ def active_transaction!
313
432
  transaction = @transaction
314
433
  raise TransactionStateError, "allocation requires a transaction" unless transaction
315
434
 
@@ -317,17 +436,20 @@ module XitDB
317
436
  transaction
318
437
  end
319
438
 
439
+ # Rejects data reads outside the object region and read boundary.
320
440
  def check_range!(offset, size, bound)
321
441
  unless offset.is_a?(Integer) && size.is_a?(Integer) && bound.is_a?(Integer) &&
322
- offset >= DATA_OFFSET && size >= 0 && offset + size <= bound
442
+ offset >= header.data_offset && size >= 0 && offset + size <= bound
323
443
  raise CorruptionError, "object exceeds its read boundary"
324
444
  end
325
445
  end
326
446
 
447
+ # Validates the published byte boundary and its root trailer.
327
448
  def committed_state
328
449
  check_open!
329
- size = Format.unsigned(@store.read_at(ROOT_OFFSET + Slot::SIZE, 8))
330
- raise CorruptionError, "invalid committed file size" if size < MINIMUM_SIZE || size > @store.length
450
+ size = Format.unsigned(@store.read_at(header.committed_size_offset, 8))
451
+ minimum_size = header.data_offset + TRAILER_SIZE
452
+ raise CorruptionError, "invalid committed file size" if size < minimum_size || size > @store.length
331
453
 
332
454
  slot, = Replication.trailer(@store, header, size, size)
333
455
  [size, slot]
@@ -335,6 +457,7 @@ module XitDB
335
457
  raise CorruptionError, e.message
336
458
  end
337
459
 
460
+ # Synchronizes an appended root trailer before publishing and synchronizing the root pointer.
338
461
  def publish(slot, commit_id)
339
462
  # @type var outcome: :not_committed | :committed | :unknown
340
463
  outcome = :not_committed
@@ -344,13 +467,24 @@ module XitDB
344
467
  @store.append(body + [checksum].pack("Q>"))
345
468
  @store.sync
346
469
  outcome = :unknown
347
- @store.write_at(ROOT_OFFSET, slot.to_bytes + [position + TRAILER_SIZE].pack("Q>"))
470
+ write_root_header(slot, position + TRAILER_SIZE)
348
471
  @store.sync
349
472
  rescue Exception => e # rubocop:disable Lint/RescueException -- Cleanup must also preserve nonstandard exceptions.
350
473
  @needs_reopen = true if outcome == :unknown
351
474
  raise CommitError.new(e.message, outcome: outcome || :not_committed), cause: e
352
475
  end
353
476
 
477
+ # Publishes the size alone in v2. Maintains the cached slot for older v1 readers.
478
+ def write_root_header(slot, size)
479
+ bytes = [size].pack("Q>")
480
+ if header.version == 1
481
+ @store.write_at(Header::SIZE, slot.to_bytes + bytes)
482
+ else
483
+ @store.write_at(header.committed_size_offset, bytes)
484
+ end
485
+ end
486
+
487
+ # Generates an unsigned 64-bit identifier from random bytes.
354
488
  def random_id
355
489
  Format.unsigned(SecureRandom.random_bytes(8))
356
490
  end
@@ -2,16 +2,37 @@
2
2
 
3
3
  module XitDB
4
4
  module Core
5
- # A synchronized file store with bounded write buffering.
5
+ # A synchronized file store with bounded buffering and exclusive writer locks.
6
+ #
7
+ # Reads include pending buffered bytes. Flush writes them to the file.
8
+ # Sync also synchronizes the file and its directory.
9
+ #
10
+ # Closing flushes pending data unless discard is requested.
6
11
  class FileStore
7
12
  include Store
8
13
 
14
+ # @!attribute [r] storage_identity
15
+ # Identity shared by handles referring to the same underlying storage.
16
+ # @return [Object, Array<Integer>]
9
17
  attr_reader :storage_identity
10
18
 
19
+ # Process-local registry of a mutex and open handle count for each file identity.
20
+ # @api private
11
21
  WRITERS = {} # rubocop:disable Style/MutableConstant -- Writer registry updates are protected by WRITERS_MUTEX.
22
+ # Mutex protecting changes to the process-local writer registry.
23
+ # @api private
12
24
  WRITERS_MUTEX = Mutex.new
13
25
  private_constant :WRITERS, :WRITERS_MUTEX
14
26
 
27
+ # Opens a binary file store with a bounded write buffer.
28
+ # @param path [String] database file path
29
+ # @param readonly [Boolean] whether to reject writes
30
+ # @param buffer_limit [Integer] positive maximum buffer size in bytes
31
+ # @param create [Boolean] whether to create a missing file
32
+ # @param exclusive [Boolean] whether creation must fail if the file exists
33
+ # @return [FileStore]
34
+ # @raise [ArgumentError] if buffer_limit is not positive or exclusive options conflict
35
+ # @raise [Errno::EEXIST] if exclusive creation finds an existing file
15
36
  def self.open(path, readonly: false, buffer_limit: 2 * 1024 * 1024, create: true, exclusive: false)
16
37
  raise TypeError, "buffer_limit must be an Integer" unless buffer_limit.is_a?(Integer)
17
38
  raise ArgumentError, "buffer_limit must be positive" unless buffer_limit.positive?
@@ -27,6 +48,7 @@ module XitDB
27
48
  end
28
49
  end
29
50
 
51
+ # Opens the file with the requested creation and exclusivity flags.
30
52
  def self.open_file(path, readonly, create, exclusive)
31
53
  flags = readonly ? File::RDONLY : File::RDWR
32
54
  return File.open(path, flags) unless create && !readonly
@@ -41,6 +63,12 @@ module XitDB
41
63
  end
42
64
  private_class_method :open_file
43
65
 
66
+ # Wraps a file and shares writer coordination with handles for the same inode.
67
+ # @param file [File] opened file handle owned by this store
68
+ # @param readonly [Boolean] whether to reject writes
69
+ # @param buffer_limit [Integer] positive maximum buffer size in bytes
70
+ # @param sync_directory [String, nil] directory to synchronize on the first durable write
71
+ # @return [FileStore]
44
72
  def initialize(file, readonly, buffer_limit, sync_directory: nil)
45
73
  @file = file.binmode
46
74
  @sync_directory = sync_directory
@@ -59,17 +87,21 @@ module XitDB
59
87
  initialize_state(writer)
60
88
  end
61
89
 
90
+ # Tests whether this file handle rejects writes.
91
+ # @return [Boolean]
62
92
  def readonly?
63
93
  @readonly
64
94
  end
65
95
 
66
96
  private
67
97
 
98
+ # Combines disk length with the end of buffered data.
68
99
  def store_length
69
100
  disk_length = @file.stat.size
70
101
  @pending.empty? ? disk_length : [disk_length, @pending_offset + @pending.bytesize].max
71
102
  end
72
103
 
104
+ # Combines disk bytes, zero-filled gaps, and pending writes into one read.
73
105
  def read_bytes(offset, length)
74
106
  return read_file(offset, length) if @pending.empty?
75
107
 
@@ -91,6 +123,7 @@ module XitDB
91
123
  result
92
124
  end
93
125
 
126
+ # Repeats positioned reads until the requested range is complete.
94
127
  def read_file(offset, length)
95
128
  result = "".b
96
129
  while result.bytesize < length
@@ -102,6 +135,7 @@ module XitDB
102
135
  result
103
136
  end
104
137
 
138
+ # Buffers a compatible write, flushing first when the buffer cannot hold it.
105
139
  def write_bytes(offset, bytes)
106
140
  if bytes.bytesize > @buffer_limit
107
141
  flush_bytes
@@ -117,6 +151,7 @@ module XitDB
117
151
  @pending[offset - @pending_offset, bytes.bytesize] = bytes
118
152
  end
119
153
 
154
+ # Repeats positioned writes until all bytes have reached the file.
120
155
  def write_file(offset, bytes)
121
156
  written = 0
122
157
  while written < bytes.bytesize
@@ -127,6 +162,7 @@ module XitDB
127
162
  end
128
163
  end
129
164
 
165
+ # Changes disk length and removes buffered bytes beyond the new end.
130
166
  def truncate_bytes(length)
131
167
  retry_interrupted { @file.truncate(length) }
132
168
  if length <= @pending_offset
@@ -136,6 +172,7 @@ module XitDB
136
172
  end
137
173
  end
138
174
 
175
+ # Writes the pending buffer to the file and clears it.
139
176
  def flush_bytes
140
177
  return if @pending.empty?
141
178
 
@@ -144,6 +181,7 @@ module XitDB
144
181
  nil
145
182
  end
146
183
 
184
+ # Synchronizes the file and its containing directory when required.
147
185
  def sync_bytes
148
186
  retry_interrupted { @file.fsync }
149
187
  sync_directory = @sync_directory
@@ -156,6 +194,7 @@ module XitDB
156
194
  nil
157
195
  end
158
196
 
197
+ # Closes the file and removes unused writer coordination state.
159
198
  def close_bytes
160
199
  @file.close
161
200
  WRITERS_MUTEX.synchronize do
@@ -165,6 +204,7 @@ module XitDB
165
204
  end
166
205
  end
167
206
 
207
+ # Acquires the shared thread mutex and the operating system file lock.
168
208
  def lock_writer(deadline)
169
209
  raise TransactionStateError, "writer lock for this file is already held by this thread" if @writer_mutex.owned?
170
210
 
@@ -178,12 +218,14 @@ module XitDB
178
218
  end
179
219
  end
180
220
 
221
+ # Releases the file lock and then the shared thread mutex.
181
222
  def unlock_writer
182
223
  retry_interrupted { @file.flock(File::LOCK_UN) }
183
224
  ensure
184
225
  super
185
226
  end
186
227
 
228
+ # Repeats an operation interrupted by an operating system signal.
187
229
  def retry_interrupted
188
230
  yield
189
231
  rescue Errno::EINTR