You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
1.8 KiB

  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package code
  5. import (
  6. "fmt"
  7. "sync"
  8. )
  9. var (
  10. indexer = newWrappedIndexer()
  11. )
  12. // ErrWrappedIndexerClosed is the error returned if the indexer was closed before it was ready
  13. var ErrWrappedIndexerClosed = fmt.Errorf("Indexer closed before ready")
  14. type wrappedIndexer struct {
  15. internal Indexer
  16. lock sync.RWMutex
  17. cond *sync.Cond
  18. closed bool
  19. }
  20. func newWrappedIndexer() *wrappedIndexer {
  21. w := &wrappedIndexer{}
  22. w.cond = sync.NewCond(w.lock.RLocker())
  23. return w
  24. }
  25. func (w *wrappedIndexer) set(indexer Indexer) {
  26. w.lock.Lock()
  27. defer w.lock.Unlock()
  28. if w.closed {
  29. // Too late!
  30. indexer.Close()
  31. }
  32. w.internal = indexer
  33. w.cond.Broadcast()
  34. }
  35. func (w *wrappedIndexer) get() (Indexer, error) {
  36. w.lock.RLock()
  37. defer w.lock.RUnlock()
  38. if w.internal == nil {
  39. if w.closed {
  40. return nil, ErrWrappedIndexerClosed
  41. }
  42. w.cond.Wait()
  43. if w.closed {
  44. return nil, ErrWrappedIndexerClosed
  45. }
  46. }
  47. return w.internal, nil
  48. }
  49. func (w *wrappedIndexer) Index(repoID int64) error {
  50. indexer, err := w.get()
  51. if err != nil {
  52. return err
  53. }
  54. return indexer.Index(repoID)
  55. }
  56. func (w *wrappedIndexer) Delete(repoID int64) error {
  57. indexer, err := w.get()
  58. if err != nil {
  59. return err
  60. }
  61. return indexer.Delete(repoID)
  62. }
  63. func (w *wrappedIndexer) Search(repoIDs []int64, language, keyword string, page, pageSize int) (int64, []*SearchResult, []*SearchResultLanguages, error) {
  64. indexer, err := w.get()
  65. if err != nil {
  66. return 0, nil, nil, err
  67. }
  68. return indexer.Search(repoIDs, language, keyword, page, pageSize)
  69. }
  70. func (w *wrappedIndexer) Close() {
  71. w.lock.Lock()
  72. defer w.lock.Unlock()
  73. if w.closed {
  74. return
  75. }
  76. w.closed = true
  77. w.cond.Broadcast()
  78. if w.internal != nil {
  79. w.internal.Close()
  80. }
  81. }