folderdb_update.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. // Copyright (C) 2025 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 sqlite
  7. import (
  8. "cmp"
  9. "context"
  10. "fmt"
  11. "slices"
  12. "github.com/jmoiron/sqlx"
  13. "github.com/syncthing/syncthing/internal/gen/dbproto"
  14. "github.com/syncthing/syncthing/internal/itererr"
  15. "github.com/syncthing/syncthing/lib/osutil"
  16. "github.com/syncthing/syncthing/lib/protocol"
  17. "github.com/syncthing/syncthing/lib/sliceutil"
  18. "google.golang.org/protobuf/proto"
  19. )
  20. const (
  21. // Arbitrarily chosen values for checkpoint frequency....
  22. updatePointsPerFile = 100
  23. updatePointsPerBlock = 1
  24. updatePointsThreshold = 250_000
  25. )
  26. func (s *folderDB) Update(device protocol.DeviceID, fs []protocol.FileInfo) error {
  27. s.updateLock.Lock()
  28. defer s.updateLock.Unlock()
  29. deviceIdx, err := s.deviceIdxLocked(device)
  30. if err != nil {
  31. return wrap(err)
  32. }
  33. tx, err := s.sql.BeginTxx(context.Background(), nil)
  34. if err != nil {
  35. return wrap(err)
  36. }
  37. defer tx.Rollback() //nolint:errcheck
  38. txp := &txPreparedStmts{Tx: tx}
  39. //nolint:sqlclosecheck
  40. insertFileStmt, err := txp.Preparex(`
  41. INSERT OR REPLACE INTO files (device_idx, remote_sequence, name, type, modified, size, version, deleted, local_flags, blocklist_hash)
  42. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  43. RETURNING sequence
  44. `)
  45. if err != nil {
  46. return wrap(err, "prepare insert file")
  47. }
  48. //nolint:sqlclosecheck
  49. insertFileInfoStmt, err := txp.Preparex(`
  50. INSERT INTO fileinfos (sequence, fiprotobuf)
  51. VALUES (?, ?)
  52. `)
  53. if err != nil {
  54. return wrap(err, "prepare insert fileinfo")
  55. }
  56. //nolint:sqlclosecheck
  57. insertBlockListStmt, err := txp.Preparex(`
  58. INSERT OR IGNORE INTO blocklists (blocklist_hash, blprotobuf)
  59. VALUES (?, ?)
  60. `)
  61. if err != nil {
  62. return wrap(err, "prepare insert blocklist")
  63. }
  64. var prevRemoteSeq int64
  65. for i, f := range fs {
  66. f.Name = osutil.NormalizedFilename(f.Name)
  67. var blockshash *[]byte
  68. if len(f.Blocks) > 0 {
  69. f.BlocksHash = protocol.BlocksHash(f.Blocks)
  70. blockshash = &f.BlocksHash
  71. } else {
  72. f.BlocksHash = nil
  73. }
  74. if f.Type == protocol.FileInfoTypeDirectory {
  75. f.Size = 128 // synthetic directory size
  76. }
  77. // Insert the file.
  78. //
  79. // If it is a remote file, set remote_sequence otherwise leave it at
  80. // null. Returns the new local sequence.
  81. var remoteSeq *int64
  82. if device != protocol.LocalDeviceID {
  83. if i > 0 && f.Sequence == prevRemoteSeq {
  84. return fmt.Errorf("duplicate remote sequence number %d", prevRemoteSeq)
  85. }
  86. prevRemoteSeq = f.Sequence
  87. remoteSeq = &f.Sequence
  88. }
  89. var localSeq int64
  90. if err := insertFileStmt.Get(&localSeq, deviceIdx, remoteSeq, f.Name, f.Type, f.ModTime().UnixNano(), f.Size, f.Version.String(), f.IsDeleted(), f.LocalFlags, blockshash); err != nil {
  91. return wrap(err, "insert file")
  92. }
  93. if len(f.Blocks) > 0 {
  94. // Indirect the block list
  95. blocks := sliceutil.Map(f.Blocks, protocol.BlockInfo.ToWire)
  96. bs, err := proto.Marshal(&dbproto.BlockList{Blocks: blocks})
  97. if err != nil {
  98. return wrap(err, "marshal blocklist")
  99. }
  100. if _, err := insertBlockListStmt.Exec(f.BlocksHash, bs); err != nil {
  101. return wrap(err, "insert blocklist")
  102. }
  103. if device == protocol.LocalDeviceID {
  104. // Insert all blocks
  105. if err := s.insertBlocksLocked(txp, f.BlocksHash, f.Blocks); err != nil {
  106. return wrap(err, "insert blocks")
  107. }
  108. }
  109. f.Blocks = nil
  110. }
  111. // Insert the fileinfo
  112. if device == protocol.LocalDeviceID {
  113. f.Sequence = localSeq
  114. }
  115. bs, err := proto.Marshal(f.ToWire(true))
  116. if err != nil {
  117. return wrap(err, "marshal fileinfo")
  118. }
  119. if _, err := insertFileInfoStmt.Exec(localSeq, bs); err != nil {
  120. return wrap(err, "insert fileinfo")
  121. }
  122. // Update global and need
  123. if err := s.recalcGlobalForFile(txp, f.Name); err != nil {
  124. return wrap(err)
  125. }
  126. }
  127. if err := tx.Commit(); err != nil {
  128. return wrap(err)
  129. }
  130. s.periodicCheckpointLocked(fs)
  131. return nil
  132. }
  133. func (s *folderDB) DropDevice(device protocol.DeviceID) error {
  134. if device == protocol.LocalDeviceID {
  135. panic("bug: cannot drop local device")
  136. }
  137. s.updateLock.Lock()
  138. defer s.updateLock.Unlock()
  139. tx, err := s.sql.BeginTxx(context.Background(), nil)
  140. if err != nil {
  141. return wrap(err)
  142. }
  143. defer tx.Rollback() //nolint:errcheck
  144. txp := &txPreparedStmts{Tx: tx}
  145. // Drop the device, which cascades to delete all files etc for it
  146. if _, err := tx.Exec(`DELETE FROM devices WHERE device_id = ?`, device.String()); err != nil {
  147. return wrap(err)
  148. }
  149. // Recalc the globals for all affected folders
  150. if err := s.recalcGlobalForFolder(txp); err != nil {
  151. return wrap(err)
  152. }
  153. return wrap(tx.Commit())
  154. }
  155. func (s *folderDB) DropAllFiles(device protocol.DeviceID) error {
  156. s.updateLock.Lock()
  157. defer s.updateLock.Unlock()
  158. // This is a two part operation, first dropping all the files and then
  159. // recalculating the global state for the entire folder.
  160. deviceIdx, err := s.deviceIdxLocked(device)
  161. if err != nil {
  162. return wrap(err)
  163. }
  164. tx, err := s.sql.BeginTxx(context.Background(), nil)
  165. if err != nil {
  166. return wrap(err)
  167. }
  168. defer tx.Rollback() //nolint:errcheck
  169. txp := &txPreparedStmts{Tx: tx}
  170. // Drop all the file entries
  171. result, err := tx.Exec(`
  172. DELETE FROM files
  173. WHERE device_idx = ?
  174. `, deviceIdx)
  175. if err != nil {
  176. return wrap(err)
  177. }
  178. if n, err := result.RowsAffected(); err == nil && n == 0 {
  179. // The delete affected no rows, so we don't need to redo the entire
  180. // global/need calculation.
  181. return wrap(tx.Commit())
  182. }
  183. // Recalc global for the entire folder
  184. if err := s.recalcGlobalForFolder(txp); err != nil {
  185. return wrap(err)
  186. }
  187. return wrap(tx.Commit())
  188. }
  189. func (s *folderDB) DropFilesNamed(device protocol.DeviceID, names []string) error {
  190. for i := range names {
  191. names[i] = osutil.NormalizedFilename(names[i])
  192. }
  193. s.updateLock.Lock()
  194. defer s.updateLock.Unlock()
  195. deviceIdx, err := s.deviceIdxLocked(device)
  196. if err != nil {
  197. return wrap(err)
  198. }
  199. tx, err := s.sql.BeginTxx(context.Background(), nil)
  200. if err != nil {
  201. return wrap(err)
  202. }
  203. defer tx.Rollback() //nolint:errcheck
  204. txp := &txPreparedStmts{Tx: tx}
  205. // Drop the named files
  206. query, args, err := sqlx.In(`
  207. DELETE FROM files
  208. WHERE device_idx = ? AND name IN (?)
  209. `, deviceIdx, names)
  210. if err != nil {
  211. return wrap(err)
  212. }
  213. if _, err := tx.Exec(query, args...); err != nil {
  214. return wrap(err)
  215. }
  216. // Recalc globals for the named files
  217. for _, name := range names {
  218. if err := s.recalcGlobalForFile(txp, name); err != nil {
  219. return wrap(err)
  220. }
  221. }
  222. return wrap(tx.Commit())
  223. }
  224. func (*folderDB) insertBlocksLocked(tx *txPreparedStmts, blocklistHash []byte, blocks []protocol.BlockInfo) error {
  225. if len(blocks) == 0 {
  226. return nil
  227. }
  228. bs := make([]map[string]any, len(blocks))
  229. for i, b := range blocks {
  230. bs[i] = map[string]any{
  231. "hash": b.Hash,
  232. "blocklist_hash": blocklistHash,
  233. "idx": i,
  234. "offset": b.Offset,
  235. "size": b.Size,
  236. }
  237. }
  238. // Very large block lists (>8000 blocks) result in "too many variables"
  239. // error. Chunk it to a reasonable size.
  240. for chunk := range slices.Chunk(bs, 1000) {
  241. if _, err := tx.NamedExec(`
  242. INSERT OR IGNORE INTO blocks (hash, blocklist_hash, idx, offset, size)
  243. VALUES (:hash, :blocklist_hash, :idx, :offset, :size)
  244. `, chunk); err != nil {
  245. return wrap(err)
  246. }
  247. }
  248. return nil
  249. }
  250. func (s *folderDB) recalcGlobalForFolder(txp *txPreparedStmts) error {
  251. // Select files where there is no global, those are the ones we need to
  252. // recalculate.
  253. //nolint:sqlclosecheck
  254. namesStmt, err := txp.Preparex(`
  255. SELECT f.name FROM files f
  256. WHERE NOT EXISTS (
  257. SELECT 1 FROM files g
  258. WHERE g.name = f.name AND g.local_flags & ? != 0
  259. )
  260. GROUP BY name
  261. `)
  262. if err != nil {
  263. return wrap(err)
  264. }
  265. rows, err := namesStmt.Queryx(protocol.FlagLocalGlobal)
  266. if err != nil {
  267. return wrap(err)
  268. }
  269. defer rows.Close()
  270. for rows.Next() {
  271. var name string
  272. if err := rows.Scan(&name); err != nil {
  273. return wrap(err)
  274. }
  275. if err := s.recalcGlobalForFile(txp, name); err != nil {
  276. return wrap(err)
  277. }
  278. }
  279. return wrap(rows.Err())
  280. }
  281. func (s *folderDB) recalcGlobalForFile(txp *txPreparedStmts, file string) error {
  282. //nolint:sqlclosecheck
  283. selStmt, err := txp.Preparex(`
  284. SELECT name, device_idx, sequence, modified, version, deleted, local_flags FROM files
  285. WHERE name = ?
  286. `)
  287. if err != nil {
  288. return wrap(err)
  289. }
  290. es, err := itererr.Collect(iterStructs[fileRow](selStmt.Queryx(file)))
  291. if err != nil {
  292. return wrap(err)
  293. }
  294. if len(es) == 0 {
  295. // shouldn't happen
  296. return nil
  297. }
  298. // Sort the entries; the global entry is at the head of the list
  299. slices.SortFunc(es, fileRow.Compare)
  300. // The global version is the first one in the list that is not invalid,
  301. // or just the first one in the list if all are invalid.
  302. var global fileRow
  303. globIdx := slices.IndexFunc(es, func(e fileRow) bool { return !e.IsInvalid() })
  304. if globIdx < 0 {
  305. globIdx = 0
  306. }
  307. global = es[globIdx]
  308. // We "have" the file if the position in the list of versions is at the
  309. // global version or better, or if the version is the same as the global
  310. // file (we might be further down the list due to invalid flags), or if
  311. // the global is deleted and we don't have it at all...
  312. localIdx := slices.IndexFunc(es, func(e fileRow) bool { return e.DeviceIdx == s.localDeviceIdx })
  313. hasLocal := localIdx >= 0 && localIdx <= globIdx || // have a better or equal version
  314. localIdx >= 0 && es[localIdx].Version.Equal(global.Version.Vector) || // have an equal version but invalid/ignored
  315. localIdx < 0 && global.Deleted // missing it, but the global is also deleted
  316. // Set the global flag on the global entry. Set the need flag if the
  317. // local device needs this file, unless it's invalid.
  318. global.LocalFlags |= protocol.FlagLocalGlobal
  319. if hasLocal || global.IsInvalid() {
  320. global.LocalFlags &= ^protocol.FlagLocalNeeded
  321. } else {
  322. global.LocalFlags |= protocol.FlagLocalNeeded
  323. }
  324. //nolint:sqlclosecheck
  325. upStmt, err := txp.Preparex(`
  326. UPDATE files SET local_flags = ?
  327. WHERE device_idx = ? AND sequence = ?
  328. `)
  329. if err != nil {
  330. return wrap(err)
  331. }
  332. if _, err := upStmt.Exec(global.LocalFlags, global.DeviceIdx, global.Sequence); err != nil {
  333. return wrap(err)
  334. }
  335. // Clear the need and global flags on all other entries
  336. //nolint:sqlclosecheck
  337. upStmt, err = txp.Preparex(`
  338. UPDATE files SET local_flags = local_flags & ?
  339. WHERE name = ? AND sequence != ? AND local_flags & ? != 0
  340. `)
  341. if err != nil {
  342. return wrap(err)
  343. }
  344. if _, err := upStmt.Exec(^(protocol.FlagLocalNeeded | protocol.FlagLocalGlobal), global.Name, global.Sequence, protocol.FlagLocalNeeded|protocol.FlagLocalGlobal); err != nil {
  345. return wrap(err)
  346. }
  347. return nil
  348. }
  349. func (s *DB) folderIdxLocked(folderID string) (int64, error) {
  350. if _, err := s.stmt(`
  351. INSERT OR IGNORE INTO folders(folder_id)
  352. VALUES (?)
  353. `).Exec(folderID); err != nil {
  354. return 0, wrap(err)
  355. }
  356. var idx int64
  357. if err := s.stmt(`
  358. SELECT idx FROM folders
  359. WHERE folder_id = ?
  360. `).Get(&idx, folderID); err != nil {
  361. return 0, wrap(err)
  362. }
  363. return idx, nil
  364. }
  365. type fileRow struct {
  366. Name string
  367. Version dbVector
  368. DeviceIdx int64 `db:"device_idx"`
  369. Sequence int64
  370. Modified int64
  371. Size int64
  372. LocalFlags protocol.FlagLocal `db:"local_flags"`
  373. Deleted bool
  374. }
  375. func (e fileRow) Compare(other fileRow) int {
  376. // From FileInfo.WinsConflict
  377. vc := e.Version.Compare(other.Version.Vector)
  378. switch vc {
  379. case protocol.Equal:
  380. if e.IsInvalid() != other.IsInvalid() {
  381. if e.IsInvalid() {
  382. return 1
  383. }
  384. return -1
  385. }
  386. // Compare the device ID index, lower is better. This is only
  387. // deterministic to the extent that LocalDeviceID will always be the
  388. // lowest one, order between remote devices is random (and
  389. // irrelevant).
  390. return cmp.Compare(e.DeviceIdx, other.DeviceIdx)
  391. case protocol.Greater: // we are newer
  392. return -1
  393. case protocol.Lesser: // we are older
  394. return 1
  395. case protocol.ConcurrentGreater, protocol.ConcurrentLesser: // there is a conflict
  396. if e.IsInvalid() != other.IsInvalid() {
  397. if e.IsInvalid() { // we are invalid, we lose
  398. return 1
  399. }
  400. return -1 // they are invalid, we win
  401. }
  402. if e.Deleted != other.Deleted {
  403. if e.Deleted { // we are deleted, we lose
  404. return 1
  405. }
  406. return -1 // they are deleted, we win
  407. }
  408. if d := cmp.Compare(e.Modified, other.Modified); d != 0 {
  409. return -d // positive d means we were newer, so we win (negative return)
  410. }
  411. if vc == protocol.ConcurrentGreater {
  412. return -1 // we have a better device ID, we win
  413. }
  414. return 1 // they win
  415. default:
  416. return 0
  417. }
  418. }
  419. func (e fileRow) IsInvalid() bool {
  420. return e.LocalFlags.IsInvalid()
  421. }
  422. func (s *folderDB) periodicCheckpointLocked(fs []protocol.FileInfo) {
  423. // Induce periodic checkpoints. We add points for each file and block,
  424. // and checkpoint when we've written more than a threshold of points.
  425. // This ensures we do not go too long without a checkpoint, while also
  426. // not doing it incessantly for every update.
  427. s.updatePoints += updatePointsPerFile * len(fs)
  428. for _, f := range fs {
  429. s.updatePoints += len(f.Blocks) * updatePointsPerBlock
  430. }
  431. if s.updatePoints > updatePointsThreshold {
  432. conn, err := s.sql.Conn(context.Background())
  433. if err != nil {
  434. l.Debugln(s.baseName, "conn:", err)
  435. return
  436. }
  437. defer conn.Close()
  438. if _, err := conn.ExecContext(context.Background(), `PRAGMA journal_size_limit = 8388608`); err != nil {
  439. l.Debugln(s.baseName, "PRAGMA journal_size_limit:", err)
  440. }
  441. // Every 50th checkpoint becomes a truncate, in an effort to bring
  442. // down the size now and then.
  443. checkpointType := "RESTART"
  444. if s.checkpointsCount > 50 {
  445. checkpointType = "TRUNCATE"
  446. }
  447. cmd := fmt.Sprintf(`PRAGMA wal_checkpoint(%s)`, checkpointType)
  448. row := conn.QueryRowContext(context.Background(), cmd)
  449. var res, modified, moved int
  450. if row.Err() != nil {
  451. l.Debugln(s.baseName, cmd+":", err)
  452. } else if err := row.Scan(&res, &modified, &moved); err != nil {
  453. l.Debugln(s.baseName, cmd+" (scan):", err)
  454. } else {
  455. l.Debugln(s.baseName, cmd, s.checkpointsCount, "at", s.updatePoints, "returned", res, modified, moved)
  456. }
  457. // Reset the truncate counter when a truncate succeeded. If it
  458. // failed, we'll keep trying it until we succeed. Increase it faster
  459. // when we fail to checkpoint, as it's more likely the WAL is
  460. // growing and will need truncation when we get out of this state.
  461. switch {
  462. case res == 1:
  463. s.checkpointsCount += 10
  464. case res == 0 && checkpointType == "TRUNCATE":
  465. s.checkpointsCount = 0
  466. default:
  467. s.checkpointsCount++
  468. }
  469. s.updatePoints = 0
  470. }
  471. }