util.go 2.2 KB

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