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
data/info/help.md CHANGED
@@ -65,11 +65,20 @@ ZIP jobs show progress in Jobs mode (`J`). `x`: Cancel the selected job there; a
65
65
  | Key | Action |
66
66
  |-----|--------|
67
67
  | `f` | Start filter mode |
68
- | `s` | Search file names with fzf |
69
- | `/` | Search file names with fzf (same as `s`) |
70
- | `F` | Search file contents with rga (ripgrep-all) |
68
+ | `s` | Fuzzy search file names |
69
+ | `/` | Fuzzy search file names (same as `s`) |
70
+ | `F` | Search file contents with rga (ripgrep-all) and pick a result |
71
71
  | `G` | Global search: file names or contents across all bookmarks |
72
72
 
73
+ **Fuzzy Search (`s`, `/`, `F`):**
74
+ - `s` / `/` list every file under the current directory (including hidden files) in a built-in search screen; no external tools are needed
75
+ - Type to narrow results with fuzzy (in-order, non-contiguous) matching; matched characters are highlighted
76
+ - `Up/Down` or `Ctrl+J/K or Ctrl+N/P`: Select | `Enter`: Open | `Ctrl+U`: Clear | `ESC`: Back
77
+ - `F` asks for text, runs rga in the background and shows its `file:line:text` results in the same screen. `Enter` opens the file at that line
78
+ - Screens at least 80 columns wide show a preview of the selected file on the right (`F` centers and highlights the matching line). Set `preview_enabled: false` in `UI_OPTIONS` to hide it
79
+ - Reopening `s` in the same directory within 5 minutes shows the cached list (`Cached ... ago` in the title). `Ctrl+R`: Rescan. A file deleted since then shows `File no longer exists`
80
+ - The cache keeps 4 directories, 200,000 files and 5 minutes by default. Change it with `FUZZY_SEARCH_CACHE = { max_entries: 500_000, max_roots: 8, ttl: 900 }` in `~/.config/rufio/config.rb` (up to 1,000,000 files, 16 directories and 86,400 seconds; `0` disables)
81
+
73
82
  **Filter Mode:**
74
83
  - Type characters to filter files in real-time
75
84
  - Press `Enter` to apply filter and exit filter mode
@@ -145,7 +154,7 @@ Press `B` then select script path management to:
145
154
 
146
155
  Search file names or text inside every bookmarked directory.
147
156
 
148
- - `Tab`: Switch between file names and content (literal, case insensitive)
157
+ - `Tab`: Switch between fuzzy file names (same matching as `s`, best matches first) and literal content (case insensitive)
149
158
  - Content search also reads `.pdf` (page), `.xlsx` (sheet/cell) and `.pptx` (slide)
150
159
  - `Up/Down` or `Ctrl+J/K or Ctrl+N/P`: Select a result | `Enter`: Go to the file in Files mode
151
160
  - `Ctrl+U`: Clear the query | `ESC`: Return to the previous mode
data/info/keybindings.md CHANGED
@@ -46,11 +46,13 @@ ZIP extraction and compression run as background jobs. Check progress in Jobs mo
46
46
  | Key | Action |
47
47
  |-----|--------|
48
48
  | `f` | Enter filter mode (type to filter) |
49
- | `s` | Search file names with fzf |
50
- | `/` | Search file names with fzf (same as `s`) |
51
- | `F` | Search file contents with rga |
49
+ | `s` | Fuzzy search file names |
50
+ | `/` | Fuzzy search file names (same as `s`) |
51
+ | `F` | Search file contents with rga and pick a result |
52
52
  | `G` | Global search: file names or contents across all bookmarks |
53
53
 
54
+ In the built-in search screen (`s`, `/`, `F`), type to fuzzy-filter, use **Up/Down** or **Ctrl+J/K** to select, **Enter** to open and **ESC** to go back. **Ctrl+R** rescans a cached file list; wide screens show a preview of the selected file.
55
+
54
56
  ## Bookmarks & Navigation
55
57
 
56
58
  | Key | Action |
data/info/welcome.md CHANGED
@@ -9,7 +9,7 @@ A TUI file manager that executes and coordinates tools and scripts from files.
9
9
  - **Tool Runtime** - Execute scripts and rake tasks from command mode
10
10
  - **Vim-like Keybindings** - Navigate with `j/k/h/l` keys
11
11
  - **Real-time Filtering** - Press `f` to filter files instantly
12
- - **Advanced Search** - Use `fzf` for file names and `rga` for content search
12
+ - **Fuzzy Search** - Press `s` to fuzzy-search file names in a built-in screen, `F` to pick from `rga` content results
13
13
  - **Global Search** - Press `G` to search names or contents (including PDF/Excel/PowerPoint) across all bookmarks
14
14
  - **ZIP Support** - Preview `.zip` contents, extract or compress selected items with `z`
15
15
  - **Bookmark Support** - Quick access to favorite directories
@@ -25,7 +25,7 @@ Text previews read at most the first 64 KiB. PDF bodies are not previewed, keepi
25
25
  | `j/k` | Move down/up |
26
26
  | `h/l` | Go to parent / Enter directory |
27
27
  | `f` | Filter files |
28
- | `s` | Search with fzf |
28
+ | `s` | Fuzzy search file names |
29
29
  | `b` | Add bookmark |
30
30
  | `B` | Bookmark menu |
31
31
  | `Tab` | Next bookmark |
data/lib/rufio/config.rb CHANGED
@@ -40,7 +40,6 @@ module Rufio
40
40
  # Keybind messages
41
41
  'keybind.invalid_key' => 'invalid key',
42
42
  'keybind.search_text' => 'Search text: ',
43
- 'keybind.no_matches' => 'No matches found.',
44
43
  'keybind.press_any_key' => 'Press any key to continue...',
45
44
  'keybind.input_filename' => 'Enter filename: ',
46
45
  'keybind.input_dirname' => 'Enter directory name: ',
@@ -63,7 +62,6 @@ module Rufio
63
62
  'health.title' => 'rufio Health Check',
64
63
  'health.ruby_version' => 'Ruby version',
65
64
  'health.required_gems' => 'Required gems',
66
- 'health.fzf' => 'fzf (file search)',
67
65
  'health.rga' => 'rga (content search)',
68
66
  'health.zoxide' => 'zoxide (directory history)',
69
67
  'health.bat' => 'bat (syntax highlight)',
@@ -14,6 +14,11 @@ module Rufio
14
14
  # 後方互換性のためのパス(非推奨)
15
15
  YAML_CONFIG_PATH = Config::YAML_CONFIG_PATH
16
16
  LOCAL_YAML_PATH = Config::LOCAL_YAML_PATH
17
+ # 1.6.0 で改名したアクション(旧名 => 新名)。ユーザー設定の旧名も受け付ける
18
+ LEGACY_KEYBIND_ACTIONS = { fzf_search: :file_search, fzf_search_alt: :file_search_alt }.freeze
19
+ # s / / の一覧キャッシュ(FuzzyCandidateCache)。FUZZY_SEARCH_CACHE で MAX_FUZZY_SEARCH_CACHE まで変更できる
20
+ DEFAULT_FUZZY_SEARCH_CACHE = { max_entries: 200_000, max_roots: 4, ttl: 300 }.freeze
21
+ MAX_FUZZY_SEARCH_CACHE = { max_entries: 1_000_000, max_roots: 16, ttl: 86_400 }.freeze
17
22
 
18
23
  class << self
19
24
  def load_config
@@ -63,8 +68,8 @@ module Rufio
63
68
  # 選択・検索
64
69
  select: ' ',
65
70
  filter: 'f',
66
- fzf_search: 's',
67
- fzf_search_alt: '/',
71
+ file_search: 's',
72
+ file_search_alt: '/',
68
73
  rga_search: 'F',
69
74
  # ブックマーク
70
75
  add_bookmark: 'b',
@@ -101,7 +106,21 @@ module Rufio
101
106
  raw_user_keybinds = load_config[:keybinds] || {}
102
107
  # 新フォーマット(単一文字列値)のみ受け入れ、古いフォーマット(配列値)は無視
103
108
  user_keybinds = raw_user_keybinds.select { |_, v| v.is_a?(String) }
104
- default_keybinds.merge(user_keybinds)
109
+ # 旧アクション名は新しい名前の別名として扱う(新しい名前の指定を優先)
110
+ legacy = user_keybinds.select { |action, _| LEGACY_KEYBIND_ACTIONS.key?(action) }
111
+ current = user_keybinds.reject { |action, _| LEGACY_KEYBIND_ACTIONS.key?(action) }
112
+ renamed = legacy.each_with_object({}) { |(action, key), map| map[LEGACY_KEYBIND_ACTIONS[action]] = key }
113
+ default_keybinds.merge(renamed).merge(current)
114
+ end
115
+
116
+ # 0 以上の整数だけを受け付け、上限を超える値は上限に丸める。不正な値は既定値のまま
117
+ def fuzzy_search_cache
118
+ values = load_config[:fuzzy_search_cache]
119
+ values = {} unless values.is_a?(Hash)
120
+ DEFAULT_FUZZY_SEARCH_CACHE.each_with_object({}) do |(key, default), settings|
121
+ value = values[key]
122
+ settings[key] = value.is_a?(Integer) && value >= 0 ? [value, MAX_FUZZY_SEARCH_CACHE[key]].min : default
123
+ end
105
124
  end
106
125
 
107
126
  def global_search_excluded_extensions
@@ -294,7 +313,8 @@ module Rufio
294
313
  applications: safe_const_get(:APPLICATIONS, default_config[:applications]),
295
314
  colors: safe_const_get(:COLORS, default_config[:colors]),
296
315
  keybinds: safe_const_get(:KEYBINDS, {}),
297
- global_search_excluded_extensions: safe_const_get(:GLOBAL_SEARCH_EXCLUDED_EXTENSIONS, [])
316
+ global_search_excluded_extensions: safe_const_get(:GLOBAL_SEARCH_EXCLUDED_EXTENSIONS, []),
317
+ fuzzy_search_cache: safe_const_get(:FUZZY_SEARCH_CACHE, {})
298
318
  }
299
319
 
300
320
  if Object.const_defined?(:LANGUAGE)
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rufio
4
+ # 候補のまとまりを Ruby の行(Hash)にせず、表示名を NUL で終端して連結した 1 本のバイト列で持つ。
5
+ # FuzzySearchSession はこのバイト列をそのままインデックスに登録し、上位の結果になった候補だけ
6
+ # entry(index) で行を作る。ソースは each_batch で行の配列の代わりにこのブロックを渡せる。
7
+ #
8
+ # ブロックは作成後に変わらないので、セッションとキャッシュが同じものを共有できる。
9
+ # rows は (index, text) から行を作る呼び出し可能オブジェクトで、同じ引数には同じ内容を返すこと。
10
+ class FuzzyCandidateBlock
11
+ include Enumerable
12
+
13
+ SEPARATOR = "\0".b.freeze
14
+ MAX_TEXT_BYTES = 65_536
15
+ TEXT_ROW = ->(_index, text) { { text: text } }
16
+
17
+ attr_reader :packed, :size
18
+
19
+ # 表示名を 1 件ずつ詰めてブロックを作る
20
+ class Builder
21
+ attr_reader :size
22
+
23
+ def initialize
24
+ @buffer = +''.b
25
+ @size = 0
26
+ end
27
+
28
+ def empty?
29
+ @size.zero?
30
+ end
31
+
32
+ # text は NUL を含まない正しい UTF-8(バイト列として渡してもよい)。追加した候補の番号を返す
33
+ def add(text)
34
+ raise ArgumentError, 'Candidate text too long' if text.bytesize > MAX_TEXT_BYTES
35
+
36
+ @buffer << text << SEPARATOR
37
+ @size += 1
38
+ @size - 1
39
+ end
40
+
41
+ def build(rows = nil)
42
+ FuzzyCandidateBlock.new(@buffer, @size, rows: rows, checked: true)
43
+ end
44
+ end
45
+
46
+ # 「接頭辞 + 表示名」がそのままパスになるファイル候補の行 { text:, path: } を作る。
47
+ # 表示名を scrub した等でパスを組み立て直せない候補だけ、exceptions に元のパスを持つ。
48
+ class PathRows
49
+ def initialize(prefix, encoding, exceptions = nil)
50
+ @prefix = prefix
51
+ @encoding = encoding
52
+ @exceptions = exceptions
53
+ freeze
54
+ end
55
+
56
+ def call(index, text)
57
+ path = @exceptions && @exceptions[index]
58
+ { text: text, path: path || (@prefix + text.b).force_encoding(@encoding).freeze }
59
+ end
60
+ end
61
+
62
+ # packed: 「表示名 NUL」を size 件連結したもの。checked: true は Builder が詰めた(確認済みの)場合だけ指定する
63
+ def initialize(packed, size, rows: nil, checked: false)
64
+ raise ArgumentError, 'Expected packed candidate text' unless packed.is_a?(String) && size.is_a?(Integer)
65
+
66
+ @packed = packed.frozen? && packed.encoding == Encoding::BINARY ? packed : packed.b.freeze
67
+ @size = size
68
+ @rows = rows || TEXT_ROW
69
+ @offsets = nil
70
+ return if checked
71
+
72
+ unless @packed.count(SEPARATOR) == size && (size.zero? ? @packed.empty? : @packed.end_with?(SEPARATOR)) &&
73
+ @packed.dup.force_encoding(Encoding::UTF_8).valid_encoding?
74
+ raise ArgumentError, 'Invalid packed candidate text'
75
+ end
76
+ end
77
+
78
+ def empty?
79
+ @size.zero?
80
+ end
81
+
82
+ alias length size
83
+
84
+ def text(index)
85
+ raise IndexError, "index #{index} outside of candidate block" unless index.is_a?(Integer) && index >= 0 && index < @size
86
+
87
+ start = offsets[index]
88
+ finish = index + 1 < @size ? offsets[index + 1] : @packed.bytesize
89
+ @packed.byteslice(start, finish - start - 1).force_encoding(Encoding::UTF_8).freeze
90
+ end
91
+
92
+ # 凍結した行(文字列も凍結)を返す。呼ぶたびに作るので、必要な候補だけに使う
93
+ def entry(index)
94
+ row = @rows.call(index, text(index))
95
+ row.each_value { |value| value.freeze if value.is_a?(String) }
96
+ row.freeze
97
+ end
98
+
99
+ def texts
100
+ list = @packed.split(SEPARATOR, -1)
101
+ list.pop
102
+ list.each { |item| item.force_encoding(Encoding::UTF_8).freeze }
103
+ end
104
+
105
+ # 全件の行を作る(テストや、行の配列しか扱えない利用者向け)
106
+ def each
107
+ return enum_for(:each) { @size } unless block_given?
108
+
109
+ @size.times { |index| yield entry(index) }
110
+ self
111
+ end
112
+
113
+ alias to_ary to_a
114
+
115
+ private
116
+
117
+ # 各表示名の開始バイト位置。結果に出す候補が初めて出たときに数え、以後は使い回す(全ブロック分を先に数えない)。
118
+ #複数のスレッドが同時に数えても同じ内容になる
119
+ def offsets
120
+ @offsets ||= begin
121
+ list = Array.new(@size)
122
+ position = 0
123
+ @size.times do |index|
124
+ list[index] = position
125
+ position = @packed.index(SEPARATOR, position) + 1
126
+ end
127
+ list
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,258 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thread'
4
+ require_relative 'fuzzy_file_source'
5
+ require_relative 'fuzzy_candidate_block'
6
+
7
+ module Rufio
8
+ # s / / を同じディレクトリで開き直したとき、走査済みの候補一覧を再利用する。
9
+ # 容量(合計候補数・ディレクトリ数)と有効期限で制限し、最近使ったものから残す。
10
+ # 検索インデックスは各セッションのワーカー専有のまま、候補だけを流し直して作り直す。
11
+ # 候補は FuzzyCandidateBlock(表示名を NUL で終端して連結したバイト列)で保持する(1 件 1 Hash より大幅に小さい)。
12
+ # パスが「ルート/表示名」と同じバイト列なら持たず、行を作るときに組み立て直す。
13
+ # 走査がブロックを出した場合はそれをそのまま保存し、再表示するセッションにも同じブロックを渡す(コピーしない)。
14
+ class FuzzyCandidateCache
15
+ # 既定値。利用者は config.rb の FUZZY_SEARCH_CACHE で変更できる(ConfigLoader.fuzzy_search_cache)
16
+ DEFAULT_MAX_ENTRIES = 200_000
17
+ DEFAULT_MAX_ROOTS = 4
18
+ DEFAULT_TTL = 300
19
+ BLOCK_SIZE = 4096
20
+ SEPARATOR = "\0"
21
+ EMPTY = [].freeze
22
+
23
+ # 保存済みの一覧。候補は FuzzyCandidateBlock のまま持ち、再表示するセッションと共有する
24
+ class Entry
25
+ attr_reader :blocks, :errors, :stored_at, :size
26
+
27
+ def initialize(blocks:, errors:, stored_at:)
28
+ @blocks = blocks.freeze
29
+ @size = blocks.sum(&:size)
30
+ @errors = errors
31
+ @stored_at = stored_at
32
+ freeze
33
+ end
34
+
35
+ # 全件を行に展開する(展開結果は保持しない)。再表示では使わない
36
+ def rows
37
+ @blocks.flat_map(&:to_a).freeze
38
+ end
39
+ end
40
+
41
+ # 候補を詰める。上限を超えたら以降は捨てて nil を返す
42
+ class Packer
43
+ def initialize(root, max_entries)
44
+ @prefix = (root.end_with?(File::SEPARATOR) ? root : root + File::SEPARATOR).b.freeze
45
+ @max_entries = max_entries
46
+ @blocks = []
47
+ @size = 0
48
+ reset
49
+ end
50
+
51
+ def overflow?
52
+ @blocks.nil?
53
+ end
54
+
55
+ # text と path を持つ行を 1 件詰める
56
+ def add(row)
57
+ return false if overflow?
58
+
59
+ text = row.is_a?(Hash) ? row[:text] : nil
60
+ path = row.is_a?(Hash) ? row[:path] : nil
61
+ return overflow! unless text.is_a?(String) && path.is_a?(String) && @size < @max_entries
62
+
63
+ text = text.dup.force_encoding(Encoding::UTF_8)
64
+ text = text.scrub unless text.valid_encoding?
65
+ bytes = path.b
66
+ if text.include?(SEPARATOR) || bytes.include?(SEPARATOR) || text.bytesize > FuzzyCandidateBlock::MAX_TEXT_BYTES
67
+ return overflow!
68
+ end
69
+
70
+ @encoding ||= path.encoding
71
+ index = @builder.add(text)
72
+ unless path.encoding == @encoding && bytes == @prefix + text.b
73
+ (@exceptions ||= {})[index] = path.frozen? ? path : path.dup.freeze
74
+ end
75
+ @size += 1
76
+ flush if @builder.size >= BLOCK_SIZE
77
+ true
78
+ end
79
+
80
+ # 走査が出したブロックは作り直さず、そのまま保存する
81
+ def add_block(block)
82
+ return false if overflow?
83
+ return overflow! if @size + block.size > @max_entries
84
+
85
+ flush
86
+ @blocks << block
87
+ @size += block.size
88
+ true
89
+ end
90
+
91
+ def add_batch(batch)
92
+ return add_block(batch) if batch.is_a?(FuzzyCandidateBlock)
93
+
94
+ batch.each { |row| break unless add(row) }
95
+ !overflow?
96
+ end
97
+
98
+ def entry(errors, stored_at)
99
+ return nil if overflow?
100
+
101
+ flush
102
+ Entry.new(blocks: @blocks, errors: errors.map { |message| message.to_s.dup.freeze }.freeze, stored_at: stored_at)
103
+ end
104
+
105
+ private
106
+
107
+ def overflow!
108
+ @blocks = nil
109
+ @builder = nil
110
+ false
111
+ end
112
+
113
+ def flush
114
+ return if @builder.empty?
115
+
116
+ @blocks << @builder.build(FuzzyCandidateBlock::PathRows.new(@prefix, @encoding, @exceptions&.freeze))
117
+ reset
118
+ end
119
+
120
+ def reset
121
+ @builder = FuzzyCandidateBlock::Builder.new
122
+ @exceptions = nil
123
+ @encoding = nil
124
+ end
125
+ end
126
+
127
+ def initialize(max_entries: DEFAULT_MAX_ENTRIES, max_roots: DEFAULT_MAX_ROOTS, ttl: DEFAULT_TTL, clock: nil)
128
+ @max_entries = max_entries
129
+ @max_roots = max_roots
130
+ @ttl = ttl
131
+ @clock = clock || -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
132
+ @mutex = Mutex.new
133
+ @entries = {} # 挿入順 = 使用順(先頭が最も古い)
134
+ end
135
+
136
+ def fetch(root)
137
+ key = normalize(root)
138
+ @mutex.synchronize do
139
+ entry = @entries.delete(key)
140
+ return nil unless entry
141
+ return nil if expired?(entry)
142
+
143
+ @entries[key] = entry
144
+ end
145
+ end
146
+
147
+ # rows は :text と :path を持つ候補。上限を超える一覧は保存しない
148
+ def store(root, rows, errors: [])
149
+ return false if rows.length > @max_entries
150
+
151
+ key = normalize(root)
152
+ packer = Packer.new(key, @max_entries)
153
+ rows.each { |row| break unless packer.add(row) }
154
+ store_entry(key, packer.entry(errors, @clock.call))
155
+ end
156
+
157
+ # RecordingSource が詰め終えた一覧を保存する
158
+ def store_entry(root, entry)
159
+ return false unless entry
160
+
161
+ key = normalize(root)
162
+ @mutex.synchronize do
163
+ @entries.delete(key)
164
+ @entries[key] = entry
165
+ @entries.shift while @entries.length > @max_roots || total_entries > @max_entries
166
+ end
167
+ true
168
+ end
169
+
170
+ def delete(root)
171
+ key = normalize(root)
172
+ @mutex.synchronize { @entries.delete(key) }
173
+ nil
174
+ end
175
+
176
+ def clear
177
+ @mutex.synchronize { @entries.clear }
178
+ nil
179
+ end
180
+
181
+ def size
182
+ @mutex.synchronize do
183
+ @entries.delete_if { |_, entry| expired?(entry) }
184
+ @entries.length
185
+ end
186
+ end
187
+
188
+ # 保存時刻と有効期限の判定に使う時刻(monotonic)
189
+ def now
190
+ @clock.call
191
+ end
192
+
193
+ def entry_count
194
+ @mutex.synchronize { total_entries }
195
+ end
196
+
197
+ # キャッシュがあれば [再生用ソース, 保存時刻]、なければ [記録付きの走査ソース, nil] を返す。
198
+ # ブロックで走査ソースを差し替えられる(既定は FuzzyFileSource)。
199
+ def source_for(root, native: true)
200
+ entry = fetch(root)
201
+ return [CachedSource.new(entry), entry.stored_at] if entry
202
+
203
+ scan = block_given? ? yield : FuzzyFileSource.new(root, native: native)
204
+ [RecordingSource.new(scan, self, root, @max_entries), nil]
205
+ end
206
+
207
+ private
208
+
209
+ def normalize(root)
210
+ File.expand_path(root.to_s)
211
+ end
212
+
213
+ def expired?(entry)
214
+ @clock.call - entry.stored_at > @ttl
215
+ end
216
+
217
+ def total_entries
218
+ @entries.each_value.sum(&:size)
219
+ end
220
+
221
+ # 保存済みのブロックを順に流し、走査時のエラーも再現する
222
+ class CachedSource
223
+ def initialize(entry)
224
+ @entry = entry
225
+ end
226
+
227
+ def each_batch(cancelled:, on_error:)
228
+ @entry.errors.each { |message| on_error.call(message) }
229
+ @entry.blocks.each do |block|
230
+ break if cancelled.call
231
+
232
+ yield block
233
+ end
234
+ end
235
+ end
236
+
237
+ # 走査結果をそのまま流しつつ記録し、最後まで走査できたときだけ保存する
238
+ class RecordingSource
239
+ def initialize(scan, cache, root, max_entries)
240
+ @scan = scan
241
+ @cache = cache
242
+ @root = root
243
+ @max_entries = max_entries
244
+ end
245
+
246
+ def each_batch(cancelled:, on_error:)
247
+ packer = Packer.new(File.expand_path(@root.to_s), @max_entries)
248
+ errors = []
249
+ recording = ->(message) { errors << message; on_error.call(message) }
250
+ @scan.each_batch(cancelled: cancelled, on_error: recording) do |batch|
251
+ packer.add_batch(batch) unless packer.overflow?
252
+ yield batch
253
+ end
254
+ @cache.store_entry(@root, packer.entry(errors, @cache.now)) unless cancelled.call
255
+ end
256
+ end
257
+ end
258
+ end