util.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. }
  20. // NewFileInfoBatch returns a new FileInfoBatch that calls fn when it's time
  21. // to flush.
  22. func NewFileInfoBatch(fn func([]protocol.FileInfo) error) *FileInfoBatch {
  23. return &FileInfoBatch{flushFn: fn}
  24. }
  25. func (b *FileInfoBatch) SetFlushFunc(fn func([]protocol.FileInfo) error) {
  26. b.flushFn = fn
  27. }
  28. func (b *FileInfoBatch) Append(f protocol.FileInfo) {
  29. if b.infos == nil {
  30. b.infos = make([]protocol.FileInfo, 0, MaxBatchSizeFiles)
  31. }
  32. b.infos = append(b.infos, f)
  33. b.size += f.ProtoSize()
  34. }
  35. func (b *FileInfoBatch) Full() bool {
  36. return len(b.infos) >= MaxBatchSizeFiles || b.size >= MaxBatchSizeBytes
  37. }
  38. func (b *FileInfoBatch) FlushIfFull() error {
  39. if b.Full() {
  40. return b.Flush()
  41. }
  42. return nil
  43. }
  44. func (b *FileInfoBatch) Flush() error {
  45. if len(b.infos) == 0 {
  46. return nil
  47. }
  48. if err := b.flushFn(b.infos); err != nil {
  49. return err
  50. }
  51. b.Reset()
  52. return nil
  53. }
  54. func (b *FileInfoBatch) Reset() {
  55. b.infos = nil
  56. b.size = 0
  57. }
  58. func (b *FileInfoBatch) Size() int {
  59. return b.size
  60. }