File: structs.go

package info (click to toggle)
syncthing 1.29.5~ds1-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 22,848 kB
  • sloc: javascript: 37,288; sh: 1,838; xml: 1,115; makefile: 66
file content (363 lines) | stat: -rw-r--r-- 11,246 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package db

import (
	"bytes"
	"fmt"
	"strings"

	"google.golang.org/protobuf/proto"

	"github.com/syncthing/syncthing/internal/gen/dbproto"
	"github.com/syncthing/syncthing/lib/protocol"
)

type CountsSet struct {
	Counts  []Counts
	Created int64 // unix nanos
}

type Counts struct {
	Files       int
	Directories int
	Symlinks    int
	Deleted     int
	Bytes       int64
	Sequence    int64             // zero for the global state
	DeviceID    protocol.DeviceID // device ID for remote devices, or special values for local/global
	LocalFlags  uint32            // the local flag for this count bucket
}

func (c Counts) toWire() *dbproto.Counts {
	return &dbproto.Counts{
		Files:       int32(c.Files),
		Directories: int32(c.Directories),
		Symlinks:    int32(c.Symlinks),
		Deleted:     int32(c.Deleted),
		Bytes:       c.Bytes,
		Sequence:    c.Sequence,
		DeviceId:    c.DeviceID[:],
		LocalFlags:  c.LocalFlags,
	}
}

func countsFromWire(w *dbproto.Counts) Counts {
	return Counts{
		Files:       int(w.Files),
		Directories: int(w.Directories),
		Symlinks:    int(w.Symlinks),
		Deleted:     int(w.Deleted),
		Bytes:       w.Bytes,
		Sequence:    w.Sequence,
		DeviceID:    protocol.DeviceID(w.DeviceId),
		LocalFlags:  w.LocalFlags,
	}
}

func (c Counts) Add(other Counts) Counts {
	return Counts{
		Files:       c.Files + other.Files,
		Directories: c.Directories + other.Directories,
		Symlinks:    c.Symlinks + other.Symlinks,
		Deleted:     c.Deleted + other.Deleted,
		Bytes:       c.Bytes + other.Bytes,
		Sequence:    c.Sequence + other.Sequence,
		DeviceID:    protocol.EmptyDeviceID,
		LocalFlags:  c.LocalFlags | other.LocalFlags,
	}
}

func (c Counts) TotalItems() int {
	return c.Files + c.Directories + c.Symlinks + c.Deleted
}

func (c Counts) String() string {
	var flags strings.Builder
	if c.LocalFlags&needFlag != 0 {
		flags.WriteString("Need")
	}
	if c.LocalFlags&protocol.FlagLocalIgnored != 0 {
		flags.WriteString("Ignored")
	}
	if c.LocalFlags&protocol.FlagLocalMustRescan != 0 {
		flags.WriteString("Rescan")
	}
	if c.LocalFlags&protocol.FlagLocalReceiveOnly != 0 {
		flags.WriteString("Recvonly")
	}
	if c.LocalFlags&protocol.FlagLocalUnsupported != 0 {
		flags.WriteString("Unsupported")
	}
	if c.LocalFlags != 0 {
		flags.WriteString(fmt.Sprintf("(%x)", c.LocalFlags))
	}
	if flags.Len() == 0 {
		flags.WriteString("---")
	}
	return fmt.Sprintf("{Device:%v, Files:%d, Dirs:%d, Symlinks:%d, Del:%d, Bytes:%d, Seq:%d, Flags:%s}", c.DeviceID, c.Files, c.Directories, c.Symlinks, c.Deleted, c.Bytes, c.Sequence, flags.String())
}

// Equal compares the numbers only, not sequence/dev/flags.
func (c Counts) Equal(o Counts) bool {
	return c.Files == o.Files && c.Directories == o.Directories && c.Symlinks == o.Symlinks && c.Deleted == o.Deleted && c.Bytes == o.Bytes
}

// update brings the VersionList up to date with file. It returns the updated
// VersionList, a device that has the global/newest version, a device that previously
// had the global/newest version, a boolean indicating if the global version has
// changed and if any error occurred (only possible in db interaction).
func vlUpdate(vl *dbproto.VersionList, folder, device []byte, file protocol.FileInfo, t readOnlyTransaction) (*dbproto.FileVersion, *dbproto.FileVersion, *dbproto.FileVersion, bool, bool, bool, error) {
	if len(vl.Versions) == 0 {
		nv := newFileVersion(device, file.FileVersion(), file.IsInvalid(), file.IsDeleted())
		vl.Versions = append(vl.Versions, nv)
		return nv, nil, nil, false, false, true, nil
	}

	// Get the current global (before updating)
	oldFV, haveOldGlobal := vlGetGlobal(vl)
	oldFV = fvCopy(oldFV)

	// Remove ourselves first
	removedFV, haveRemoved, _ := vlPop(vl, device)
	// Find position and insert the file
	err := vlInsert(vl, folder, device, file, t)
	if err != nil {
		return nil, nil, nil, false, false, false, err
	}

	newFV, _ := vlGetGlobal(vl) // We just inserted something above, can't be empty

	if !haveOldGlobal {
		return newFV, nil, removedFV, false, haveRemoved, true, nil
	}

	globalChanged := true
	if fvIsInvalid(oldFV) == fvIsInvalid(newFV) && protocol.VectorFromWire(oldFV.Version).Equal(protocol.VectorFromWire(newFV.Version)) {
		globalChanged = false
	}

	return newFV, oldFV, removedFV, true, haveRemoved, globalChanged, nil
}

func vlInsert(vl *dbproto.VersionList, folder, device []byte, file protocol.FileInfo, t readOnlyTransaction) error {
	var added bool
	var err error
	i := 0
	for ; i < len(vl.Versions); i++ {
		// Insert our new version
		added, err = vlCheckInsertAt(vl, i, folder, device, file, t)
		if err != nil {
			return err
		}
		if added {
			break
		}
	}
	if i == len(vl.Versions) {
		// Append to the end
		vl.Versions = append(vl.Versions, newFileVersion(device, file.FileVersion(), file.IsInvalid(), file.IsDeleted()))
	}
	return nil
}

func vlInsertAt(vl *dbproto.VersionList, i int, v *dbproto.FileVersion) {
	vl.Versions = append(vl.Versions, &dbproto.FileVersion{})
	copy(vl.Versions[i+1:], vl.Versions[i:])
	vl.Versions[i] = v
}

// pop removes the given device from the VersionList and returns the FileVersion
// before removing the device, whether it was found/removed at all and whether
// the global changed in the process.
func vlPop(vl *dbproto.VersionList, device []byte) (*dbproto.FileVersion, bool, bool) {
	invDevice, i, j, ok := vlFindDevice(vl, device)
	if !ok {
		return nil, false, false
	}
	globalPos := vlFindGlobal(vl)

	fv := vl.Versions[i]
	if fvDeviceCount(fv) == 1 {
		vlPopVersionAt(vl, i)
		return fv, true, globalPos == i
	}

	oldFV := fvCopy(fv)
	if invDevice {
		vl.Versions[i].InvalidDevices = popDeviceAt(vl.Versions[i].InvalidDevices, j)
		return oldFV, true, false
	}
	vl.Versions[i].Devices = popDeviceAt(vl.Versions[i].Devices, j)
	// If the last valid device of the previous global was removed above,
	// the global changed.
	return oldFV, true, len(vl.Versions[i].Devices) == 0 && globalPos == i
}

// Get returns a FileVersion that contains the given device and whether it has
// been found at all.
func vlGet(vl *dbproto.VersionList, device []byte) (*dbproto.FileVersion, bool) {
	_, i, _, ok := vlFindDevice(vl, device)
	if !ok {
		return &dbproto.FileVersion{}, false
	}
	return vl.Versions[i], true
}

// GetGlobal returns the current global FileVersion. The returned FileVersion
// may be invalid, if all FileVersions are invalid. Returns false only if
// VersionList is empty.
func vlGetGlobal(vl *dbproto.VersionList) (*dbproto.FileVersion, bool) {
	i := vlFindGlobal(vl)
	if i == -1 {
		return nil, false
	}
	return vl.Versions[i], true
}

// findGlobal returns the first version that isn't invalid, or if all versions are
// invalid just the first version (i.e. 0) or -1, if there's no versions at all.
func vlFindGlobal(vl *dbproto.VersionList) int {
	for i := range vl.Versions {
		if !fvIsInvalid(vl.Versions[i]) {
			return i
		}
	}
	if len(vl.Versions) == 0 {
		return -1
	}
	return 0
}

// findDevice returns whether the device is in InvalidVersions or Versions and
// in InvalidDevices or Devices (true for invalid), the positions in the version
// and device slices and whether it has been found at all.
func vlFindDevice(vl *dbproto.VersionList, device []byte) (bool, int, int, bool) {
	for i, v := range vl.Versions {
		if j := deviceIndex(v.Devices, device); j != -1 {
			return false, i, j, true
		}
		if j := deviceIndex(v.InvalidDevices, device); j != -1 {
			return true, i, j, true
		}
	}
	return false, -1, -1, false
}

func vlPopVersionAt(vl *dbproto.VersionList, i int) {
	vl.Versions = append(vl.Versions[:i], vl.Versions[i+1:]...)
}

// checkInsertAt determines if the given device and associated file should be
// inserted into the FileVersion at position i or into a new FileVersion at
// position i.
func vlCheckInsertAt(vl *dbproto.VersionList, i int, folder, device []byte, file protocol.FileInfo, t readOnlyTransaction) (bool, error) {
	fv := vl.Versions[i]
	ordering := protocol.VectorFromWire(fv.Version).Compare(file.FileVersion())
	if ordering == protocol.Equal {
		if !file.IsInvalid() {
			fv.Devices = append(fv.Devices, device)
		} else {
			fv.InvalidDevices = append(fv.InvalidDevices, device)
		}
		return true, nil
	}
	existingDevice, _ := fvFirstDevice(fv)
	insert, err := shouldInsertBefore(ordering, folder, existingDevice, fvIsInvalid(fv), file, t)
	if err != nil {
		return false, err
	}
	if insert {
		vlInsertAt(vl, i, newFileVersion(device, file.FileVersion(), file.IsInvalid(), file.IsDeleted()))
		return true, nil
	}
	return false, nil
}

// shouldInsertBefore determines whether the file comes before an existing
// entry, given the version ordering (existing compared to new one), existing
// device and if the existing version is invalid.
func shouldInsertBefore(ordering protocol.Ordering, folder, existingDevice []byte, existingInvalid bool, file protocol.FileInfo, t readOnlyTransaction) (bool, error) {
	switch ordering {
	case protocol.Lesser:
		// The version at this point in the list is lesser
		// ("older") than us. We insert ourselves in front of it.
		return true, nil

	case protocol.ConcurrentLesser, protocol.ConcurrentGreater:
		// The version in conflict with us.
		// Check if we can shortcut due to one being invalid.
		if existingInvalid != file.IsInvalid() {
			return existingInvalid, nil
		}
		// We must pull the actual file metadata to determine who wins.
		// If we win, we insert ourselves in front of the loser here.
		// (The "Lesser" and "Greater" in the condition above is just
		// based on the device IDs in the version vector, which is not
		// the only thing we use to determine the winner.)
		of, ok, err := t.getFile(folder, existingDevice, []byte(file.FileName()))
		if err != nil {
			return false, err
		}
		// A surprise missing file entry here is counted as a win for us.
		if !ok {
			return true, nil
		}
		if file.WinsConflict(of) {
			return true, nil
		}
	}
	return false, nil
}

func deviceIndex(devices [][]byte, device []byte) int {
	for i, dev := range devices {
		if bytes.Equal(device, dev) {
			return i
		}
	}
	return -1
}

func popDeviceAt(devices [][]byte, i int) [][]byte {
	return append(devices[:i], devices[i+1:]...)
}

func newFileVersion(device []byte, version protocol.Vector, invalid, deleted bool) *dbproto.FileVersion {
	fv := &dbproto.FileVersion{
		Version: version.ToWire(),
		Deleted: deleted,
	}
	if invalid {
		fv.InvalidDevices = [][]byte{device}
	} else {
		fv.Devices = [][]byte{device}
	}
	return fv
}

func fvFirstDevice(fv *dbproto.FileVersion) ([]byte, bool) {
	if len(fv.Devices) != 0 {
		return fv.Devices[0], true
	}
	if len(fv.InvalidDevices) != 0 {
		return fv.InvalidDevices[0], true
	}
	return nil, false
}

func fvIsInvalid(fv *dbproto.FileVersion) bool {
	return fv == nil || len(fv.Devices) == 0
}

func fvDeviceCount(fv *dbproto.FileVersion) int {
	return len(fv.Devices) + len(fv.InvalidDevices)
}

func fvCopy(fv *dbproto.FileVersion) *dbproto.FileVersion {
	return proto.Clone(fv).(*dbproto.FileVersion)
}