backend.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package backend
  7. import (
  8. "errors"
  9. "sync"
  10. )
  11. // CommitHook is a function that is executed before a WriteTransaction is
  12. // committed or before it is flushed to disk, e.g. on calling CheckPoint. The
  13. // transaction can be accessed via a closure.
  14. type CommitHook func(WriteTransaction) error
  15. // The Reader interface specifies the read-only operations available on the
  16. // main database and on read-only transactions (snapshots). Note that when
  17. // called directly on the database handle these operations may take implicit
  18. // transactions and performance may suffer.
  19. type Reader interface {
  20. Get(key []byte) ([]byte, error)
  21. NewPrefixIterator(prefix []byte) (Iterator, error)
  22. NewRangeIterator(first, last []byte) (Iterator, error)
  23. }
  24. // The Writer interface specifies the mutating operations available on the
  25. // main database and on writable transactions. Note that when called
  26. // directly on the database handle these operations may take implicit
  27. // transactions and performance may suffer.
  28. type Writer interface {
  29. Put(key, val []byte) error
  30. Delete(key []byte) error
  31. }
  32. // The ReadTransaction interface specifies the operations on read-only
  33. // transactions. Every ReadTransaction must be released when no longer
  34. // required.
  35. type ReadTransaction interface {
  36. Reader
  37. Release()
  38. }
  39. // The WriteTransaction interface specifies the operations on writable
  40. // transactions. Every WriteTransaction must be either committed or released
  41. // (i.e., discarded) when no longer required. No further operations must be
  42. // performed after release or commit (regardless of whether commit succeeded),
  43. // with one exception -- it's fine to release an already committed or released
  44. // transaction.
  45. //
  46. // A Checkpoint is a potential partial commit of the transaction so far, for
  47. // purposes of saving memory when transactions are in-RAM. Note that
  48. // transactions may be checkpointed *anyway* even if this is not called, due to
  49. // resource constraints, but this gives you a chance to decide when. If, and
  50. // only if, calling Checkpoint will result in a partial commit/flush, the
  51. // CommitHooks passed to Backend.NewWriteTransaction are called before
  52. // committing. If any of those returns an error, committing is aborted and the
  53. // error bubbled.
  54. type WriteTransaction interface {
  55. ReadTransaction
  56. Writer
  57. Checkpoint() error
  58. Commit() error
  59. }
  60. // The Iterator interface specifies the operations available on iterators
  61. // returned by NewPrefixIterator and NewRangeIterator. The iterator pattern
  62. // is to loop while Next returns true, then check Error after the loop. Next
  63. // will return false when iteration is complete (Error() == nil) or when
  64. // there is an error preventing iteration, which is then returned by
  65. // Error(). For example:
  66. //
  67. // it, err := db.NewPrefixIterator(nil)
  68. // if err != nil {
  69. // // problem preventing iteration
  70. // }
  71. // defer it.Release()
  72. // for it.Next() {
  73. // // ...
  74. // }
  75. // if err := it.Error(); err != nil {
  76. // // there was a database problem while iterating
  77. // }
  78. //
  79. // An iterator must be Released when no longer required. The Error method
  80. // can be called either before or after Release with the same results. If an
  81. // iterator was created in a transaction (whether read-only or write) it
  82. // must be released before the transaction is released (or committed).
  83. type Iterator interface {
  84. Next() bool
  85. Key() []byte
  86. Value() []byte
  87. Error() error
  88. Release()
  89. }
  90. // The Backend interface represents the main database handle. It supports
  91. // both read/write operations and opening read-only or writable
  92. // transactions. Depending on the actual implementation, individual
  93. // read/write operations may be implicitly wrapped in transactions, making
  94. // them perform quite badly when used repeatedly. For bulk operations,
  95. // consider always using a transaction of the appropriate type. The
  96. // transaction isolation level is "read committed" - there are no dirty
  97. // reads.
  98. // Location returns the path to the database, as given to Open. The returned string
  99. // is empty for a db in memory.
  100. type Backend interface {
  101. Reader
  102. NewReadTransaction() (ReadTransaction, error)
  103. Close() error
  104. }
  105. var (
  106. errClosed = errors.New("database is closed")
  107. errNotFound = errors.New("key not found")
  108. )
  109. func IsClosed(err error) bool { return errors.Is(err, errClosed) }
  110. func IsNotFound(err error) bool { return errors.Is(err, errNotFound) }
  111. // releaser manages counting on top of a waitgroup
  112. type releaser struct {
  113. wg *closeWaitGroup
  114. once sync.Once
  115. }
  116. func newReleaser(wg *closeWaitGroup) (*releaser, error) {
  117. if err := wg.Add(1); err != nil {
  118. return nil, err
  119. }
  120. return &releaser{wg: wg}, nil
  121. }
  122. func (r *releaser) Release() {
  123. // We use the Once because we may get called multiple times from
  124. // Commit() and deferred Release().
  125. r.once.Do(r.wg.Done)
  126. }
  127. // closeWaitGroup behaves just like a sync.WaitGroup, but does not require
  128. // a single routine to do the Add and Wait calls. If Add is called after
  129. // CloseWait, it will return an error, and both are safe to be used concurrently.
  130. type closeWaitGroup struct {
  131. sync.WaitGroup
  132. closed bool
  133. closeMut sync.RWMutex
  134. }
  135. func (cg *closeWaitGroup) Add(i int) error {
  136. cg.closeMut.RLock()
  137. defer cg.closeMut.RUnlock()
  138. if cg.closed {
  139. return errClosed
  140. }
  141. cg.WaitGroup.Add(i)
  142. return nil
  143. }
  144. func (cg *closeWaitGroup) CloseWait() {
  145. cg.closeMut.Lock()
  146. cg.closed = true
  147. cg.closeMut.Unlock()
  148. cg.WaitGroup.Wait()
  149. }