util.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright (C) 2021 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 db
  7. import "github.com/syncthing/syncthing/lib/protocol"
  8. // How many files to send in each Index/IndexUpdate message.
  9. const (
  10. MaxBatchSizeBytes = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  11. MaxBatchSizeFiles = 1000 // Either way, don't include more files than this
  12. )
  13. // FileInfoBatch is a utility to do file operations on the database in suitably
  14. // sized batches.
  15. type FileInfoBatch struct {
  16. infos []protocol.FileInfo
  17. size int
  18. flushFn func([]protocol.FileInfo) error
  19. error error
  20. }
  21. // NewFileInfoBatch returns a new FileInfoBatch that calls fn when it's time
  22. // to flush. Errors from the flush function are considered non-recoverable;
  23. // once an error is returned the flush function wil not be called again, and
  24. // any further calls to Flush will return the same error (unless Reset is
  25. // called).
  26. func NewFileInfoBatch(fn func([]protocol.FileInfo) error) *FileInfoBatch {
  27. return &FileInfoBatch{flushFn: fn}
  28. }
  29. func (b *FileInfoBatch) SetFlushFunc(fn func([]protocol.FileInfo) error) {
  30. b.flushFn = fn
  31. }
  32. func (b *FileInfoBatch) Append(f protocol.FileInfo) {
  33. if b.error != nil {
  34. panic("bug: calling append on a failed batch")
  35. }
  36. if b.infos == nil {
  37. b.infos = make([]protocol.FileInfo, 0, MaxBatchSizeFiles)
  38. }
  39. b.infos = append(b.infos, f)
  40. b.size += f.ProtoSize()
  41. }
  42. func (b *FileInfoBatch) Full() bool {
  43. return len(b.infos) >= MaxBatchSizeFiles || b.size >= MaxBatchSizeBytes
  44. }
  45. func (b *FileInfoBatch) FlushIfFull() error {
  46. if b.error != nil {
  47. return b.error
  48. }
  49. if b.Full() {
  50. return b.Flush()
  51. }
  52. return nil
  53. }
  54. func (b *FileInfoBatch) Flush() error {
  55. if b.error != nil {
  56. return b.error
  57. }
  58. if len(b.infos) == 0 {
  59. return nil
  60. }
  61. if err := b.flushFn(b.infos); err != nil {
  62. b.error = err
  63. return err
  64. }
  65. b.Reset()
  66. return nil
  67. }
  68. func (b *FileInfoBatch) Reset() {
  69. b.infos = nil
  70. b.error = nil
  71. b.size = 0
  72. }
  73. func (b *FileInfoBatch) Size() int {
  74. return b.size
  75. }