util.go 1.6 KB

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