gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package bleve
  4. import (
  5. "github.com/blevesearch/bleve/v2"
  6. )
  7. // FlushingBatch is a batch of operations that automatically flushes to the
  8. // underlying index once it reaches a certain size.
  9. type FlushingBatch struct {
  10. maxBatchSize int
  11. batch *bleve.Batch
  12. index bleve.Index
  13. }
  14. // NewFlushingBatch creates a new flushing batch for the specified index. Once
  15. // the number of operations in the batch reaches the specified limit, the batch
  16. // automatically flushes its operations to the index.
  17. func NewFlushingBatch(index bleve.Index, maxBatchSize int) *FlushingBatch {
  18. return &FlushingBatch{
  19. maxBatchSize: maxBatchSize,
  20. batch: index.NewBatch(),
  21. index: index,
  22. }
  23. }
  24. // Index add a new index to batch
  25. func (b *FlushingBatch) Index(id string, data any) error {
  26. if err := b.batch.Index(id, data); err != nil {
  27. return err
  28. }
  29. return b.flushIfFull()
  30. }
  31. // Delete add a delete index to batch
  32. func (b *FlushingBatch) Delete(id string) error {
  33. b.batch.Delete(id)
  34. return b.flushIfFull()
  35. }
  36. func (b *FlushingBatch) flushIfFull() error {
  37. if b.batch.Size() < b.maxBatchSize {
  38. return nil
  39. }
  40. return b.Flush()
  41. }
  42. // Flush submit the batch and create a new one
  43. func (b *FlushingBatch) Flush() error {
  44. err := b.index.Batch(b.batch)
  45. if err != nil {
  46. return err
  47. }
  48. b.batch = b.index.NewBatch()
  49. return nil
  50. }