···11+// Copyright 2021 The Gitea Authors. All rights reserved.
22+// SPDX-License-Identifier: MIT
33+44+package bleveutil
55+66+import (
77+ "github.com/blevesearch/bleve/v2"
88+)
99+1010+// FlushingBatch is a batch of operations that automatically flushes to the
1111+// underlying index once it reaches a certain size.
1212+type FlushingBatch struct {
1313+ maxBatchSize int
1414+ batch *bleve.Batch
1515+ index bleve.Index
1616+}
1717+1818+// NewFlushingBatch creates a new flushing batch for the specified index. Once
1919+// the number of operations in the batch reaches the specified limit, the batch
2020+// automatically flushes its operations to the index.
2121+func NewFlushingBatch(index bleve.Index, maxBatchSize int) *FlushingBatch {
2222+ return &FlushingBatch{
2323+ maxBatchSize: maxBatchSize,
2424+ batch: index.NewBatch(),
2525+ index: index,
2626+ }
2727+}
2828+2929+// Index add a new index to batch
3030+func (b *FlushingBatch) Index(id string, data any) error {
3131+ if err := b.batch.Index(id, data); err != nil {
3232+ return err
3333+ }
3434+ return b.flushIfFull()
3535+}
3636+3737+// Delete add a delete index to batch
3838+func (b *FlushingBatch) Delete(id string) error {
3939+ b.batch.Delete(id)
4040+ return b.flushIfFull()
4141+}
4242+4343+func (b *FlushingBatch) flushIfFull() error {
4444+ if b.batch.Size() < b.maxBatchSize {
4545+ return nil
4646+ }
4747+ return b.Flush()
4848+}
4949+5050+// Flush submit the batch and create a new one
5151+func (b *FlushingBatch) Flush() error {
5252+ err := b.index.Batch(b.batch)
5353+ if err != nil {
5454+ return err
5555+ }
5656+ b.batch = b.index.NewBatch()
5757+ return nil
5858+}