backend.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. "sync"
  9. )
  10. // The Reader interface specifies the read-only operations available on the
  11. // main database and on read-only transactions (snapshots). Note that when
  12. // called directly on the database handle these operations may take implicit
  13. // transactions and performance may suffer.
  14. type Reader interface {
  15. Get(key []byte) ([]byte, error)
  16. NewPrefixIterator(prefix []byte) (Iterator, error)
  17. NewRangeIterator(first, last []byte) (Iterator, error)
  18. }
  19. // The Writer interface specifies the mutating operations available on the
  20. // main database and on writable transactions. Note that when called
  21. // directly on the database handle these operations may take implicit
  22. // transactions and performance may suffer.
  23. type Writer interface {
  24. Put(key, val []byte) error
  25. Delete(key []byte) error
  26. }
  27. // The ReadTransaction interface specifies the operations on read-only
  28. // transactions. Every ReadTransaction must be released when no longer
  29. // required.
  30. type ReadTransaction interface {
  31. Reader
  32. Release()
  33. }
  34. // The WriteTransaction interface specifies the operations on writable
  35. // transactions. Every WriteTransaction must be either committed or released
  36. // (i.e., discarded) when no longer required. No further operations must be
  37. // performed after release or commit (regardless of whether commit succeeded),
  38. // with one exception -- it's fine to release an already committed or released
  39. // transaction.
  40. //
  41. // A Checkpoint is a potential partial commit of the transaction so far, for
  42. // purposes of saving memory when transactions are in-RAM. Note that
  43. // transactions may be checkpointed *anyway* even if this is not called, due to
  44. // resource constraints, but this gives you a chance to decide when.
  45. //
  46. // Functions can be passed to Checkpoint. These are run if and only if the
  47. // checkpoint will result in a flush, and will run before the flush. The
  48. // transaction can be accessed via a closure. If an error is returned from
  49. // these functions the flush will be aborted and the error bubbled.
  50. type WriteTransaction interface {
  51. ReadTransaction
  52. Writer
  53. Checkpoint(...func() error) error
  54. Commit() error
  55. }
  56. // The Iterator interface specifies the operations available on iterators
  57. // returned by NewPrefixIterator and NewRangeIterator. The iterator pattern
  58. // is to loop while Next returns true, then check Error after the loop. Next
  59. // will return false when iteration is complete (Error() == nil) or when
  60. // there is an error preventing iteration, which is then returned by
  61. // Error(). For example:
  62. //
  63. // it, err := db.NewPrefixIterator(nil)
  64. // if err != nil {
  65. // // problem preventing iteration
  66. // }
  67. // defer it.Release()
  68. // for it.Next() {
  69. // // ...
  70. // }
  71. // if err := it.Error(); err != nil {
  72. // // there was a database problem while iterating
  73. // }
  74. //
  75. // An iterator must be Released when no longer required. The Error method
  76. // can be called either before or after Release with the same results. If an
  77. // iterator was created in a transaction (whether read-only or write) it
  78. // must be released before the transaction is released (or committed).
  79. type Iterator interface {
  80. Next() bool
  81. Key() []byte
  82. Value() []byte
  83. Error() error
  84. Release()
  85. }
  86. // The Backend interface represents the main database handle. It supports
  87. // both read/write operations and opening read-only or writable
  88. // transactions. Depending on the actual implementation, individual
  89. // read/write operations may be implicitly wrapped in transactions, making
  90. // them perform quite badly when used repeatedly. For bulk operations,
  91. // consider always using a transaction of the appropriate type. The
  92. // transaction isolation level is "read committed" - there are no dirty
  93. // reads.
  94. type Backend interface {
  95. Reader
  96. Writer
  97. NewReadTransaction() (ReadTransaction, error)
  98. NewWriteTransaction() (WriteTransaction, error)
  99. Close() error
  100. Compact() error
  101. }
  102. type Tuning int
  103. const (
  104. // N.b. these constants must match those in lib/config.Tuning!
  105. TuningAuto Tuning = iota
  106. TuningSmall
  107. TuningLarge
  108. )
  109. func Open(path string, tuning Tuning) (Backend, error) {
  110. return OpenLevelDB(path, tuning)
  111. }
  112. func OpenMemory() Backend {
  113. return OpenLevelDBMemory()
  114. }
  115. type errClosed struct{}
  116. func (errClosed) Error() string { return "database is closed" }
  117. type errNotFound struct{}
  118. func (errNotFound) Error() string { return "key not found" }
  119. func IsClosed(err error) bool {
  120. if _, ok := err.(errClosed); ok {
  121. return true
  122. }
  123. if _, ok := err.(*errClosed); ok {
  124. return true
  125. }
  126. return false
  127. }
  128. func IsNotFound(err error) bool {
  129. if _, ok := err.(errNotFound); ok {
  130. return true
  131. }
  132. if _, ok := err.(*errNotFound); ok {
  133. return true
  134. }
  135. return false
  136. }
  137. // releaser manages counting on top of a waitgroup
  138. type releaser struct {
  139. wg *closeWaitGroup
  140. once *sync.Once
  141. }
  142. func newReleaser(wg *closeWaitGroup) (*releaser, error) {
  143. if err := wg.Add(1); err != nil {
  144. return nil, err
  145. }
  146. return &releaser{
  147. wg: wg,
  148. once: new(sync.Once),
  149. }, nil
  150. }
  151. func (r releaser) Release() {
  152. // We use the Once because we may get called multiple times from
  153. // Commit() and deferred Release().
  154. r.once.Do(func() {
  155. r.wg.Done()
  156. })
  157. }
  158. // closeWaitGroup behaves just like a sync.WaitGroup, but does not require
  159. // a single routine to do the Add and Wait calls. If Add is called after
  160. // CloseWait, it will return an error, and both are safe to be used concurrently.
  161. type closeWaitGroup struct {
  162. sync.WaitGroup
  163. closed bool
  164. closeMut sync.RWMutex
  165. }
  166. func (cg *closeWaitGroup) Add(i int) error {
  167. cg.closeMut.RLock()
  168. defer cg.closeMut.RUnlock()
  169. if cg.closed {
  170. return errClosed{}
  171. }
  172. cg.WaitGroup.Add(i)
  173. return nil
  174. }
  175. func (cg *closeWaitGroup) CloseWait() {
  176. cg.closeMut.Lock()
  177. cg.closed = true
  178. cg.closeMut.Unlock()
  179. cg.WaitGroup.Wait()
  180. }