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,11 +6,24 @@ require_relative "conversion"
6
6
  module XitDB
7
7
  # Owns the profile, history, and transactions of a public database.
8
8
  class Database
9
+ # @!attribute [r] core
10
+ # Raw storage API for operations such as replication.
11
+ # @return [Core::Database]
12
+ # @!attribute [r] profile
13
+ # Rules used to interpret values and collection keys.
14
+ # @return [Profiles::Portable, Profiles::Ruby]
9
15
  attr_reader :core, :profile
10
16
 
17
+ # Resolve a portable hash algorithm and reject the reserved Ruby identifier.
18
+ # @api private
19
+ # @param value [Symbol, Core::Hasher] algorithm name or configured hasher
20
+ # @return [Core::Hasher]
21
+ # @raise [ProfileMismatchError] if the hasher uses a reserved Ruby profile identifier
11
22
  def self.hasher(value)
12
23
  if value.is_a?(Core::Hasher)
13
- raise ProfileMismatchError, "rb01 is reserved for XitDB::Ruby" if value.id == "rb01"
24
+ if %w[rb01 rb02 rb03 rb04].include?(value.id)
25
+ raise ProfileMismatchError, "#{value.id} is reserved for XitDB::Ruby"
26
+ end
14
27
 
15
28
  return value
16
29
  end
@@ -24,14 +37,36 @@ module XitDB
24
37
  end
25
38
  end
26
39
 
27
- def self.open(path, readonly: false, hash: nil, lock_timeout: 5.0)
40
+ # Open a portable database, creating a missing file.
41
+ #
42
+ # A profile defines which Ruby values a file can represent. Portable files
43
+ # use the upstream xitdb rules. Ruby-profile files require {Ruby.open}.
44
+ # With a block, the handle closes even if the block raises an exception.
45
+ # Without a block, the caller must call {#close}.
46
+ #
47
+ # @param path [String] file to open or create
48
+ # @param readonly [Boolean] forbid transactions and require an existing file
49
+ # @param hash [Symbol, Core::Hasher, nil] hash configuration; nil reads the header or defaults to SHA-1
50
+ # @param lock_timeout [Float] seconds to wait for the writer lock
51
+ # @param format_version [Integer] binary format version used when creating a file
52
+ # @yield [database] use the database before automatic closure
53
+ # @yieldparam database [Database] open handle
54
+ # @return [Database, Object] handle without a block, otherwise the block's result
55
+ # @raise [ProfileMismatchError] if the file uses an incompatible profile
56
+ # @raise [CorruptionError] if the existing file has invalid storage data
57
+ # @see XitDB.open
58
+ def self.open(path, readonly: false, hash: nil, lock_timeout: 5.0, format_version: Core::Header::VERSION)
59
+ Core::Header.validate_version!(format_version)
28
60
  selected = hasher(hash) unless hash.nil?
29
61
  # @type var options: { ?hash_id: String, ?hash_size: Integer }
30
62
  options = selected ? { hash_id: selected.id, hash_size: selected.size } : {}
31
63
  store, created = open_store(path, readonly: readonly)
32
64
  begin
33
- core = Core::Database.new(store: store, initialize_empty: created, lock_timeout: lock_timeout, **options)
34
- raise ProfileMismatchError, "Ruby profile file requires XitDB::Ruby.open" if core.header.hash_id == "rb01"
65
+ core = Core::Database.new(store: store, initialize_empty: created, lock_timeout: lock_timeout,
66
+ format_version: format_version, **options)
67
+ if %w[rb01 rb02 rb03 rb04].include?(core.header.hash_id)
68
+ raise ProfileMismatchError, "Ruby profile file requires XitDB::Ruby.open"
69
+ end
35
70
 
36
71
  selected ||= header_hasher(core.header)
37
72
  database = new(core: core, profile: Profiles::Portable.new(hasher: selected), readonly: readonly)
@@ -48,6 +83,10 @@ module XitDB
48
83
  end
49
84
  end
50
85
 
86
+ # Match the file's hash identifier and digest size to a builtin algorithm.
87
+ # @param header [Core::Header]
88
+ # @return [Core::Hasher]
89
+ # @raise [ProfileMismatchError] if explicit configuration is required
51
90
  def self.header_hasher(header)
52
91
  case [header.hash_id, header.hash_size]
53
92
  when ["sha1", 20] then Core::Hasher.sha1
@@ -59,6 +98,10 @@ module XitDB
59
98
  end
60
99
  private_class_method :header_hasher
61
100
 
101
+ # Create exclusively first, so opening an existing empty file cannot initialize it.
102
+ # @param path [String]
103
+ # @param readonly [Boolean]
104
+ # @return [Array(Core::FileStore, Boolean)] storage and whether this call created it
62
105
  def self.open_store(path, readonly:)
63
106
  return [Core::FileStore.open(path, readonly: true), false] if readonly
64
107
 
@@ -70,6 +113,13 @@ module XitDB
70
113
  end
71
114
  private_class_method :open_store
72
115
 
116
+ # Create a portable database that stores bytes only in this process.
117
+ #
118
+ # Closing discards its data. The block form closes automatically.
119
+ # @param hash [Symbol, Core::Hasher] portable hash algorithm
120
+ # @yield [database] work with the temporary database
121
+ # @yieldparam database [Database]
122
+ # @return [Database, Object] handle or block result
73
123
  def self.memory(hash: :sha1)
74
124
  selected = hasher(hash)
75
125
  database = new(core: Core::Database.memory(hash_id: selected.id, hash_size: selected.size),
@@ -83,6 +133,11 @@ module XitDB
83
133
  end
84
134
  end
85
135
 
136
+ # Attach a value profile to storage and validate its public root.
137
+ # @api private
138
+ # @param core [Core::Database] owned storage handle
139
+ # @param profile [Profiles::Portable, Profiles::Ruby] value interpretation
140
+ # @param readonly [Boolean] disable public writes
86
141
  def initialize(core:, profile:, readonly: false)
87
142
  @core = core
88
143
  @profile = profile
@@ -90,6 +145,26 @@ module XitDB
90
145
  snapshot
91
146
  end
92
147
 
148
+ # Change values together and return their committed snapshot.
149
+ #
150
+ # The root acts like a Hash. Nested collections are database views.
151
+ # Normal completion commits changes; an exception aborts them.
152
+ # The block's views expire when the transaction ends.
153
+ # A transaction with no logical changes adds no history entry.
154
+ #
155
+ # @yield [root] make related changes under one writer lock
156
+ # @yieldparam root [Views::Map] writable root map
157
+ # @return [Snapshot] committed root, regardless of the block's return value
158
+ # @raise [ReadOnlyError] if the handle forbids writes
159
+ # @raise [BusyError] if the writer lock times out before the block runs
160
+ # @raise [CommitError] if storage publication or synchronization fails
161
+ # @raise [ArgumentError] if no block is supplied
162
+ # @example Commit two related values
163
+ # db.transaction do |root|
164
+ # root["name"] = "Ada"
165
+ # root["visits"] = 1
166
+ # end
167
+ # @see CommitError#outcome
93
168
  def transaction(&block)
94
169
  raise ArgumentError, "transaction requires a block" unless block_given?
95
170
  raise ReadOnlyError, "database is read-only" if @readonly
@@ -97,6 +172,10 @@ module XitDB
97
172
  core.with_operation { perform_transaction(&block) }
98
173
  end
99
174
 
175
+ # Append a logical root only after the user's changes complete.
176
+ # @yield [root] transaction's writable map
177
+ # @yieldparam root [Views::Map]
178
+ # @return [Snapshot] committed state
100
179
  def perform_transaction
101
180
  committed = core.transaction do |history_cursor|
102
181
  array = history_array(history_cursor)
@@ -104,19 +183,25 @@ module XitDB
104
183
  slot = empty ? Core::Slot.new : (array.get(-1) || raise(CorruptionError, "missing history root"))
105
184
  context = Context.new(database: self, root: slot, bound: history_cursor.bound,
106
185
  transaction: history_cursor.transaction)
107
- validate_root(slot, context) unless empty
186
+ validate_root!(slot, context) unless empty
108
187
  root = context.view(slot, path: [], kind: :map)
109
188
  yield root
110
189
  if context.changed?
111
190
  array.append(context.root)
112
191
  else
113
- context.writable_transaction.cancel_publication
192
+ context.writable_transaction!.cancel_publication
114
193
  end
115
194
  end
116
195
  snapshot_from_cursor(committed)
117
196
  end
118
197
  private :perform_transaction
119
198
 
199
+ # Capture the latest root or resolve a saved revision.
200
+ #
201
+ # Later commits do not change this snapshot. Its views require an open handle.
202
+ # @param revision [Revision, nil] saved position; nil selects the latest state
203
+ # @return [Snapshot] read-only root
204
+ # @raise [ForeignRevisionError] if the revision no longer identifies this file
120
205
  def snapshot(revision: nil)
121
206
  core.with_operation do
122
207
  if revision
@@ -128,15 +213,25 @@ module XitDB
128
213
  end
129
214
  end
130
215
 
216
+ # Access committed roots in oldest-first order.
217
+ # @return [History] live access to the database's history
131
218
  def history
132
219
  core.check_open!
133
220
  History.new(self)
134
221
  end
135
222
 
223
+ # Append a previous root as a new commit without deleting history.
224
+ # @param value [Snapshot, Revision] state from this file generation
225
+ # @return [Snapshot] new commit containing the selected values
226
+ # @raise [ForeignRevisionError] if the state belongs to another file generation
227
+ # @raise [ReadOnlyError] if writes are forbidden
136
228
  def revert(value)
137
229
  core.with_operation { perform_revert(value) }
138
230
  end
139
231
 
232
+ # Validate the selected root again under the writer lock before appending it.
233
+ # @param value [Snapshot, Revision]
234
+ # @return [Snapshot] newly published state
140
235
  def perform_revert(value)
141
236
  target = if value.is_a?(Snapshot)
142
237
  unless value.context.database.core.header.file_id == core.header.file_id
@@ -165,12 +260,22 @@ module XitDB
165
260
  end
166
261
  private :perform_revert
167
262
 
263
+ # Close storage and invalidate every view that uses this handle.
264
+ # @return [void]
168
265
  def close
169
266
  core.close
170
267
  end
171
268
 
172
- def compact(to:)
173
- compacted = core.compact(to: to)
269
+ # Copy reachable storage to a separate file and return its open handle.
270
+ #
271
+ # Shared structures remain shared. Compaction preserves the stored profile.
272
+ # The caller closes the returned database.
273
+ # @param to [String] separate empty destination file
274
+ # @param format_version [Integer] binary format version of the destination
275
+ # @return [Database] compacted database
276
+ # @see #convert
277
+ def compact(to:, format_version: Core::Header::VERSION)
278
+ compacted = core.compact(to: to, format_version: format_version)
174
279
  begin
175
280
  selected_profile = profile
176
281
  copied_profile = if defined?(Profiles::Ruby) && selected_profile.is_a?(Profiles::Ruby)
@@ -185,10 +290,26 @@ module XitDB
185
290
  end
186
291
  end
187
292
 
293
+ # Report whether this handle has closed.
294
+ # @return [Boolean]
188
295
  def closed?
189
296
  core.closed?
190
297
  end
191
298
 
299
+ # Copy logical values into a separate database with the selected profile.
300
+ #
301
+ # Conversion decodes and encodes values, so shared histories can duplicate data.
302
+ # Use a transform when a value or key needs an explicit representation change.
303
+ # The caller closes the returned database.
304
+ #
305
+ # @param to [String] separate empty destination file
306
+ # @param profile [Symbol, Profiles::Portable, Profiles::Ruby] :portable, :ruby, or a configured profile
307
+ # @param history [Symbol] :all copies every root; :latest copies only the last root
308
+ # @param transform [#call, nil] callback receiving value:, path:, and role: (:key or :value)
309
+ # @return [Database] converted database
310
+ # @raise [UnsupportedValueError] if the destination cannot encode a value
311
+ # @raise [KeyCollisionError] if different source keys become the same destination key
312
+ # @see #compact
192
313
  def convert(to:, profile:, history: :all, transform: nil)
193
314
  raise ArgumentError, "history must be :all or :latest" unless %i[all latest].include?(history)
194
315
  raise TypeError, "transform must respond to call" unless transform.nil? || transform.respond_to?(:call)
@@ -223,6 +344,11 @@ module XitDB
223
344
  end
224
345
 
225
346
  # Conventional history is shared by profiles; logical roots use the profile seam.
347
+ # Read the physical array whose entries are committed logical root maps.
348
+ # @api private
349
+ # @param cursor [Core::Cursor]
350
+ # @return [Core::ArrayList]
351
+ # @raise [ProfileMismatchError] if the physical root is not a history array
226
352
  def history_array(cursor)
227
353
  unless cursor.slot.empty? || cursor.slot.tag == :array_list
228
354
  raise ProfileMismatchError, "public databases require a top-level history array"
@@ -231,6 +357,12 @@ module XitDB
231
357
  Core::ArrayList.new(cursor)
232
358
  end
233
359
 
360
+ # Build a read-only map from one entry in a captured history.
361
+ # @api private
362
+ # @param cursor [Core::Cursor]
363
+ # @param index [Integer] history position
364
+ # @param revision [Revision, nil] existing identity proof
365
+ # @return [Snapshot]
234
366
  def snapshot_from_history(cursor, index, revision: nil)
235
367
  core.with_operation do
236
368
  slot = history_array(cursor).get(index)
@@ -238,7 +370,7 @@ module XitDB
238
370
  raise ProfileMismatchError, "history entry must contain a root map" if slot.empty?
239
371
 
240
372
  context = Context.new(database: self, root: slot, bound: cursor.bound)
241
- validate_root(slot, context)
373
+ validate_root!(slot, context)
242
374
  revision ||= revision_for(cursor, index)
243
375
  Snapshot.new(context: context, revision: revision)
244
376
  end
@@ -246,6 +378,9 @@ module XitDB
246
378
 
247
379
  private
248
380
 
381
+ # Create an independent profile configuration for the destination.
382
+ # @param selected [Symbol, Profiles::Portable, Profiles::Ruby]
383
+ # @return [Profiles::Portable, Profiles::Ruby]
249
384
  def conversion_profile(selected)
250
385
  source_profile = profile
251
386
  case selected
@@ -264,11 +399,20 @@ module XitDB
264
399
  end
265
400
  end
266
401
 
402
+ # Copy selected roots in one destination transaction after checking target identity.
403
+ # @param target [Database]
404
+ # @param store [Core::FileStore]
405
+ # @param captured [Core::Cursor] source commit boundary
406
+ # @param histories [Core::ArrayList]
407
+ # @param history [Symbol] :all or :latest
408
+ # @param transform [#call, nil]
409
+ # @return [Core::Cursor] committed destination cursor
267
410
  def copy_history(target, store, captured, histories, history, transform)
268
411
  target_core = target.core
269
412
  target_core.transaction do |cursor|
270
413
  current_header = Core::Header.parse(store.read_at(0, Core::Header::SIZE))
271
- unchanged = current_header.file_id == target_core.header.file_id && cursor.bound == Core::Database::MINIMUM_SIZE
414
+ minimum_size = current_header.data_offset + Core::Database::TRAILER_SIZE
415
+ unchanged = current_header.file_id == target_core.header.file_id && cursor.bound == minimum_size
272
416
  raise ArgumentError, "conversion target changed before copying" unless unchanged && cursor.slot.empty?
273
417
 
274
418
  if histories.size.zero? # rubocop:disable Style/ZeroLengthPredicate -- Core arrays expose size, not empty?.
@@ -282,7 +426,7 @@ module XitDB
282
426
  source = snapshot_from_history(captured, index).context
283
427
  destination = Context.new(database: target, root: Core::Slot.new,
284
428
  bound: cursor.bound, transaction: cursor.transaction)
285
- transaction = destination.writable_transaction
429
+ transaction = destination.writable_transaction!
286
430
  transaction.with_logical_mutation do
287
431
  output.append(Conversion.new(source, destination, transform: transform).copy(source.root))
288
432
  transaction.freeze
@@ -291,13 +435,20 @@ module XitDB
291
435
  end
292
436
  end
293
437
 
294
- def validate_root(slot, context)
438
+ # Require a logical root map after the selected profile interprets its storage.
439
+ # @param slot [Core::Slot]
440
+ # @param context [Context]
441
+ # @return [void]
442
+ def validate_root!(slot, context)
295
443
  adapter = profile.container(slot, context: context, path: []) unless slot.empty?
296
444
  return if adapter && %i[map sorted_map].include?(adapter.kind)
297
445
 
298
446
  raise ProfileMismatchError, "history entry must contain a root map"
299
447
  end
300
448
 
449
+ # Select the latest history entry, or expose an empty uncommitted root.
450
+ # @param cursor [Core::Cursor]
451
+ # @return [Snapshot]
301
452
  def snapshot_from_cursor(cursor)
302
453
  count = history_array(cursor).size
303
454
  return snapshot_from_history(cursor, count - 1) unless count.zero?
@@ -305,6 +456,10 @@ module XitDB
305
456
  Snapshot.new(context: Context.new(database: self, root: Core::Slot.new, bound: cursor.bound), revision: nil)
306
457
  end
307
458
 
459
+ # Bind a history index to the file identifier and commit trailer checksum.
460
+ # @param cursor [Core::Cursor]
461
+ # @param index [Integer]
462
+ # @return [Revision]
308
463
  def revision_for(cursor, index)
309
464
  position = cursor.bound - Core::Database::TRAILER_SIZE
310
465
  checksum = core.read_at(position + 17, 8, bound: cursor.bound).unpack1("Q>")
@@ -314,14 +469,38 @@ module XitDB
314
469
  end
315
470
  end
316
471
 
317
- def self.open(path, readonly: false, hash: nil, lock_timeout: 5.0, &block)
472
+ # Open or create a portable database.
473
+ #
474
+ # Portable map keys are Strings. Use {Ruby.open} for native Ruby values.
475
+ # @param path [String] database filename
476
+ # @param readonly [Boolean] require an existing file and forbid writes
477
+ # @param hash [Symbol, Core::Hasher, nil] algorithm or configuration; nil detects existing files
478
+ # @param lock_timeout [Float] seconds allowed to acquire the writer lock
479
+ # @param format_version [Integer] binary format version used when creating a file
480
+ # @yield [database] use a handle that closes when the block ends
481
+ # @yieldparam database [Database]
482
+ # @return [Database, Object] open handle or block result
483
+ # @see Database.open
484
+ def self.open(path, readonly: false, hash: nil, lock_timeout: 5.0, format_version: Core::Header::VERSION, &block)
318
485
  if block
319
- Database.open(path, readonly: readonly, hash: hash, lock_timeout: lock_timeout, &block)
486
+ Database.open(path, readonly: readonly, hash: hash, lock_timeout: lock_timeout, format_version: format_version,
487
+ &block)
320
488
  else
321
- Database.open(path, readonly: readonly, hash: hash, lock_timeout: lock_timeout)
489
+ Database.open(path, readonly: readonly, hash: hash, lock_timeout: lock_timeout, format_version: format_version)
322
490
  end
323
491
  end
324
492
 
493
+ # Create a portable database without a disk file.
494
+ # @param hash [Symbol, Core::Hasher] hash algorithm
495
+ # @yield [database] use a handle that closes when the block ends
496
+ # @yieldparam database [Database]
497
+ # @return [Database, Object] open handle or block result
498
+ # @example Store and read a value
499
+ # XitDB.memory do |db|
500
+ # db.transaction { |root| root["score"] = 10 }
501
+ # db.snapshot["score"] # => 10
502
+ # end
503
+ # @see Database.memory
325
504
  def self.memory(hash: :sha1, &block)
326
505
  if block
327
506
  Database.memory(hash: hash, &block)
@@ -2,72 +2,72 @@
2
2
 
3
3
  # Persistent collections with immutable snapshots and explicit transactions.
4
4
  module XitDB
5
- # Explicit unsigned storage for an integer.
6
- class UInt
7
- attr_reader :value
8
-
9
- def initialize(value)
10
- @value = Core::Format.integer(value, 0..Core::Format::UINT64_MAX)
11
- freeze
12
- end
13
- end
14
-
15
- # Describes the storage layout of a new empty collection.
16
- class CollectionDeclaration
17
- KINDS = %i[hash_map counted_hash_map hash_set counted_hash_set array_list linked_array_list sorted_map
18
- sorted_set].freeze
19
-
20
- attr_reader :kind, :key_kind
21
-
22
- def initialize(kind, key: nil)
23
- raise ArgumentError, "unknown collection kind" unless KINDS.include?(kind)
24
- if !nil.equal?(key) && (!%i[sorted_map sorted_set].include?(kind) || !%i[string integer float time].include?(key))
25
- raise ArgumentError, "sorted key kind must be :string, :integer, :float, or :time"
26
- end
27
-
28
- @kind = kind
29
- @key_kind = key
30
- freeze
31
- end
32
-
33
- def counted?
34
- %i[counted_hash_map counted_hash_set].include?(kind)
35
- end
36
- end
37
-
5
+ # Request unsigned integer storage explicitly.
6
+ # @param value [Integer] integer from zero through 2**64 - 1
7
+ # @return [UInt]
8
+ # @example Assign an unsigned integer
9
+ # root["counter"] = XitDB.uint(42)
38
10
  def self.uint(value)
39
11
  UInt.new(value)
40
12
  end
41
13
 
14
+ # Wrap bytes with an optional two-byte label describing their meaning.
15
+ #
16
+ # A format tag labels bytes; the storage core does not interpret their contents.
17
+ # @param bytes [String] raw content
18
+ # @param format_tag [String, nil] optional two-byte format identifier
19
+ # @return [Core::ByteValue]
42
20
  def self.bytes(bytes, format_tag: nil)
43
21
  Core::ByteValue.new(bytes, format_tag: format_tag)
44
22
  end
45
23
 
24
+ # Declare an empty hash map with an optional stored entry count.
25
+ # @param counted [Boolean] store counts for direct size lookup
26
+ # @return [CollectionDeclaration]
27
+ # @example Create a nested map
28
+ # root["users"] = XitDB.map(counted: true)
46
29
  def self.map(counted: false)
47
30
  raise ArgumentError, "counted must be true or false" unless counted.equal?(true) || counted.equal?(false)
48
31
 
49
32
  CollectionDeclaration.new(counted ? :counted_hash_map : :hash_map)
50
33
  end
51
34
 
35
+ # Declare an empty set with an optional stored member count.
36
+ # @param counted [Boolean]
37
+ # @return [CollectionDeclaration]
52
38
  def self.set(counted: false)
53
39
  raise ArgumentError, "counted must be true or false" unless counted.equal?(true) || counted.equal?(false)
54
40
 
55
41
  CollectionDeclaration.new(counted ? :counted_hash_set : :hash_set)
56
42
  end
57
43
 
44
+ # Declare an empty array indexed by integer position.
45
+ # @return [CollectionDeclaration]
58
46
  def self.array
59
47
  CollectionDeclaration.new(:array_list)
60
48
  end
61
49
 
50
+ # Declare an empty array backed by a tree with positional insert and delete operations.
51
+ # @return [CollectionDeclaration]
62
52
  def self.linked_array
63
53
  CollectionDeclaration.new(:linked_array_list)
64
54
  end
65
55
 
56
+ # Declare an empty map whose keys are visited in storage order.
57
+ # @param key [Symbol, nil] :string, :integer, :float, or :time; profile rules determine the default
58
+ # @return [CollectionDeclaration]
59
+ # @see Views::Sorted
66
60
  def self.sorted_map(key: nil)
67
61
  CollectionDeclaration.new(:sorted_map, key: key)
68
62
  end
69
63
 
64
+ # Declare an empty set whose members are visited in storage order.
65
+ # @param key [Symbol, nil] :string, :integer, :float, or :time; profile rules determine the default
66
+ # @return [CollectionDeclaration]
70
67
  def self.sorted_set(key: nil)
71
68
  CollectionDeclaration.new(:sorted_set, key: key)
72
69
  end
73
70
  end
71
+
72
+ require_relative "uint"
73
+ require_relative "collection_declaration"
data/lib/xitdb/errors.rb CHANGED
@@ -30,8 +30,12 @@ module XitDB
30
30
 
31
31
  # An invalid value with an owned, immutable diagnostic path.
32
32
  class ValueError < Error
33
+ # @return [Array<Object>] immutable selectors locating the rejected input
33
34
  attr_reader :path
34
35
 
36
+ # Store an error message and an owned immutable copy of its value location.
37
+ # @param message [String, nil]
38
+ # @param path [Array<Object>] selectors leading to the rejected value
35
39
  def initialize(message = nil, path: [])
36
40
  @path = copy_path(path)
37
41
  super(message)
@@ -39,6 +43,8 @@ module XitDB
39
43
 
40
44
  private
41
45
 
46
+ # Copy diagnostic containers and replace unsupported objects with safe class descriptions.
47
+ # @return [Object] immutable diagnostic value
42
48
  def copy_path(value)
43
49
  case value
44
50
  when Array then Array.instance_method(:map).bind_call(value) { |part| copy_path(part) }.freeze
@@ -70,8 +76,17 @@ module XitDB
70
76
 
71
77
  # A failed commit with its observed durability outcome.
72
78
  class CommitError < Error
79
+ # @return [Symbol] :not_committed, :committed, or :unknown; inspect before retrying
73
80
  attr_reader :outcome
74
81
 
82
+ # Describe a commit failure together with its observed publication outcome.
83
+ #
84
+ # :not_committed means the root was not published. :committed means it was
85
+ # published despite the error. :unknown means publication could not be established.
86
+ # A retry can repeat application effects when publication already succeeded.
87
+ # @param message [String, nil]
88
+ # @param outcome [Symbol] :not_committed, :committed, or :unknown
89
+ # @raise [ArgumentError] if the outcome is not recognized
75
90
  def initialize(message = nil, outcome:)
76
91
  unless %i[not_committed committed unknown].include?(outcome)
77
92
  raise ArgumentError, "invalid commit outcome: #{outcome.inspect}"
data/lib/xitdb/history.rb CHANGED
@@ -2,13 +2,22 @@
2
2
 
3
3
  module XitDB
4
4
  # Enumerates the committed snapshots of a database.
5
+ #
6
+ # A changed transaction appends one root. Index zero selects the oldest root.
7
+ # Reads need an open database handle. Iteration captures one history boundary.
5
8
  class History
6
9
  include Enumerable
7
10
 
11
+ # Bind history reads to an open database handle.
12
+ # @api private
13
+ # @param database [Database]
8
14
  def initialize(database)
9
15
  @database = database
10
16
  end
11
17
 
18
+ # Read a committed root by position, with the oldest commit at zero.
19
+ # @param index [Integer] negative positions count from the latest commit
20
+ # @return [Snapshot, nil] nil when outside the captured history
12
21
  def [](index)
13
22
  @database.core.with_operation do
14
23
  cursor = @database.core.root_cursor
@@ -22,14 +31,26 @@ module XitDB
22
31
  end
23
32
  end
24
33
 
34
+ # Read a history position and raise when absent.
35
+ # @param index [Integer]
36
+ # @return [Snapshot]
37
+ # @raise [IndexError] if the position is outside history
25
38
  def fetch(index)
26
39
  self[index] || raise(IndexError, "history index outside history")
27
40
  end
28
41
 
42
+ # Count logical commits in the latest published history.
43
+ # @return [Integer]
29
44
  def size
30
45
  @database.core.with_operation { @database.history_array(@database.core.root_cursor).size }
31
46
  end
32
47
 
48
+ # Visit oldest-to-newest snapshots from one captured history boundary.
49
+ #
50
+ # Commits added after iteration starts do not extend this iteration.
51
+ # @yield [snapshot]
52
+ # @yieldparam snapshot [Snapshot]
53
+ # @return [self, Enumerator]
33
54
  def each
34
55
  return enum_for(:each) unless block_given?
35
56
 
@@ -4,17 +4,31 @@ require_relative "errors"
4
4
 
5
5
  module XitDB
6
6
  # Rejects objects with altered method behavior before encoding them.
7
+ # @api private
7
8
  module InputGuard
9
+ # These exact classes cannot have separate per-object method tables.
10
+ IMMEDIATE_TYPES = [NilClass, FalseClass, TrueClass, Integer, Float, Symbol].freeze
11
+ private_constant :IMMEDIATE_TYPES
12
+
13
+ # Reject objects whose per-object methods can change native encoding behavior.
14
+ #
15
+ # Bound native methods inspect the object without trusting its own overrides.
16
+ # @param value [Object]
17
+ # @param path [Array<Object>] logical location for a value error
18
+ # @return [void]
19
+ # @raise [UnsupportedValueError] if singleton behavior or removed methods are detected
8
20
  def self.check!(value, path: [])
9
21
  unless Object.instance_method(:is_a?).bind_call(value, Object)
10
22
  raise UnsupportedValueError.new("unsupported Ruby object", path: path)
11
23
  end
12
24
 
25
+ klass = Object.instance_method(:class).bind_call(value)
26
+ return if IMMEDIATE_TYPES.any? { |type| type.equal?(klass) }
27
+
13
28
  unless Object.instance_method(:singleton_methods).bind_call(value).empty?
14
29
  raise UnsupportedValueError.new("singleton behavior is unsupported", path: path)
15
30
  end
16
31
 
17
- klass = Object.instance_method(:class).bind_call(value)
18
32
  # @type var methods: ::Array[native_visibility_pair]
19
33
  methods = [%i[public_instance_methods public_methods], %i[protected_instance_methods protected_methods],
20
34
  %i[private_instance_methods private_methods]]