batch.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /*
  2. * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package badger
  6. import (
  7. "sync"
  8. "sync/atomic"
  9. "github.com/pkg/errors"
  10. "google.golang.org/protobuf/proto"
  11. "github.com/dgraph-io/badger/v4/pb"
  12. "github.com/dgraph-io/badger/v4/y"
  13. "github.com/dgraph-io/ristretto/v2/z"
  14. )
  15. // WriteBatch holds the necessary info to perform batched writes.
  16. type WriteBatch struct {
  17. sync.Mutex
  18. txn *Txn
  19. db *DB
  20. throttle *y.Throttle
  21. err atomic.Value
  22. isManaged bool
  23. commitTs uint64
  24. finished bool
  25. }
  26. // NewWriteBatch creates a new WriteBatch. This provides a way to conveniently do a lot of writes,
  27. // batching them up as tightly as possible in a single transaction and using callbacks to avoid
  28. // waiting for them to commit, thus achieving good performance. This API hides away the logic of
  29. // creating and committing transactions. Due to the nature of SSI guaratees provided by Badger,
  30. // blind writes can never encounter transaction conflicts (ErrConflict).
  31. func (db *DB) NewWriteBatch() *WriteBatch {
  32. if db.opt.managedTxns {
  33. panic("cannot use NewWriteBatch in managed mode. Use NewWriteBatchAt instead")
  34. }
  35. return db.newWriteBatch(false)
  36. }
  37. func (db *DB) newWriteBatch(isManaged bool) *WriteBatch {
  38. return &WriteBatch{
  39. db: db,
  40. isManaged: isManaged,
  41. txn: db.newTransaction(true, isManaged),
  42. throttle: y.NewThrottle(16),
  43. }
  44. }
  45. // SetMaxPendingTxns sets a limit on maximum number of pending transactions while writing batches.
  46. // This function should be called before using WriteBatch. Default value of MaxPendingTxns is
  47. // 16 to minimise memory usage.
  48. func (wb *WriteBatch) SetMaxPendingTxns(max int) {
  49. wb.throttle = y.NewThrottle(max)
  50. }
  51. // Cancel function must be called if there's a chance that Flush might not get
  52. // called. If neither Flush or Cancel is called, the transaction oracle would
  53. // never get a chance to clear out the row commit timestamp map, thus causing an
  54. // unbounded memory consumption. Typically, you can call Cancel as a defer
  55. // statement right after NewWriteBatch is called.
  56. //
  57. // Note that any committed writes would still go through despite calling Cancel.
  58. func (wb *WriteBatch) Cancel() {
  59. wb.Lock()
  60. defer wb.Unlock()
  61. wb.finished = true
  62. if err := wb.throttle.Finish(); err != nil {
  63. wb.db.opt.Errorf("WatchBatch.Cancel error while finishing: %v", err)
  64. }
  65. wb.txn.Discard()
  66. }
  67. func (wb *WriteBatch) callback(err error) {
  68. // sync.WaitGroup is thread-safe, so it doesn't need to be run inside wb.Lock.
  69. defer wb.throttle.Done(err)
  70. if err == nil {
  71. return
  72. }
  73. if err := wb.Error(); err != nil {
  74. return
  75. }
  76. wb.err.Store(err)
  77. }
  78. func (wb *WriteBatch) writeKV(kv *pb.KV) error {
  79. e := Entry{Key: kv.Key, Value: kv.Value}
  80. if len(kv.UserMeta) > 0 {
  81. e.UserMeta = kv.UserMeta[0]
  82. }
  83. y.AssertTrue(kv.Version != 0)
  84. e.version = kv.Version
  85. return wb.handleEntry(&e)
  86. }
  87. func (wb *WriteBatch) Write(buf *z.Buffer) error {
  88. wb.Lock()
  89. defer wb.Unlock()
  90. err := buf.SliceIterate(func(s []byte) error {
  91. kv := &pb.KV{}
  92. if err := proto.Unmarshal(s, kv); err != nil {
  93. return err
  94. }
  95. return wb.writeKV(kv)
  96. })
  97. return err
  98. }
  99. func (wb *WriteBatch) WriteList(kvList *pb.KVList) error {
  100. wb.Lock()
  101. defer wb.Unlock()
  102. for _, kv := range kvList.Kv {
  103. if err := wb.writeKV(kv); err != nil {
  104. return err
  105. }
  106. }
  107. return nil
  108. }
  109. // SetEntryAt is the equivalent of Txn.SetEntry but it also allows setting version for the entry.
  110. // SetEntryAt can be used only in managed mode.
  111. func (wb *WriteBatch) SetEntryAt(e *Entry, ts uint64) error {
  112. if !wb.db.opt.managedTxns {
  113. return errors.New("SetEntryAt can only be used in managed mode. Use SetEntry instead")
  114. }
  115. e.version = ts
  116. return wb.SetEntry(e)
  117. }
  118. // Should be called with lock acquired.
  119. func (wb *WriteBatch) handleEntry(e *Entry) error {
  120. if err := wb.txn.SetEntry(e); err != ErrTxnTooBig {
  121. return err
  122. }
  123. // Txn has reached it's zenith. Commit now.
  124. if cerr := wb.commit(); cerr != nil {
  125. return cerr
  126. }
  127. // This time the error must not be ErrTxnTooBig, otherwise, we make the
  128. // error permanent.
  129. if err := wb.txn.SetEntry(e); err != nil {
  130. wb.err.Store(err)
  131. return err
  132. }
  133. return nil
  134. }
  135. // SetEntry is the equivalent of Txn.SetEntry.
  136. func (wb *WriteBatch) SetEntry(e *Entry) error {
  137. wb.Lock()
  138. defer wb.Unlock()
  139. return wb.handleEntry(e)
  140. }
  141. // Set is equivalent of Txn.Set().
  142. func (wb *WriteBatch) Set(k, v []byte) error {
  143. e := &Entry{Key: k, Value: v}
  144. return wb.SetEntry(e)
  145. }
  146. // DeleteAt is equivalent of Txn.Delete but accepts a delete timestamp.
  147. func (wb *WriteBatch) DeleteAt(k []byte, ts uint64) error {
  148. e := Entry{Key: k, meta: bitDelete, version: ts}
  149. return wb.SetEntry(&e)
  150. }
  151. // Delete is equivalent of Txn.Delete.
  152. func (wb *WriteBatch) Delete(k []byte) error {
  153. wb.Lock()
  154. defer wb.Unlock()
  155. if err := wb.txn.Delete(k); err != ErrTxnTooBig {
  156. return err
  157. }
  158. if err := wb.commit(); err != nil {
  159. return err
  160. }
  161. if err := wb.txn.Delete(k); err != nil {
  162. wb.err.Store(err)
  163. return err
  164. }
  165. return nil
  166. }
  167. // Caller to commit must hold a write lock.
  168. func (wb *WriteBatch) commit() error {
  169. if err := wb.Error(); err != nil {
  170. return err
  171. }
  172. if wb.finished {
  173. return y.ErrCommitAfterFinish
  174. }
  175. if err := wb.throttle.Do(); err != nil {
  176. wb.err.Store(err)
  177. return err
  178. }
  179. wb.txn.CommitWith(wb.callback)
  180. wb.txn = wb.db.newTransaction(true, wb.isManaged)
  181. wb.txn.commitTs = wb.commitTs
  182. return wb.Error()
  183. }
  184. // Flush must be called at the end to ensure that any pending writes get committed to Badger. Flush
  185. // returns any error stored by WriteBatch.
  186. func (wb *WriteBatch) Flush() error {
  187. wb.Lock()
  188. err := wb.commit()
  189. if err != nil {
  190. wb.Unlock()
  191. return err
  192. }
  193. wb.finished = true
  194. wb.txn.Discard()
  195. wb.Unlock()
  196. if err := wb.throttle.Finish(); err != nil {
  197. if wb.Error() != nil {
  198. return errors.Errorf("wb.err: %s err: %s", wb.Error(), err)
  199. }
  200. return err
  201. }
  202. return wb.Error()
  203. }
  204. // Error returns any errors encountered so far. No commits would be run once an error is detected.
  205. func (wb *WriteBatch) Error() error {
  206. // If the interface conversion fails, the err will be nil.
  207. err, _ := wb.err.Load().(error)
  208. return err
  209. }