rlucene 0.1.0-alpha.3

A Rust port of Apache Lucene, a full-text search engine library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
use crate::core::index::index_commit::{IndexCommit, cmp_commit, is_same_commit};
use crate::core::index::index_deletion_policy::IndexDeletionPolicy;
#[cfg(test)]
use crate::core::index::index_writer::IndexWriter;
use crate::core::index::index_writer::IndexWriterDir;
use crate::core::index::segment_infos::SegmentInfos;
use crate::core::index::{CODEC_FILE_PATTERN, IndexFileNames};
use crate::core::store::directory::Directory;
use crate::core::util::IOUtils;
use crate::core::util::close::Closeable;
use crate::core::util::error::lucene_error::{
  CaughtResult, CaughtResultExt, LuceneError, LuceneErrorKind, Result,
};
use crate::core::util::file_deleter::{FileDeleter, Messenger, MsgType};
use crate::core::util::info_stream::{InfoStream, InfoStreamMT};
#[cfg(test)]
use crate::test_framework::core::util::failure_context::{
  ExecutionMethod, ExecutionOwner, ExecutionScope,
};
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::fmt::{Display, Formatter};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;

/// This struct keeps track of each [`SegmentInfos`](crate::core::index::segment_infos::SegmentInfos) instance that is still "live", either because it
/// corresponds to a `segments_N` file in the [`Directory`](crate::core::store::directory::Directory) (a "commit", i.e. a committed
/// [`SegmentInfos`](crate::core::index::segment_infos::SegmentInfos)) or because it's an in-memory [`SegmentInfos`](crate::core::index::segment_infos::SegmentInfos) that a writer is actively
/// updating but has not yet committed. This struct uses simple reference counting to map the live
/// [`SegmentInfos`](crate::core::index::segment_infos::SegmentInfos) instances to individual files in the [`Directory`](crate::core::store::directory::Directory).
///
/// The same directory file may be referenced by more than one [`IndexCommit`](crate::core::index::index_commit::IndexCommit), i.e. more than one
/// [`SegmentInfos`](crate::core::index::segment_infos::SegmentInfos). Therefore we count how many commits reference each file. When all the commits
/// referencing a certain file have been deleted, the refcount for that file becomes zero, and the
/// file is deleted.
///
/// A separate deletion policy trait ([`IndexDeletionPolicy`](crate::core::index::index_deletion_policy::IndexDeletionPolicy)) is consulted on creation.
/// (`on_init`) and once per commit (`on_commit`), to decide when a commit should be removed.
///
/// It is the business of the [`IndexDeletionPolicy`](crate::core::index::index_deletion_policy::IndexDeletionPolicy) to choose when to delete commit points. The
/// actual mechanics of file deletion, retrying, etc., derived from the deletion of commit points is
/// the business of the `IndexFileDeleter`.
///
/// The current default deletion policy is [`KeepOnlyLastCommitDeletionPolicy`](crate::core::index::keep_only_last_commit_deletion_policy::KeepOnlyLastCommitDeletionPolicy), which removes all
/// prior commits when a new commit has completed. This matches the behavior before 2.2.
///
/// Note that you must hold the `write.lock` before instantiating This struct. It opens `segments_N`
/// file(s) directly with no retry logic.
pub struct IndexFileDeleter<D>
where
  D: Directory,
{
  /// Holds all commits (segments_N) currently in the index.
  /// This will have just 1 commit if you are using the
  /// default delete policy (KeepOnlyLastCommitDeletionPolicy).
  /// Other policies may leave commit points live for longer
  /// in which case this list would be longer than 1.
  commits: Vec<Arc<CommitPoint<D>>>,

  /// Holds files we had incref'd from the previous non-commit checkpoint.
  last_files: Option<CheckpointFiles>,

  /// Commits that the IndexDeletionPolicy have decided to delete.
  commits_to_delete: Arc<AtomicBool>,

  info_stream: InfoStreamMT,
  directory_orig: Arc<D>,
  directory: Arc<IndexWriterDir<D>>,

  /// Whether the starting commit was deleted.
  pub(crate) starting_commit_deleted: bool,

  file_deleter: FileDeleter<D, MessengerImpl>,
}
impl<D> IndexFileDeleter<D>
where
  D: Directory,
{
  /// Initialize the deleter: find all previous commits in the Directory, incref the files they reference, call the policy to let it delete commits.
  /// This will remove any files not referenced by any of the commits.
  #[allow(clippy::too_many_arguments)]
  pub fn new<P, I>(
    files: I,
    directory_orig: Arc<D>,
    directory: Arc<IndexWriterDir<D>>,
    policy: &P,
    segment_infos: &mut SegmentInfos<D>,
    info_stream: InfoStreamMT,
    initial_index_exists: bool,
    is_reader_init: bool,
  ) -> Result<Self>
  where
    P: IndexDeletionPolicy<Arc<CommitPoint<D>>>,
    I: IntoIterator<Item = String>,
  {
    // init fields
    let files = files.into_iter();
    let commits = Vec::new();
    let mut last_segment_infos: Option<SegmentInfos<D>> = None;

    let current_segments_file_opt = segment_infos.get_segments_file_name();
    if info_stream.is_enabled("IFD") {
      info_stream.message(
                "IFD",
                &format!(
                    "init: current segments file is \"{current_segments_file_opt:?}\"; deletionPolicy={policy}"
                ),
            )?;
    }

    // create file_deleter
    let file_deleter = FileDeleter::new(
      directory.clone(),
      Some(MessengerImpl::new(info_stream.clone(), false)),
    );

    let mut index_file_deleter = Self {
      commits,
      last_files: None,
      commits_to_delete: Arc::new(AtomicBool::new(false)),
      info_stream,
      directory_orig: directory_orig.clone(),
      directory,
      starting_commit_deleted: !initial_index_exists,
      file_deleter,
    };
    let mut current_commit_point = None;
    if current_segments_file_opt.is_some() {
      let current_gen = segment_infos.get_generation();
      for file in files {
        if file.ends_with("write.lock") {
          continue;
        }
        let is_segments = file.starts_with(IndexFileNames::SEGMENTS);
        if CODEC_FILE_PATTERN.is_match(&file)
          || is_segments
          || file.starts_with(IndexFileNames::PENDING_SEGMENTS)
        {
          // Add this file to refCounts with initial count 0:
          if is_segments {
            index_file_deleter.file_deleter.init_ref_count(&file);
            // This is a commit (segments or segments_N), and
            // it's valid (<= the max gen).  Load it, then
            // incref all files it refers to:
            if index_file_deleter.info_stream.is_enabled("IFD") {
              index_file_deleter
                .info_stream
                .message("IFD", &format!("init: load commit \"{file}\""))?;
            }
            let sis = SegmentInfos::read_commit(directory_orig.clone(), &file)?;
            let commit_point = Arc::new(CommitPoint::new(
              index_file_deleter.commits_to_delete.clone(),
              directory_orig.clone(),
              &sis,
              None,
            )?);
            if sis.get_generation() == current_gen {
              current_commit_point = Some(Arc::clone(&commit_point));
            }
            index_file_deleter.commits.push(Arc::clone(&commit_point));
            index_file_deleter.inc_ref_files(commit_point.files.iter())?;

            if last_segment_infos
              .as_ref()
              .is_none_or(|last| sis.get_generation() > last.get_generation())
            {
              last_segment_infos = Some(sis);
            }
          } else {
            index_file_deleter.file_deleter.init_ref_count_owned(file);
          }
        }
      }
    }
    if let Some(file) = current_segments_file_opt
      && current_commit_point.is_none()
      && initial_index_exists
    {
      // We did not in fact see the segments_N file
      // corresponding to the segmentInfos that was passed
      // in.  Yet, it must exist, because our caller holds
      // the write lock.  This can happen when the directory
      // listing was stale (eg when index accessed via NFS
      // client with stale directory listing cache).  So we
      // try now to explicitly open this commit point:
      let sis = SegmentInfos::read_commit(directory_orig.clone(), &file);
      let sis = sis.map_err(|e| {
        if e.is_io_error() {
          let mut error = LuceneError::corrupt_index(format!(
            "unable to read current segments_N file (resource={file})"
          ));
          error.add_suppressed(e);
          error
        } else {
          e
        }
      })?;
      if index_file_deleter.info_stream.is_enabled("IFD") {
        index_file_deleter.info_stream.message(
          "IFD",
          &format!(
            "forced open of current segments file {:?}",
            segment_infos.get_segments_file_name()
          ),
        )?;
      }
      let commit_point = Arc::new(CommitPoint::new(
        index_file_deleter.commits_to_delete.clone(),
        directory_orig.clone(),
        &sis,
        None,
      )?);
      current_commit_point = Some(Arc::clone(&commit_point));
      index_file_deleter.commits.push(Arc::clone(&commit_point));
      index_file_deleter.inc_ref_files(commit_point.files.iter())?;
    }

    if is_reader_init {
      // Incoming SegmentInfos may have NRT changes not yet visible in the latest commit, so we have
      // to protect its files from deletion too:
      index_file_deleter.checkpoint(segment_infos, false, policy)?;
    }

    // keep commits sorted by generation
    index_file_deleter.commits.sort_unstable();

    let pending = directory_orig.get_pending_deletions()?;
    let relevant_files = index_file_deleter.file_deleter.get_all_files();
    if !pending.is_empty() {
      let relevant_files = relevant_files.chain(pending.iter());
      inflate_gens(
        segment_infos,
        relevant_files,
        &index_file_deleter.info_stream,
      )?;
    } else {
      inflate_gens(
        segment_infos,
        relevant_files,
        &index_file_deleter.info_stream,
      )?;
    }

    // inflate gens and delete abandoned files
    let unrefed = index_file_deleter.file_deleter.get_unrefed_files()?;
    for file in &unrefed {
      if file.starts_with(IndexFileNames::SEGMENTS) {
        return Err(LuceneError::illegal_state(
          "file \"{file}\" has refCount=0, which should never happen on init",
        ));
      }
      if index_file_deleter.info_stream.is_enabled("IFD") {
        index_file_deleter.info_stream.message(
          "IFD",
          &format!("init: removing unreferenced file \"{file}\""),
        )?;
      }
    }
    index_file_deleter
      .file_deleter
      .delete_owned_files_if_no_ref(unrefed)?;
    // Finally, give policy a chance to remove things on
    // startup:
    policy.on_init(&index_file_deleter.commits)?;
    // Always protect the incoming segmentInfos since
    // sometime it may not be the most recent commit
    index_file_deleter.checkpoint(segment_infos, false, policy)?;

    index_file_deleter.starting_commit_deleted = match current_commit_point {
      Some(commit) => commit.is_deleted(),
      None => false,
    };

    index_file_deleter.delete_commits()?;
    Ok(index_file_deleter)
  }
  #[cfg(test)]
  fn ensure_open(&self, index_writer: &IndexWriter<D>) -> Result<()> {
    index_writer.do_ensure_open(false)?;

    let tragic_arc = index_writer.get_tragic_exception();
    let error = tragic_arc.get();
    if let Some(e) = error {
      let mut error = LuceneError::already_closed(
        "refusing to delete any files: this IndexWriter encountered an unrecoverable error",
      );
      error.add_suppressed(e.clone());
      return Err(error);
    }

    Ok(())
  }
  #[cfg(test)]
  pub(crate) fn is_closed(&self, index_writer: &IndexWriter<D>) -> Result<bool> {
    match self.ensure_open(index_writer) {
      Ok(_) => Ok(false),
      Err(e) => {
        if matches!(e.kind(), LuceneErrorKind::AlreadyClosed(_)) {
          Ok(true)
        } else {
          Err(e)
        }
      },
    }
  }
  /// Removes pending commit points by decrementing every referenced segment file.
  fn delete_commits(&mut self) -> Result<()> {
    #[cfg(test)]
    let _execution_scope = ExecutionScope::enter(
      ExecutionOwner::IndexFileDeleter,
      ExecutionMethod::DeleteCommits,
    );
    if !self.commits_to_delete.load(SeqCst) {
      return Ok(());
    }
    let mut removed = smallvec::SmallVec::<[_; 2]>::new();
    // commits retains each owner until the compaction below.
    for commit in &self.commits {
      if commit.is_deleted() {
        removed.push(commit);
      }
    }

    // First decref all files that had been referred to by
    // the now-deleted commits:
    let mut first_failure: Option<CaughtResult> = None;
    for commit in removed {
      if self.info_stream.is_enabled("IFD") {
        self.info_stream.message(
          "IFD",
          &format!(
            "deleteCommits: now decRef commit \"{}\"",
            commit.get_segments_file_name()
          ),
        )?;
      }
      let failure = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        #[cfg(test)]
        let _execution_scope =
          ExecutionScope::enter(ExecutionOwner::IndexFileDeleter, ExecutionMethod::DecRef);
        self.file_deleter.dec_ref(commit.files.iter())
      }));
      if !matches!(&failure, Ok(Ok(()))) {
        match first_failure.as_mut() {
          Some(first_failure) => {
            first_failure.add_suppressed(failure, "panic while decrementing file references")
          },
          None => first_failure = Some(failure),
        }
      }
    }
    self.commits_to_delete.store(false, SeqCst);

    // Now compact commits to remove deleted ones (preserving the sort):
    self.commits.retain(|commit| !commit.is_deleted());

    if let Some(first_failure) = first_failure {
      return IOUtils::rethrow_always(first_failure);
    }
    Ok(())
  }

  /// Writer calls this when it has hit an error and had to roll back, to tell us that there may now be unreferenced files in the filesystem.
  /// So we re-list the filesystem and delete such files.
  /// If segmentName is present, we will only delete files corresponding to that segment.
  pub(crate) fn refresh(&self) -> Result<()> {
    // debug_assert!(self.locked());
    let mut to_delete = HashSet::new();

    let files = self.directory.list_all()?;

    for file_name in files {
      let is_lock_file = file_name.ends_with("write.lock");
      let is_codec_match = CODEC_FILE_PATTERN.is_match(&file_name);
      let is_segments = file_name.starts_with(IndexFileNames::SEGMENTS);
      let is_pending_segments = file_name.starts_with(IndexFileNames::PENDING_SEGMENTS);

      // we only try to clear out pending_segments_N during rollback(), because we don't
      // ref-count it
      if !is_lock_file
        && !self.file_deleter.exists(&file_name)
        && (is_codec_match || is_segments || is_pending_segments)
      {
        if self.info_stream.is_enabled("IFD") {
          self.info_stream.message(
            "IFD",
            &format!("refresh: removing newly created unreferenced file \"{file_name}\""),
          )?;
        }
        to_delete.insert(file_name);
      }
    }

    self.file_deleter.delete_owned_files_if_no_ref(to_delete)
  }
  fn assert_commits_are_not_deleted(&self, commits: &[Arc<CommitPoint<D>>]) -> bool {
    for commit in commits {
      debug_assert!(
        !commit.is_deleted(),
        "Commit [{commit}] was deleted already"
      );
    }
    true
  }
  /// Revisits the [`IndexDeletionPolicy`](crate::core::index::index_deletion_policy::IndexDeletionPolicy) by calling its [`IndexDeletionPolicy::on_commit()`] again with the known commits.
  /// This is useful when using a deletion policy that holds onto index commits.
  /// The application may know that some commits are no longer held by the policy and call `IndexWriter::delete_unused_files()`,
  /// which will attempt to delete those unused commits again.
  pub(crate) fn revisit_policy<P>(&mut self, policy: &P) -> Result<()>
  where
    P: IndexDeletionPolicy<Arc<CommitPoint<D>>>,
  {
    {
      if self.info_stream.is_enabled("IFD") {
        self.info_stream.message("IFD", "now revisitPolicy")?;
      }
    }

    if !self.commits.is_empty() {
      debug_assert!(self.assert_commits_are_not_deleted(&self.commits));
      policy.on_commit(&self.commits)?;
      self.delete_commits()?;
    }

    Ok(())
  }
  /// For definition of “check point” see [`IndexWriter`](crate::core::index::index_writer::IndexWriter) comments: “Clarification: Check Points (and commits)”.
  ///
  /// Writer calls this when it has made a “consistent change” to the index, meaning new files are
  /// written to the index and the in-memory [`SegmentInfos`](crate::core::index::segment_infos::SegmentInfos) have been modified to point to those files.
  ///
  /// This may or may not be a commit (`segments_N` may or may not have been written).
  ///
  /// We simply incref the files referenced by the new [`SegmentInfos`](crate::core::index::segment_infos::SegmentInfos) and decref the files we had
  /// previously seen (if any).
  ///
  /// If this is a commit, we also call the policy to give it a chance to remove other commits. If
  /// any commits are removed, we decref their files as well.
  pub fn checkpoint<P>(
    &mut self,
    segment_infos: &SegmentInfos<D>,
    is_commit: bool,
    policy: &P,
  ) -> Result<()>
  where
    P: IndexDeletionPolicy<Arc<CommitPoint<D>>>,
  {
    #[cfg(test)]
    let _execution_scope = ExecutionScope::enter(
      ExecutionOwner::IndexFileDeleter,
      ExecutionMethod::Checkpoint,
    );
    // `IndexFileDeleter` runs while the writer's inner mutex is held.
    let t0 = std::time::Instant::now();

    {
      if self.info_stream.is_enabled("IFD") {
        // TODO:
      }
    }
    if is_commit {
      let files = segment_infos.files(true)?;
      self.inc_ref_files(files.iter())?;
      // Append to our commits list:
      self.commits.push(Arc::new(CommitPoint::new(
        Arc::clone(&self.commits_to_delete),
        Arc::clone(&self.directory_orig),
        segment_infos,
        Some(files),
      )?));

      debug_assert!(self.assert_commits_are_not_deleted(&self.commits));
      policy.on_commit(&self.commits)?;
      // Decref files for commits that were deleted by the policy:
      self.delete_commits()?;
    } else {
      let new_files = if let [info] = segment_infos.iter()
        && info.has_only_base_files()
      {
        CheckpointFiles::Shared(Arc::clone(info.info.files_snapshot()?))
      } else {
        CheckpointFiles::Owned(segment_infos.files(false)?)
      };
      self.inc_ref_files(new_files.as_set().iter())?;
      // DecRef old files from the last checkpoint, if any:
      let old_files = self.last_files.take();
      self.dec_ref(old_files.iter().flat_map(|files| files.as_set().iter()))?;
      drop(old_files);
      self.last_files = Some(new_files);
    }

    {
      if self.info_stream.is_enabled("IFD") {
        let elapsed_ms = t0.elapsed().as_millis();
        self
          .info_stream
          .message("IFD", &format!("{elapsed_ms} ms to checkpoint"))?;
      }
    }

    Ok(())
  }
  pub fn inc_ref_from_segment(
    &mut self,
    segment_infos: &SegmentInfos<D>,
    is_commit: bool,
  ) -> Result<()> {
    let files = segment_infos.files_for_read(is_commit)?;
    self.inc_ref_files(files.iter())
  }

  pub fn inc_ref_files<I>(&mut self, files: I) -> Result<()>
  where
    I: IntoIterator,
    I::Item: AsRef<str>,
  {
    self.file_deleter.inc_ref(files)
  }

  /// Decrefs all provided files, even on error; returns first error hit, if any.
  pub(crate) fn dec_ref<'a, I>(&mut self, files: I) -> Result<()>
  where
    I: IntoIterator<Item = &'a String>,
  {
    #[cfg(test)]
    let _execution_scope =
      ExecutionScope::enter(ExecutionOwner::IndexFileDeleter, ExecutionMethod::DecRef);
    self.file_deleter.dec_ref(files)
  }
  pub(crate) fn dec_ref_from_segment(&mut self, segment_infos: &SegmentInfos<D>) -> Result<()> {
    let files = segment_infos.files_for_read(false)?;
    self.dec_ref(files.iter())
  }
  pub fn exists(&self, file_name: &str) -> bool {
    self.file_deleter.exists(file_name)
  }
  /// Deletes the specified files, but only if they are new (have not yet been incref'd)
  pub(crate) fn delete_new_files<'a, I>(&self, files: I) -> Result<()>
  where
    I: IntoIterator<Item = &'a String>,
  {
    self.file_deleter.delete_files_if_no_ref(files)
  }
}
pub(crate) enum CheckpointFiles {
  Shared(Arc<HashSet<String>>),
  Owned(HashSet<String>),
}

impl CheckpointFiles {
  pub(crate) fn as_set(&self) -> &HashSet<String> {
    match self {
      Self::Shared(files) => files,
      Self::Owned(files) => files,
    }
  }
}

impl<D> Closeable for IndexFileDeleter<D>
where
  D: Directory,
{
  fn close(&mut self) -> Result<()> {
    if let Some(files) = self.last_files.take()
      && !files.as_set().is_empty()
    {
      self.dec_ref(files.as_set().iter())?;
    }
    Ok(())
  }
}
/// Holds details for each commit point. This struct is also passed to the deletion policy.
/// Note: This struct has a natural ordering that is inconsistent with equals.
pub struct CommitPoint<D> {
  pub(crate) files: Vec<String>,
  pub(crate) segments_file_name: String,
  pub(crate) deleted: AtomicBool,
  pub(crate) directory_orig: Arc<D>,
  pub(crate) generation: i64,
  pub(crate) user_data: HashMap<String, String>,
  pub(crate) segment_count: usize,
  pub(crate) commits_to_delete: Arc<AtomicBool>,
}
impl<D> CommitPoint<D>
where
  D: Directory,
{
  pub(crate) fn new(
    commits_to_delete: Arc<AtomicBool>,
    directory_orig: Arc<D>,
    segment_infos: &SegmentInfos<D>,
    referenced_files: Option<HashSet<String>>,
  ) -> Result<Self> {
    // TODO:是不是只要保存segment的ID就行,避免一些拷贝
    let user_data = segment_infos.get_user_data().clone();
    let segments_file_name = segment_infos
      .get_segments_file_name()
      .ok_or_else(|| LuceneError::illegal_state("segment_N file is none"))?;
    let generation = segment_infos.get_generation();
    let files = match referenced_files {
      Some(files) => files,
      None => segment_infos.files(true)?,
    }
    .into_iter()
    .collect();
    let segment_count = segment_infos.size();

    Ok(CommitPoint {
      files,
      segments_file_name,
      deleted: AtomicBool::new(false),
      directory_orig,
      generation,
      user_data,
      segment_count,
      commits_to_delete,
    })
  }
}

impl<D> PartialEq for CommitPoint<D>
where
  D: Directory,
{
  fn eq(&self, other: &Self) -> bool {
    is_same_commit(self, other)
  }
}

impl<D> Eq for CommitPoint<D> where D: Directory {}

impl<D> PartialOrd for CommitPoint<D>
where
  D: Directory,
{
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl<D> Ord for CommitPoint<D>
where
  D: Directory,
{
  fn cmp(&self, other: &Self) -> Ordering {
    cmp_commit(self, other)
  }
}

impl<D> Display for CommitPoint<D> {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    write!(
      f,
      "{}({})",
      std::any::type_name::<Self>(),
      self.segments_file_name
    )
  }
}

impl<D> IndexCommit for CommitPoint<D>
where
  D: Directory,
{
  fn get_segments_file_name(&self) -> &str {
    &self.segments_file_name
  }

  fn get_file_names(&self) -> Result<&[String]> {
    Ok(self.files.as_slice())
  }

  type Directory = Arc<D>;

  fn get_directory(&self) -> Self::Directory {
    self.directory_orig.clone()
  }

  /// Called only be the deletion policy, to remove this commit point from the index.
  fn delete(&self) -> Result<()> {
    if !self.deleted.swap(true, SeqCst) {
      self
        .commits_to_delete
        .store(true, std::sync::atomic::Ordering::SeqCst);
    }
    Ok(())
  }

  fn is_deleted(&self) -> bool {
    self.deleted.load(SeqCst)
  }

  fn get_segment_count(&self) -> usize {
    self.segment_count
  }

  fn get_generation(&self) -> i64 {
    self.generation
  }

  fn get_user_data(&self) -> &HashMap<String, String> {
    &self.user_data
  }
}

pub(crate) struct MessengerImpl {
  info_stream: InfoStreamMT,
  verbose_ref_counts: bool,
}
impl MessengerImpl {
  pub(crate) fn new(info_stream: InfoStreamMT, verbose_ref_counts: bool) -> Self {
    MessengerImpl {
      info_stream,
      verbose_ref_counts,
    }
  }
}
impl Messenger for MessengerImpl {
  fn accept(&self, msg_type: MsgType, msg: &str) -> Result<()> {
    if msg_type == MsgType::Ref && !self.verbose_ref_counts {
      return Ok(());
    }
    if self.info_stream.is_enabled("IFD") {
      self.info_stream.message("IFD", msg)?;
    }
    Ok(())
  }

  fn accept_formatted(&self, msg_type: MsgType, msg: std::fmt::Arguments<'_>) -> Result<()> {
    if msg_type == MsgType::Ref && !self.verbose_ref_counts {
      return Ok(());
    }
    if self.info_stream.is_enabled("IFD") {
      self.info_stream.message("IFD", &msg.to_string())?;
    }
    Ok(())
  }
}

use crate::core::index::index_writer::WRITE_LOCK_NAME;
use crate::core::index::segment_infos::generation_from_segments_file_name;

/// Set all gens beyond what we currently see in the directory, to avoid double-write in cases
/// where the previous [`IndexWriter`](crate::core::index::index_writer::IndexWriter) did not gracefully close/rollback (e.g. OS/machine crashed or
/// lost power).
pub(crate) fn inflate_gens<'a, D, I>(
  infos: &mut SegmentInfos<D>,
  files: I,
  info_stream: &InfoStreamMT,
) -> Result<()>
where
  I: IntoIterator<Item = &'a String>,
{
  let mut max_segment_gen = i64::MIN;
  let mut max_segment_name = i64::MIN;
  // Confusingly, this is the union of liveDocs, field infos, doc values
  // (and maybe others, in the future) gens.  This is somewhat messy,
  // since it means DV updates will suddenly write to the next gen after
  // live docs' gen, for example, but we don't have the APIs to ask the
  // codec which file is which:
  let mut max_per_segment_gen = HashMap::with_capacity(infos.size());

  for file_name in files {
    if file_name == WRITE_LOCK_NAME {
      continue;
    } else if file_name.starts_with(IndexFileNames::SEGMENTS) {
      let v = generation_from_segments_file_name(file_name);
      match v {
        Ok(gen_) => {
          max_segment_gen = max_segment_gen.max(gen_);
        },
        Err(e) => {
          // trash file: we have to handle this since we allow anything starting with 'segments'
          // here
          if !matches!(e.kind(), LuceneErrorKind::NumberFormat(_)) {
            return Err(e);
          }
        },
      }
    } else if file_name.starts_with(IndexFileNames::PENDING_SEGMENTS) {
      let v = generation_from_segments_file_name(&file_name[8..]);
      match v {
        Ok(gen_) => {
          max_segment_gen = max_segment_gen.max(gen_);
        },
        Err(e) => {
          // trash file: we have to handle this since we allow anything starting with
          // 'pending_segments' here
          if !matches!(e.kind(), LuceneErrorKind::NumberFormat(_)) {
            return Err(e);
          }
        },
      }
    } else {
      let segment_name = IndexFileNames::parse_segment_name(file_name);
      debug_assert!(segment_name.starts_with('_'), "wtf? file={file_name}");
      let is_temp_file = if file_name.is_ascii() {
        file_name
          .get(file_name.len().saturating_sub(4)..)
          .is_some_and(|suffix| suffix.eq_ignore_ascii_case(".tmp"))
      } else {
        file_name.to_lowercase().ends_with(".tmp")
      };
      if is_temp_file {
        // A temp file: don't try to look at its gen
        continue;
      }
      max_segment_name = max_segment_name.max(i64::from_str_radix(&segment_name[1..], 36)?);

      let mut cur_gen = *max_per_segment_gen.get(segment_name).unwrap_or(&0i64);

      let v = IndexFileNames::parse_generation(file_name);
      match v {
        Ok(gen_) => {
          cur_gen = cur_gen.max(gen_);
        },
        Err(e) => {
          // trash file: we have to handle this since codec regex is only so good
          if !matches!(e.kind(), LuceneErrorKind::NumberFormat(_)) {
            return Err(e);
          }
        },
      }
      max_per_segment_gen.insert(segment_name, cur_gen);
    }
  }

  // Generation is advanced before write:
  let next_gen = infos.get_generation().max(max_segment_gen);
  infos.set_next_write_generation(next_gen)?;

  let desired = 1 + max_segment_name;
  if infos.counter < desired {
    if info_stream.is_enabled("IFD") {
      info_stream.message(
        "IFD",
        &format!(
          "init: inflate infos.counter to {} vs current={}",
          desired, infos.counter
        ),
      )?;
    }
    infos.counter = desired;
  }
  for info in infos.iter_mut() {
    let gen_long = *max_per_segment_gen
      .get(info.info.name.as_ref())
      .ok_or_else(|| {
        LuceneError::illegal_state(format!(
          "missing maximum generation for segment {}",
          info.info.name
        ))
      })?;

    let next_del = info.get_next_write_del_gen();
    if next_del < gen_long + 1 {
      if info_stream.is_enabled("IFD") {
        info_stream.message(
          "IFD",
          &format!(
            "init: seg={} set nextWriteDelGen={} vs current={}",
            info.info.name,
            gen_long + 1,
            next_del
          ),
        )?;
      }
      info.set_next_write_del_gen(gen_long + 1);
    }

    let next_fi = info.get_next_write_field_infos_gen();
    if next_fi < gen_long + 1 {
      if info_stream.is_enabled("IFD") {
        info_stream.message(
          "IFD",
          &format!(
            "init: seg={} set nextWriteFieldInfosGen={} vs current={}",
            info.info.name,
            gen_long + 1,
            next_fi
          ),
        )?;
      }
      info.set_next_write_field_infos_gen(gen_long + 1);
    }

    let next_dv = info.get_next_write_doc_values_gen();
    if next_dv < gen_long + 1 {
      if info_stream.is_enabled("IFD") {
        info_stream.message(
          "IFD",
          &format!(
            "init: seg={} set nextWriteDocValuesGen={} vs current={}",
            info.info.name,
            gen_long + 1,
            next_dv
          ),
        )?;
      }
      info.set_next_write_doc_values_gen(gen_long + 1);
    }
  }
  Ok(())
}