backend.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. Writer
  103. NewReadTransaction() (ReadTransaction, error)
  104. NewWriteTransaction(hooks ...CommitHook) (WriteTransaction, error)
  105. Close() error
  106. Compact() error
  107. Location() string
  108. }
  109. type Tuning int
  110. const (
  111. // N.b. these constants must match those in lib/config.Tuning!
  112. TuningAuto Tuning = iota
  113. TuningSmall
  114. TuningLarge
  115. )
  116. func Open(path string, tuning Tuning) (Backend, error) {
  117. return OpenLevelDB(path, tuning)
  118. }
  119. func OpenMemory() Backend {
  120. return OpenLevelDBMemory()
  121. }
  122. var (
  123. errClosed = errors.New("database is closed")
  124. errNotFound = errors.New("key not found")
  125. )
  126. func IsClosed(err error) bool { return errors.Is(err, errClosed) }
  127. func IsNotFound(err error) bool { return errors.Is(err, errNotFound) }
  128. // releaser manages counting on top of a waitgroup
  129. type releaser struct {
  130. wg *closeWaitGroup
  131. once sync.Once
  132. }
  133. func newReleaser(wg *closeWaitGroup) (*releaser, error) {
  134. if err := wg.Add(1); err != nil {
  135. return nil, err
  136. }
  137. return &releaser{wg: wg}, nil
  138. }
  139. func (r *releaser) Release() {
  140. // We use the Once because we may get called multiple times from
  141. // Commit() and deferred Release().
  142. r.once.Do(r.wg.Done)
  143. }
  144. // closeWaitGroup behaves just like a sync.WaitGroup, but does not require
  145. // a single routine to do the Add and Wait calls. If Add is called after
  146. // CloseWait, it will return an error, and both are safe to be used concurrently.
  147. type closeWaitGroup struct {
  148. sync.WaitGroup
  149. closed bool
  150. closeMut sync.RWMutex
  151. }
  152. func (cg *closeWaitGroup) Add(i int) error {
  153. cg.closeMut.RLock()
  154. defer cg.closeMut.RUnlock()
  155. if cg.closed {
  156. return errClosed
  157. }
  158. cg.WaitGroup.Add(i)
  159. return nil
  160. }
  161. func (cg *closeWaitGroup) CloseWait() {
  162. cg.closeMut.Lock()
  163. cg.closed = true
  164. cg.closeMut.Unlock()
  165. cg.WaitGroup.Wait()
  166. }