rufio 1.5.1 → 1.6.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 (49) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -0
  3. data/README.md +8 -3
  4. data/README_ja.md +7 -3
  5. data/Rakefile +5 -0
  6. data/SECURITY.md +2 -2
  7. data/docs/guide.md +41 -8
  8. data/docs/guide_ja.md +41 -8
  9. data/docs/native_fuzzy_search_design_ja.md +684 -0
  10. data/info/help.md +13 -4
  11. data/info/keybindings.md +5 -3
  12. data/info/welcome.md +2 -2
  13. data/lib/rufio/config.rb +0 -2
  14. data/lib/rufio/config_loader.rb +24 -4
  15. data/lib/rufio/fuzzy_candidate_block.rb +131 -0
  16. data/lib/rufio/fuzzy_candidate_cache.rb +258 -0
  17. data/lib/rufio/fuzzy_file_source.rb +180 -0
  18. data/lib/rufio/fuzzy_finder.rb +313 -0
  19. data/lib/rufio/fuzzy_preview_loader.rb +107 -0
  20. data/lib/rufio/fuzzy_search.rb +327 -0
  21. data/lib/rufio/fuzzy_search_session.rb +426 -0
  22. data/lib/rufio/global_search.rb +292 -51
  23. data/lib/rufio/health_checker.rb +0 -22
  24. data/lib/rufio/help_menu.rb +5 -4
  25. data/lib/rufio/keybind_handler.rb +6 -5
  26. data/lib/rufio/native/aarch64-linux-gnu/librufio_zig.so +0 -0
  27. data/lib/rufio/native/aarch64-linux-musl/librufio_zig.so +0 -0
  28. data/lib/rufio/native/aarch64-macos/librufio_zig.dylib +0 -0
  29. data/lib/rufio/native/aarch64-windows/rufio_zig.dll +0 -0
  30. data/lib/rufio/native/x86_64-linux-gnu/librufio_zig.so +0 -0
  31. data/lib/rufio/native/x86_64-linux-musl/librufio_zig.so +0 -0
  32. data/lib/rufio/native/x86_64-macos/librufio_zig.dylib +0 -0
  33. data/lib/rufio/native/x86_64-windows/rufio_zig.dll +0 -0
  34. data/lib/rufio/native_content_search.rb +43 -7
  35. data/lib/rufio/native_scanner_zig.rb +17 -0
  36. data/lib/rufio/rga_result_source.rb +89 -0
  37. data/lib/rufio/screen.rb +5 -1
  38. data/lib/rufio/search_controller.rb +56 -54
  39. data/lib/rufio/terminal_ui.rb +70 -8
  40. data/lib/rufio/ui_renderer.rb +1 -1
  41. data/lib/rufio/version.rb +1 -1
  42. data/lib/rufio.rb +6 -0
  43. data/lib_zig/rufio_native/Makefile +16 -2
  44. data/lib_zig/rufio_native/build.zig +8 -0
  45. data/lib_zig/rufio_native/src/fuzzy.zig +520 -0
  46. data/lib_zig/rufio_native/src/fuzzy_test.zig +212 -0
  47. data/lib_zig/rufio_native/src/main.zig +27 -0
  48. data/lib_zig/rufio_native/src/search.zig +221 -44
  49. metadata +13 -2
@@ -0,0 +1,426 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thread'
4
+ require_relative 'fuzzy_search'
5
+ require_relative 'fuzzy_candidate_block'
6
+ require_relative 'fuzzy_file_source'
7
+
8
+ module Rufio
9
+ # One-shot asynchronous session. The UI calls start/update_query/poll/close;
10
+ # the index worker alone creates, uses and destroys the fuzzy index. Source
11
+ # producers must check the supplied cancellation callback between batches.
12
+ # A batch is an array of rows or a FuzzyCandidateBlock. Blocks are registered as
13
+ # packed text and only the candidates that reach the results become Ruby rows.
14
+ class FuzzySearchSession
15
+ BATCH_SIZE = 256
16
+ MAX_PENDING_BATCHES = 4
17
+ MAX_ERRORS = 100
18
+ REFRESH_INTERVAL = 0.05
19
+ EMPTY = [].freeze
20
+ State = Struct.new(:generation, :query, :results, :total_matches, :candidate_count,
21
+ :scanning, :searching, :errors, keyword_init: true)
22
+
23
+ attr_reader :snapshot
24
+
25
+ # position_limit: 一致位置を求める上位の件数(省略時は limit 件すべて)。それより後の結果の
26
+ # :positions は nil で、表示するときに FuzzySearch.positions で求める。
27
+ def initialize(root: nil, source: nil, native: true, library: nil, limit: 100,
28
+ index_factory: nil, refresh_interval: REFRESH_INTERVAL, position_limit: nil)
29
+ raise ArgumentError, 'Specify either root or source' unless root.nil? != source.nil?
30
+ unless limit.is_a?(Integer) && limit.between?(0, FuzzySearch::MAX_RESULTS)
31
+ raise ArgumentError, 'Invalid result limit'
32
+ end
33
+ unless refresh_interval.is_a?(Numeric) && refresh_interval.real? &&
34
+ refresh_interval.finite? && refresh_interval >= 0
35
+ raise ArgumentError, 'Invalid refresh interval'
36
+ end
37
+
38
+ @source = source || FuzzyFileSource.new(root, native: native)
39
+ raise ArgumentError, 'Source must implement each_batch' unless @source.respond_to?(:each_batch)
40
+
41
+ @index_factory = index_factory || -> { FuzzySearch.new(native: native, library: library) }
42
+ @limit = limit
43
+ unless position_limit.nil? || (position_limit.is_a?(Integer) && position_limit >= 0)
44
+ raise ArgumentError, 'Invalid position limit'
45
+ end
46
+
47
+ @position_limit = position_limit
48
+ @refresh_interval = refresh_interval.to_f
49
+ @mutex = Mutex.new
50
+ @wake = ConditionVariable.new
51
+ @threads = []
52
+ @batches = []
53
+ @revision = 0
54
+ @started = false
55
+ @closed = false
56
+ @failed = false
57
+ @source_done = false
58
+ @error_messages = []
59
+ @pending_snapshot = nil
60
+ @snapshot = State.new(generation: 0, query: ''.freeze, results: EMPTY, total_matches: 0,
61
+ candidate_count: 0, scanning: false, searching: false, errors: EMPTY).freeze
62
+ end
63
+
64
+ def start
65
+ starting = false
66
+ @mutex.synchronize do
67
+ raise IOError, 'Session has already started or closed' if @started || @closed
68
+
69
+ @started = true
70
+ starting = true
71
+ change_state(scanning: true, searching: true)
72
+ @threads << Thread.new { run_index }
73
+ @threads << Thread.new { run_source }
74
+ end
75
+ self
76
+ rescue StandardError
77
+ close if starting
78
+ raise
79
+ end
80
+
81
+ def active?
82
+ @mutex.synchronize { @started && !@closed }
83
+ end
84
+
85
+ def query
86
+ @snapshot.query
87
+ end
88
+
89
+ def generation
90
+ @snapshot.generation
91
+ end
92
+
93
+ def results
94
+ @snapshot.results
95
+ end
96
+
97
+ def total_matches
98
+ @snapshot.total_matches
99
+ end
100
+
101
+ def candidate_count
102
+ @snapshot.candidate_count
103
+ end
104
+
105
+ def scanning?
106
+ @snapshot.scanning
107
+ end
108
+
109
+ def searching?
110
+ @snapshot.searching
111
+ end
112
+
113
+ def errors
114
+ @snapshot.errors
115
+ end
116
+
117
+ def update_query(text)
118
+ @mutex.synchronize do
119
+ raise IOError, 'Session is not accepting input' unless @started && !cancelled_locked?
120
+ unless text.is_a?(String) && text.bytesize <= FuzzySearch::MAX_QUERY_BYTES
121
+ raise ArgumentError, 'Invalid search query'
122
+ end
123
+
124
+ text = text.dup.force_encoding(Encoding::UTF_8)
125
+ raise ArgumentError, 'Invalid UTF-8 or NUL in query' unless text.valid_encoding? && !text.include?("\0")
126
+ return generation if text == query
127
+
128
+ # A result for the previous query must not remain selectable, even if
129
+ # the index is still running it or it already arrived before poll.
130
+ @pending_snapshot = nil
131
+ change_state(generation: generation + 1, query: text.freeze, results: EMPTY,
132
+ total_matches: 0, searching: true)
133
+ @revision += 1
134
+ @wake.broadcast
135
+ generation
136
+ end
137
+ end
138
+
139
+ # At most one immutable snapshot is pending; the UI never drains a queue of
140
+ # obsolete results, and the generation check also runs at publication time.
141
+ def poll
142
+ @mutex.synchronize do
143
+ pending = @pending_snapshot
144
+ @pending_snapshot = nil
145
+ return false if @closed || !pending || pending.generation != generation
146
+
147
+ @snapshot = pending
148
+ true
149
+ end
150
+ end
151
+
152
+ # Nonblocking. No Thread#kill, joins, or native destroy from the caller.
153
+ def close
154
+ @mutex.synchronize do
155
+ return if @closed
156
+
157
+ @closed = true
158
+ @batches.clear
159
+ @pending_snapshot = nil
160
+ change_state(results: EMPTY, total_matches: 0, candidate_count: 0, scanning: false, searching: false)
161
+ @wake.broadcast
162
+ end
163
+ nil
164
+ end
165
+
166
+ # Explicit cleanup barrier, outside the input loop. A running native query
167
+ # completes before its owner frees the handle. False means cleanup is pending.
168
+ def wait(timeout: nil)
169
+ if timeout && (!timeout.is_a?(Numeric) || !timeout.real? || !timeout.finite? || timeout < 0)
170
+ raise ArgumentError, 'Invalid wait timeout'
171
+ end
172
+ deadline = timeout && monotonic + timeout
173
+ threads = @mutex.synchronize { @threads.dup }
174
+ threads.each do |thread|
175
+ remaining = deadline && [deadline - monotonic, 0].max
176
+ return false unless thread.join(remaining)
177
+ end
178
+ true
179
+ end
180
+
181
+ private
182
+
183
+ def monotonic
184
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
185
+ end
186
+
187
+ def change_state(**changes)
188
+ @snapshot = State.new(**@snapshot.to_h.merge(changes)).freeze
189
+ end
190
+
191
+ def cancelled_locked?
192
+ @closed || @failed
193
+ end
194
+
195
+ def cancelled?
196
+ @mutex.synchronize { cancelled_locked? }
197
+ end
198
+
199
+ def immutable_entry(value)
200
+ row = value.is_a?(String) ? { text: value } : value
201
+ raise ArgumentError, 'Candidate must contain text' unless row.is_a?(Hash) && row[:text].is_a?(String)
202
+ return row if reusable?(row)
203
+
204
+ copied = row.each_with_object({}) do |(key, item), copy|
205
+ unless item.is_a?(String) || item.is_a?(Numeric) || item.is_a?(Symbol) ||
206
+ item.nil? || item == true || item == false
207
+ raise ArgumentError, 'Candidate metadata must contain scalar values'
208
+ end
209
+ copy[key] = item.is_a?(String) ? item.dup.freeze : item
210
+ end
211
+ text = row[:text].dup.force_encoding(Encoding::UTF_8)
212
+ unless text.valid_encoding? && !text.include?("\0") && text.bytesize <= FuzzySearch::MAX_CANDIDATE_BYTES
213
+ raise ArgumentError, 'Invalid candidate text'
214
+ end
215
+ copied[:text] = text.freeze
216
+ copied.freeze
217
+ end
218
+
219
+ # A frozen row whose strings are frozen cannot change after it is queued, so the
220
+ # session keeps it as is instead of copying every candidate (sources freeze rows).
221
+ def reusable?(row)
222
+ return false unless row.frozen?
223
+
224
+ text = row[:text]
225
+ return false unless text.frozen? && text.encoding == Encoding::UTF_8 && text.valid_encoding? &&
226
+ !text.include?("\0") && text.bytesize <= FuzzySearch::MAX_CANDIDATE_BYTES
227
+
228
+ row.each_value.all? do |item|
229
+ item.is_a?(String) ? item.frozen? : (item.is_a?(Numeric) || item.is_a?(Symbol) || item.nil? || item == true || item == false)
230
+ end
231
+ end
232
+
233
+ # 登録済みの候補。ブロックは詰めたまま持ち、結果に出す候補だけ行にする
234
+ class Entries
235
+ attr_reader :length
236
+
237
+ def initialize
238
+ @starts = []
239
+ @parts = []
240
+ @length = 0
241
+ end
242
+
243
+ def add(part)
244
+ if part.is_a?(Array) && @parts.last.is_a?(Array)
245
+ @parts.last.concat(part)
246
+ else
247
+ @starts << @length
248
+ @parts << (part.is_a?(Array) ? part.dup : part)
249
+ end
250
+ @length += part.size
251
+ end
252
+
253
+ def fetch(id)
254
+ raise IndexError, "candidate #{id} is not registered" unless id.is_a?(Integer) && id >= 0 && id < @length
255
+
256
+ at = (@starts.bsearch_index { |start| start > id } || @starts.length) - 1
257
+ part = @parts[at]
258
+ part.is_a?(Array) ? part.fetch(id - @starts[at]) : part.entry(id - @starts[at])
259
+ end
260
+
261
+ def clear
262
+ @starts.clear
263
+ @parts.clear
264
+ @length = 0
265
+ end
266
+ end
267
+
268
+ def enqueue(batch)
269
+ rows = batch.is_a?(FuzzyCandidateBlock) ? batch : batch.map { |row| immutable_entry(row) }.freeze
270
+ return true if rows.empty?
271
+
272
+ @mutex.synchronize do
273
+ while @batches.length >= MAX_PENDING_BATCHES && !cancelled_locked?
274
+ @wake.wait(@mutex)
275
+ end
276
+ return false if cancelled_locked?
277
+
278
+ @batches << rows
279
+ @revision += 1
280
+ @wake.broadcast
281
+ true
282
+ end
283
+ end
284
+
285
+ def record_error(message)
286
+ @mutex.synchronize do
287
+ return if cancelled_locked? || @error_messages.length >= MAX_ERRORS
288
+
289
+ @error_messages << message.to_s.dup.force_encoding(Encoding::UTF_8).scrub.freeze
290
+ @revision += 1
291
+ @wake.broadcast
292
+ end
293
+ end
294
+
295
+ def run_source
296
+ @source.each_batch(cancelled: method(:cancelled?), on_error: method(:record_error)) do |batch|
297
+ break if cancelled?
298
+
299
+ if batch.is_a?(FuzzyCandidateBlock)
300
+ break unless enqueue(batch)
301
+
302
+ # ブロックは待ち行列でほとんど待たされないので、検索ワーカーと UI に実行を譲る
303
+ Thread.pass
304
+ else
305
+ batch.each_slice(BATCH_SIZE) do |part|
306
+ break unless enqueue(part)
307
+ end
308
+ end
309
+ end
310
+ rescue StandardError, NoMemoryError => e
311
+ record_error("#{e.class}: #{e.message}")
312
+ ensure
313
+ @mutex.synchronize do
314
+ @source = nil
315
+ @source_done = true
316
+ @revision += 1
317
+ @wake.broadcast
318
+ end
319
+ end
320
+
321
+ def take_work(previous_revision, refresh_at)
322
+ @mutex.synchronize do
323
+ while @revision == previous_revision && !cancelled_locked?
324
+ remaining = refresh_at && refresh_at - monotonic
325
+ break if remaining && remaining <= 0
326
+
327
+ @wake.wait(@mutex, remaining)
328
+ end
329
+ return if cancelled_locked?
330
+
331
+ batches = @batches
332
+ @batches = []
333
+ @wake.broadcast
334
+ [@revision, batches]
335
+ end
336
+ end
337
+
338
+ def publish(current_generation, text, matches, total, count, searching)
339
+ @mutex.synchronize do
340
+ return if cancelled_locked? || generation != current_generation
341
+
342
+ @pending_snapshot = State.new(generation: current_generation, query: text, results: matches,
343
+ total_matches: total, candidate_count: count,
344
+ scanning: !@source_done || !@batches.empty?, searching: searching,
345
+ errors: @error_messages.dup.freeze).freeze
346
+ end
347
+ end
348
+
349
+ def run_index
350
+ entries = Entries.new
351
+ index = nil
352
+ return if cancelled?
353
+
354
+ index = @index_factory.call
355
+ previous_revision = -1
356
+ signature = nil
357
+ matches = EMPTY
358
+ total = 0
359
+ refresh_at = nil
360
+ next_query_at = 0
361
+ while (work = take_work(previous_revision, refresh_at))
362
+ previous_revision, batches = work
363
+ batches.each do |batch|
364
+ break if cancelled?
365
+
366
+ if !batch.is_a?(FuzzyCandidateBlock)
367
+ index.add(batch.map { |row| row[:text] })
368
+ elsif index.respond_to?(:add_packed)
369
+ index.add_packed(batch.packed)
370
+ else
371
+ index.add(batch.texts)
372
+ end
373
+ entries.add(batch)
374
+ end
375
+ break if cancelled?
376
+
377
+ current_generation, text, complete = @mutex.synchronize do
378
+ [generation, query, @source_done && @batches.empty?]
379
+ end
380
+ desired = [current_generation, entries.length]
381
+ dirty = signature != desired
382
+ # Input changes and a complete scan bypass throttling. Candidate-only
383
+ # changes are batched so loading N files doesn't trigger N/B full scans.
384
+ force = signature.nil? || signature[0] != current_generation || complete
385
+ if dirty && (force || monotonic >= next_query_at)
386
+ raw = @position_limit ? index.query(text, limit: @limit, positions: @position_limit) : index.query(text, limit: @limit)
387
+ break if cancelled?
388
+
389
+ total = index.total_matches
390
+ matches = raw.map do |match|
391
+ match.merge(positions: match[:positions].dup.freeze, entry: entries.fetch(match[:id])).freeze
392
+ end.freeze
393
+ signature = desired
394
+ dirty = false
395
+ # 候補がまだない検索は集約の待ち時間を始めない(最初の候補が届いたらすぐ照合する)
396
+ next_query_at = entries.length.zero? ? 0 : monotonic + @refresh_interval
397
+ end
398
+ refresh_at = dirty ? next_query_at : nil
399
+ publish(current_generation, text, matches, total, entries.length, dirty)
400
+ end
401
+ rescue StandardError, NoMemoryError => e
402
+ fail_session(e)
403
+ ensure
404
+ entries.clear
405
+ begin
406
+ index&.close
407
+ rescue StandardError, NoMemoryError => e
408
+ fail_session(e)
409
+ end
410
+ end
411
+
412
+ def fail_session(error)
413
+ @mutex.synchronize do
414
+ return if @closed
415
+
416
+ @failed = true
417
+ @batches.clear
418
+ @error_messages << "#{error.class}: #{error.message}".freeze if @error_messages.length < MAX_ERRORS
419
+ @pending_snapshot = State.new(generation: generation, query: query, results: EMPTY,
420
+ total_matches: 0, candidate_count: 0, scanning: false, searching: false,
421
+ errors: @error_messages.dup.freeze).freeze
422
+ @wake.broadcast
423
+ end
424
+ end
425
+ end
426
+ end