db_test.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  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. "context"
  9. "crypto/sha256"
  10. "encoding/binary"
  11. "errors"
  12. "iter"
  13. "os"
  14. "path"
  15. "path/filepath"
  16. "sync"
  17. "testing"
  18. "time"
  19. "github.com/syncthing/syncthing/internal/db"
  20. "github.com/syncthing/syncthing/internal/itererr"
  21. "github.com/syncthing/syncthing/internal/timeutil"
  22. "github.com/syncthing/syncthing/lib/build"
  23. "github.com/syncthing/syncthing/lib/config"
  24. "github.com/syncthing/syncthing/lib/protocol"
  25. )
  26. const (
  27. folderID = "test"
  28. blockSize = 128 << 10
  29. dirSize = 128
  30. )
  31. func TestBasics(t *testing.T) {
  32. t.Parallel()
  33. sdb, err := Open(t.TempDir())
  34. if err != nil {
  35. t.Fatal(err)
  36. }
  37. t.Cleanup(func() {
  38. if err := sdb.Close(); err != nil {
  39. t.Fatal(err)
  40. }
  41. })
  42. // Some local files
  43. local := []protocol.FileInfo{
  44. genFile("test1", 1, 0),
  45. genDir("test2", 0),
  46. genFile("test2/a", 2, 0),
  47. genFile("test2/b", 3, 0),
  48. }
  49. err = sdb.Update(folderID, protocol.LocalDeviceID, local)
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. // Some remote files
  54. remote := []protocol.FileInfo{
  55. genFile("test3", 3, 101),
  56. genFile("test4", 4, 102),
  57. genFile("test1", 5, 103),
  58. }
  59. // All newer than the local ones
  60. for i := range remote {
  61. remote[i].Version = remote[i].Version.Update(42)
  62. }
  63. err = sdb.Update(folderID, protocol.DeviceID{42}, remote)
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. const (
  68. localSize = (1+2+3)*blockSize + dirSize
  69. remoteSize = (3 + 4 + 5) * blockSize
  70. globalSize = (2+3+3+4+5)*blockSize + dirSize
  71. needSizeLocal = remoteSize
  72. needSizeRemote = (2+3)*blockSize + dirSize
  73. )
  74. t.Run("SchemaVersion", func(t *testing.T) {
  75. ver, err := sdb.getAppliedSchemaVersion()
  76. if err != nil {
  77. t.Fatal(err)
  78. }
  79. if ver.SchemaVersion != currentSchemaVersion {
  80. t.Log(ver)
  81. t.Error("should be version 1")
  82. }
  83. if d := time.Since(ver.AppliedTime()); d > time.Minute || d < 0 {
  84. t.Log(ver)
  85. t.Error("suspicious applied tim")
  86. }
  87. })
  88. t.Run("Local", func(t *testing.T) {
  89. t.Parallel()
  90. fi, ok, err := sdb.GetDeviceFile(folderID, protocol.LocalDeviceID, "test2/a") // exists
  91. if err != nil {
  92. t.Fatal(err)
  93. }
  94. if !ok {
  95. t.Fatal("not found")
  96. }
  97. if fi.Name != filepath.FromSlash("test2/a") {
  98. t.Fatal("should have got test2/a")
  99. }
  100. if len(fi.Blocks) != 2 {
  101. t.Fatal("expected two blocks")
  102. }
  103. _, ok, err = sdb.GetDeviceFile(folderID, protocol.LocalDeviceID, "test3") // does not exist
  104. if err != nil {
  105. t.Fatal(err)
  106. }
  107. if ok {
  108. t.Fatal("should be not found")
  109. }
  110. })
  111. t.Run("Global", func(t *testing.T) {
  112. t.Parallel()
  113. fi, ok, err := sdb.GetGlobalFile(folderID, "test1")
  114. if err != nil {
  115. t.Fatal(err)
  116. }
  117. if !ok {
  118. t.Fatal("not found")
  119. }
  120. if fi.Size != 5*blockSize {
  121. t.Fatal("should be the remote file")
  122. }
  123. })
  124. t.Run("AllLocal", func(t *testing.T) {
  125. t.Parallel()
  126. have := mustCollect[protocol.FileInfo](t)(sdb.AllLocalFiles(folderID, protocol.LocalDeviceID))
  127. if len(have) != 4 {
  128. t.Log(have)
  129. t.Error("expected four files")
  130. }
  131. have = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFiles(folderID, protocol.DeviceID{42}))
  132. if len(have) != 3 {
  133. t.Log(have)
  134. t.Error("expected three files")
  135. }
  136. })
  137. t.Run("AllNeededNamesLocal", func(t *testing.T) {
  138. t.Parallel()
  139. need := fiNames(mustCollect[protocol.FileInfo](t)(sdb.AllNeededGlobalFiles(folderID, protocol.LocalDeviceID, config.PullOrderAlphabetic, 0, 0)))
  140. if len(need) != 3 || need[0] != "test1" {
  141. t.Log(need)
  142. t.Error("expected three files, ordered alphabetically")
  143. }
  144. need = fiNames(mustCollect[protocol.FileInfo](t)(sdb.AllNeededGlobalFiles(folderID, protocol.LocalDeviceID, config.PullOrderAlphabetic, 1, 0)))
  145. if len(need) != 1 || need[0] != "test1" {
  146. t.Log(need)
  147. t.Error("expected one file, limited, ordered alphabetically")
  148. }
  149. need = fiNames(mustCollect[protocol.FileInfo](t)(sdb.AllNeededGlobalFiles(folderID, protocol.LocalDeviceID, config.PullOrderLargestFirst, 0, 0)))
  150. if len(need) != 3 || need[0] != "test1" { // largest
  151. t.Log(need)
  152. t.Error("expected three files, ordered largest to smallest")
  153. }
  154. need = fiNames(mustCollect[protocol.FileInfo](t)(sdb.AllNeededGlobalFiles(folderID, protocol.LocalDeviceID, config.PullOrderSmallestFirst, 0, 0)))
  155. if len(need) != 3 || need[0] != "test3" { // smallest
  156. t.Log(need)
  157. t.Error("expected three files, ordered smallest to largest")
  158. }
  159. need = fiNames(mustCollect[protocol.FileInfo](t)(sdb.AllNeededGlobalFiles(folderID, protocol.LocalDeviceID, config.PullOrderNewestFirst, 0, 0)))
  160. if len(need) != 3 || need[0] != "test1" { // newest
  161. t.Log(need)
  162. t.Error("expected three files, ordered newest to oldest")
  163. }
  164. need = fiNames(mustCollect[protocol.FileInfo](t)(sdb.AllNeededGlobalFiles(folderID, protocol.LocalDeviceID, config.PullOrderOldestFirst, 0, 0)))
  165. if len(need) != 3 || need[0] != "test3" { // oldest
  166. t.Log(need)
  167. t.Error("expected three files, ordered oldest to newest")
  168. }
  169. })
  170. t.Run("LocalSize", func(t *testing.T) {
  171. t.Parallel()
  172. // Local device
  173. c, err := sdb.CountLocal(folderID, protocol.LocalDeviceID)
  174. if err != nil {
  175. t.Fatal(err)
  176. }
  177. if c.Files != 3 {
  178. t.Log(c)
  179. t.Error("one file expected")
  180. }
  181. if c.Directories != 1 {
  182. t.Log(c)
  183. t.Error("one directory expected")
  184. }
  185. if c.Bytes != localSize {
  186. t.Log(c)
  187. t.Error("size unexpected")
  188. }
  189. // Other device
  190. c, err = sdb.CountLocal(folderID, protocol.DeviceID{42})
  191. if err != nil {
  192. t.Fatal(err)
  193. }
  194. if c.Files != 3 {
  195. t.Log(c)
  196. t.Error("three files expected")
  197. }
  198. if c.Directories != 0 {
  199. t.Log(c)
  200. t.Error("no directories expected")
  201. }
  202. if c.Bytes != remoteSize {
  203. t.Log(c)
  204. t.Error("size unexpected")
  205. }
  206. })
  207. t.Run("GlobalSize", func(t *testing.T) {
  208. t.Parallel()
  209. c, err := sdb.CountGlobal(folderID)
  210. if err != nil {
  211. t.Fatal(err)
  212. }
  213. if c.Files != 5 {
  214. t.Log(c)
  215. t.Error("five files expected")
  216. }
  217. if c.Directories != 1 {
  218. t.Log(c)
  219. t.Error("one directory expected")
  220. }
  221. if c.Bytes != int64(globalSize) {
  222. t.Log(c)
  223. t.Error("size unexpected")
  224. }
  225. })
  226. t.Run("NeedSizeLocal", func(t *testing.T) {
  227. t.Parallel()
  228. c, err := sdb.CountNeed(folderID, protocol.LocalDeviceID)
  229. if err != nil {
  230. t.Fatal(err)
  231. }
  232. if c.Files != 3 {
  233. t.Log(c)
  234. t.Error("three files expected")
  235. }
  236. if c.Directories != 0 {
  237. t.Log(c)
  238. t.Error("no directories expected")
  239. }
  240. if c.Bytes != needSizeLocal {
  241. t.Log(c)
  242. t.Error("size unexpected")
  243. }
  244. })
  245. t.Run("NeedSizeRemote", func(t *testing.T) {
  246. t.Parallel()
  247. c, err := sdb.CountNeed(folderID, protocol.DeviceID{42})
  248. if err != nil {
  249. t.Fatal(err)
  250. }
  251. if c.Files != 2 {
  252. t.Log(c)
  253. t.Error("two files expected")
  254. }
  255. if c.Directories != 1 {
  256. t.Log(c)
  257. t.Error("one directory expected")
  258. }
  259. if c.Bytes != needSizeRemote {
  260. t.Log(c)
  261. t.Error("size unexpected")
  262. }
  263. })
  264. t.Run("Folders", func(t *testing.T) {
  265. t.Parallel()
  266. folders, err := sdb.ListFolders()
  267. if err != nil {
  268. t.Fatal(err)
  269. }
  270. if len(folders) != 1 || folders[0] != folderID {
  271. t.Log(folders)
  272. t.Error("expected one folder")
  273. }
  274. })
  275. t.Run("DevicesForFolder", func(t *testing.T) {
  276. t.Parallel()
  277. devs, err := sdb.ListDevicesForFolder("test")
  278. if err != nil {
  279. t.Fatal(err)
  280. }
  281. if len(devs) != 1 || devs[0] != (protocol.DeviceID{42}) {
  282. t.Log(devs)
  283. t.Error("expected one device")
  284. }
  285. })
  286. t.Run("Sequence", func(t *testing.T) {
  287. t.Parallel()
  288. iid, err := sdb.GetIndexID(folderID, protocol.LocalDeviceID)
  289. if err != nil {
  290. t.Fatal(err)
  291. }
  292. if iid == 0 {
  293. t.Log(iid)
  294. t.Fatal("expected index ID")
  295. }
  296. if seq, err := sdb.GetDeviceSequence(folderID, protocol.LocalDeviceID); err != nil {
  297. t.Fatal(err)
  298. } else if seq != 4 {
  299. t.Log(seq)
  300. t.Error("expected local sequence to match number of files inserted")
  301. }
  302. if seq, err := sdb.GetDeviceSequence(folderID, protocol.DeviceID{42}); err != nil {
  303. t.Fatal(err)
  304. } else if seq != 103 {
  305. t.Log(seq)
  306. t.Error("expected remote sequence to match highest sent")
  307. }
  308. // Non-existent should be zero and no error
  309. if seq, err := sdb.GetDeviceSequence("trolol", protocol.LocalDeviceID); err != nil {
  310. t.Fatal(err)
  311. } else if seq != 0 {
  312. t.Log(seq)
  313. t.Error("expected zero sequence")
  314. }
  315. if seq, err := sdb.GetDeviceSequence("trolol", protocol.DeviceID{42}); err != nil {
  316. t.Fatal(err)
  317. } else if seq != 0 {
  318. t.Log(seq)
  319. t.Error("expected zero sequence")
  320. }
  321. if seq, err := sdb.GetDeviceSequence(folderID, protocol.DeviceID{99}); err != nil {
  322. t.Fatal(err)
  323. } else if seq != 0 {
  324. t.Log(seq)
  325. t.Error("expected zero sequence")
  326. }
  327. })
  328. t.Run("AllGlobalPrefix", func(t *testing.T) {
  329. t.Parallel()
  330. vals := mustCollect[db.FileMetadata](t)(sdb.AllGlobalFilesPrefix(folderID, "test2"))
  331. // Vals should be test2, test2/a, test2/b
  332. if len(vals) != 3 {
  333. t.Log(vals)
  334. t.Error("expected three items")
  335. } else if vals[0].Name != "test2" {
  336. t.Error(vals)
  337. }
  338. // Empty prefix should be all the files
  339. vals = mustCollect[db.FileMetadata](t)(sdb.AllGlobalFilesPrefix(folderID, ""))
  340. if len(vals) != 6 {
  341. t.Log(vals)
  342. t.Error("expected six items")
  343. }
  344. })
  345. t.Run("AllLocalPrefix", func(t *testing.T) {
  346. t.Parallel()
  347. vals := mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "test2"))
  348. // Vals should be test2, test2/a, test2/b
  349. if len(vals) != 3 {
  350. t.Log(vals)
  351. t.Error("expected three items")
  352. } else if vals[0].Name != "test2" {
  353. t.Error(vals)
  354. }
  355. // Empty prefix should be all the files
  356. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, ""))
  357. if len(vals) != 4 {
  358. t.Log(vals)
  359. t.Error("expected four items")
  360. }
  361. })
  362. t.Run("AllLocalSequenced", func(t *testing.T) {
  363. t.Parallel()
  364. vals := mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesBySequence(folderID, protocol.LocalDeviceID, 3, 0))
  365. // Vals should be test2/a, test2/b
  366. if len(vals) != 2 {
  367. t.Log(vals)
  368. t.Error("expected three items")
  369. } else if vals[0].Name != filepath.FromSlash("test2/a") || vals[0].Sequence != 3 {
  370. t.Error(vals)
  371. }
  372. })
  373. }
  374. func TestPrefixGlobbing(t *testing.T) {
  375. t.Parallel()
  376. sdb, err := Open(t.TempDir())
  377. if err != nil {
  378. t.Fatal(err)
  379. }
  380. t.Cleanup(func() {
  381. if err := sdb.Close(); err != nil {
  382. t.Fatal(err)
  383. }
  384. })
  385. // Some local files
  386. local := []protocol.FileInfo{
  387. genFile("test1", 1, 0),
  388. genDir("test2", 0),
  389. genFile("test2/a", 2, 0),
  390. genDir("test2/b", 0),
  391. genFile("test2/b/c", 3, 0),
  392. }
  393. err = sdb.Update(folderID, protocol.LocalDeviceID, local)
  394. if err != nil {
  395. t.Fatal(err)
  396. }
  397. vals := mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "test2"))
  398. // Vals should be test2, test2/a, test2/b, test2/b/c
  399. if len(vals) != 4 {
  400. t.Log(vals)
  401. t.Error("expected four items")
  402. } else if vals[0].Name != "test2" || vals[3].Name != filepath.FromSlash("test2/b/c") {
  403. t.Error(vals)
  404. }
  405. // Empty prefix should be all the files
  406. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, ""))
  407. if len(vals) != 5 {
  408. t.Log(vals)
  409. t.Error("expected five items")
  410. }
  411. // Same as partial prefix
  412. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "tes"))
  413. if len(vals) != 5 {
  414. t.Log(vals)
  415. t.Error("expected five items")
  416. }
  417. // Prefix should be case sensitive, so no match here
  418. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "tEsT2"))
  419. if len(vals) != 0 {
  420. t.Log(vals)
  421. t.Error("expected no items")
  422. }
  423. // Subdir should match
  424. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "test2/b"))
  425. if len(vals) != 2 {
  426. t.Log(vals)
  427. t.Error("expected two items")
  428. }
  429. }
  430. func TestPrefixGlobbingStar(t *testing.T) {
  431. t.Parallel()
  432. sdb, err := Open(t.TempDir())
  433. if err != nil {
  434. t.Fatal(err)
  435. }
  436. t.Cleanup(func() {
  437. if err := sdb.Close(); err != nil {
  438. t.Fatal(err)
  439. }
  440. })
  441. // Some local files
  442. local := []protocol.FileInfo{
  443. genFile("test1a", 1, 0),
  444. genFile("test*a", 2, 0),
  445. genFile("test2a", 3, 0),
  446. }
  447. err = sdb.Update(folderID, protocol.LocalDeviceID, local)
  448. if err != nil {
  449. t.Fatal(err)
  450. }
  451. vals := mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "test*a"))
  452. // Vals should be test*a
  453. if len(vals) != 1 {
  454. t.Log(vals)
  455. t.Error("expected one item")
  456. } else if vals[0].Name != "test*a" {
  457. t.Error(vals)
  458. }
  459. }
  460. func TestAvailability(t *testing.T) {
  461. db, err := Open(t.TempDir())
  462. if err != nil {
  463. t.Fatal(err)
  464. }
  465. const folderID = "test"
  466. // Some local files
  467. err = db.Update(folderID, protocol.LocalDeviceID, []protocol.FileInfo{
  468. genFile("test1", 1, 0),
  469. genFile("test2", 2, 0),
  470. })
  471. if err != nil {
  472. t.Fatal(err)
  473. }
  474. // Some remote files
  475. err = db.Update(folderID, protocol.DeviceID{42}, []protocol.FileInfo{
  476. genFile("test2", 2, 1),
  477. genFile("test3", 3, 2),
  478. })
  479. if err != nil {
  480. t.Fatal(err)
  481. }
  482. // Further remote files
  483. err = db.Update(folderID, protocol.DeviceID{45}, []protocol.FileInfo{
  484. genFile("test3", 3, 1),
  485. genFile("test4", 4, 2),
  486. })
  487. if err != nil {
  488. t.Fatal(err)
  489. }
  490. a, err := db.GetGlobalAvailability(folderID, "test1")
  491. if err != nil {
  492. t.Fatal(err)
  493. }
  494. if len(a) != 0 {
  495. t.Log(a)
  496. t.Error("expected no availability (only local)")
  497. }
  498. a, err = db.GetGlobalAvailability(folderID, "test2")
  499. if err != nil {
  500. t.Fatal(err)
  501. }
  502. if len(a) != 1 || a[0] != (protocol.DeviceID{42}) {
  503. t.Log(a)
  504. t.Error("expected one availability (only 42)")
  505. }
  506. a, err = db.GetGlobalAvailability(folderID, "test3")
  507. if err != nil {
  508. t.Fatal(err)
  509. }
  510. if len(a) != 2 || a[0] != (protocol.DeviceID{42}) || a[1] != (protocol.DeviceID{45}) {
  511. t.Log(a)
  512. t.Error("expected two availabilities (both remotes)")
  513. }
  514. if err := db.Close(); err != nil {
  515. t.Fatal(err)
  516. }
  517. }
  518. func TestDropFilesNamed(t *testing.T) {
  519. db, err := Open(t.TempDir())
  520. if err != nil {
  521. t.Fatal(err)
  522. }
  523. t.Cleanup(func() {
  524. if err := db.Close(); err != nil {
  525. t.Fatal(err)
  526. }
  527. })
  528. const folderID = "test"
  529. // Some local files
  530. err = db.Update(folderID, protocol.LocalDeviceID, []protocol.FileInfo{
  531. genFile("test1", 1, 0),
  532. genFile("test2", 2, 0),
  533. })
  534. if err != nil {
  535. t.Fatal(err)
  536. }
  537. // Drop test1
  538. if err := db.DropFilesNamed(folderID, protocol.LocalDeviceID, []string{"test1"}); err != nil {
  539. t.Fatal(err)
  540. }
  541. // Check
  542. if _, ok, err := db.GetDeviceFile(folderID, protocol.LocalDeviceID, "test1"); err != nil || ok {
  543. t.Log(err, ok)
  544. t.Error("expected to not exist")
  545. }
  546. if c, err := db.CountLocal(folderID, protocol.LocalDeviceID); err != nil {
  547. t.Fatal(err)
  548. } else if c.Files != 1 {
  549. t.Log(c)
  550. t.Error("expected count to be one")
  551. }
  552. if _, ok, err := db.GetDeviceFile(folderID, protocol.LocalDeviceID, "test2"); err != nil || !ok {
  553. t.Log(err, ok)
  554. t.Error("expected to exist")
  555. }
  556. }
  557. func TestDropFolder(t *testing.T) {
  558. db, err := Open(t.TempDir())
  559. if err != nil {
  560. t.Fatal(err)
  561. }
  562. t.Cleanup(func() {
  563. if err := db.Close(); err != nil {
  564. t.Fatal(err)
  565. }
  566. })
  567. // Some local files
  568. // Folder A
  569. err = db.Update("a", protocol.LocalDeviceID, []protocol.FileInfo{
  570. genFile("test1", 1, 0),
  571. genFile("test2", 2, 0),
  572. })
  573. if err != nil {
  574. t.Fatal(err)
  575. }
  576. // Folder B
  577. err = db.Update("b", protocol.LocalDeviceID, []protocol.FileInfo{
  578. genFile("test1", 1, 0),
  579. genFile("test2", 2, 0),
  580. })
  581. if err != nil {
  582. t.Fatal(err)
  583. }
  584. // Drop A
  585. if err := db.DropFolder("a"); err != nil {
  586. t.Fatal(err)
  587. }
  588. // Check
  589. if _, ok, err := db.GetDeviceFile("a", protocol.LocalDeviceID, "test1"); err != nil || ok {
  590. t.Log(err, ok)
  591. t.Error("expected to not exist")
  592. }
  593. if c, err := db.CountLocal("a", protocol.LocalDeviceID); err != nil {
  594. t.Fatal(err)
  595. } else if c.Files != 0 {
  596. t.Log(c)
  597. t.Error("expected count to be zero")
  598. }
  599. if _, ok, err := db.GetDeviceFile("b", protocol.LocalDeviceID, "test1"); err != nil || !ok {
  600. t.Log(err, ok)
  601. t.Error("expected to exist")
  602. }
  603. if c, err := db.CountLocal("b", protocol.LocalDeviceID); err != nil {
  604. t.Fatal(err)
  605. } else if c.Files != 2 {
  606. t.Log(c)
  607. t.Error("expected count to be two")
  608. }
  609. }
  610. func TestDropDevice(t *testing.T) {
  611. db, err := Open(t.TempDir())
  612. if err != nil {
  613. t.Fatal(err)
  614. }
  615. t.Cleanup(func() {
  616. if err := db.Close(); err != nil {
  617. t.Fatal(err)
  618. }
  619. })
  620. // Some local files
  621. // Device 1
  622. err = db.Update("a", protocol.DeviceID{1}, []protocol.FileInfo{
  623. genFile("test1", 1, 1),
  624. genFile("test2", 2, 2),
  625. })
  626. if err != nil {
  627. t.Fatal(err)
  628. }
  629. // Device 2
  630. err = db.Update("a", protocol.DeviceID{2}, []protocol.FileInfo{
  631. genFile("test1", 1, 1),
  632. genFile("test2", 2, 2),
  633. })
  634. if err != nil {
  635. t.Fatal(err)
  636. }
  637. // Drop 1
  638. if err := db.DropDevice(protocol.DeviceID{1}); err != nil {
  639. t.Fatal(err)
  640. }
  641. // Check
  642. if _, ok, err := db.GetDeviceFile("a", protocol.DeviceID{1}, "test1"); err != nil || ok {
  643. t.Log(err, ok)
  644. t.Error("expected to not exist")
  645. }
  646. if c, err := db.CountLocal("a", protocol.DeviceID{1}); err != nil {
  647. t.Fatal(err)
  648. } else if c.Files != 0 {
  649. t.Log(c)
  650. t.Error("expected count to be zero")
  651. }
  652. if _, ok, err := db.GetDeviceFile("a", protocol.DeviceID{2}, "test1"); err != nil || !ok {
  653. t.Log(err, ok)
  654. t.Error("expected to exist")
  655. }
  656. if c, err := db.CountLocal("a", protocol.DeviceID{2}); err != nil {
  657. t.Fatal(err)
  658. } else if c.Files != 2 {
  659. t.Log(c)
  660. t.Error("expected count to be two")
  661. }
  662. // Drop something that doesn't exist
  663. if err := db.DropDevice(protocol.DeviceID{99}); err != nil {
  664. t.Fatal(err)
  665. }
  666. }
  667. func TestDropAllFiles(t *testing.T) {
  668. db, err := Open(t.TempDir())
  669. if err != nil {
  670. t.Fatal(err)
  671. }
  672. t.Cleanup(func() {
  673. if err := db.Close(); err != nil {
  674. t.Fatal(err)
  675. }
  676. })
  677. // Some local files
  678. // Device 1 folder A
  679. err = db.Update("a", protocol.DeviceID{1}, []protocol.FileInfo{
  680. genFile("test1", 1, 1),
  681. genFile("test2", 2, 2),
  682. })
  683. if err != nil {
  684. t.Fatal(err)
  685. }
  686. // Device 1 folder B
  687. err = db.Update("b", protocol.DeviceID{1}, []protocol.FileInfo{
  688. genFile("test1", 1, 1),
  689. genFile("test2", 2, 2),
  690. })
  691. if err != nil {
  692. t.Fatal(err)
  693. }
  694. // Drop folder A
  695. if err := db.DropAllFiles("a", protocol.DeviceID{1}); err != nil {
  696. t.Fatal(err)
  697. }
  698. // Check
  699. if _, ok, err := db.GetDeviceFile("a", protocol.DeviceID{1}, "test1"); err != nil || ok {
  700. t.Log(err, ok)
  701. t.Error("expected to not exist")
  702. }
  703. if c, err := db.CountLocal("a", protocol.DeviceID{1}); err != nil {
  704. t.Fatal(err)
  705. } else if c.Files != 0 {
  706. t.Log(c)
  707. t.Error("expected count to be zero")
  708. }
  709. if _, ok, err := db.GetDeviceFile("b", protocol.DeviceID{1}, "test1"); err != nil || !ok {
  710. t.Log(err, ok)
  711. t.Error("expected to exist")
  712. }
  713. if c, err := db.CountLocal("b", protocol.DeviceID{1}); err != nil {
  714. t.Fatal(err)
  715. } else if c.Files != 2 {
  716. t.Log(c)
  717. t.Error("expected count to be two")
  718. }
  719. // Drop things that don't exist
  720. if err := db.DropAllFiles("a", protocol.DeviceID{99}); err != nil {
  721. t.Fatal(err)
  722. }
  723. if err := db.DropAllFiles("trolol", protocol.DeviceID{1}); err != nil {
  724. t.Fatal(err)
  725. }
  726. if err := db.DropAllFiles("trolol", protocol.DeviceID{99}); err != nil {
  727. t.Fatal(err)
  728. }
  729. }
  730. func TestConcurrentUpdate(t *testing.T) {
  731. t.Parallel()
  732. db, err := Open(filepath.Join(t.TempDir(), "db"))
  733. if err != nil {
  734. t.Fatal(err)
  735. }
  736. t.Cleanup(func() {
  737. if err := db.Close(); err != nil {
  738. t.Fatal(err)
  739. }
  740. })
  741. const folderID = "test"
  742. files := []protocol.FileInfo{
  743. genFile("test1", 1, 1),
  744. genFile("test2", 2, 2),
  745. genFile("test3", 3, 3),
  746. genFile("test4", 4, 4),
  747. }
  748. const n = 32
  749. res := make([]error, n)
  750. var wg sync.WaitGroup
  751. wg.Add(n)
  752. for i := range n {
  753. go func() {
  754. res[i] = db.Update(folderID, protocol.DeviceID{byte(i), byte(i), byte(i)}, files)
  755. wg.Done()
  756. }()
  757. }
  758. wg.Wait()
  759. for i, err := range res {
  760. if err != nil {
  761. t.Errorf("%d: %v", i, err)
  762. }
  763. }
  764. }
  765. func TestConcurrentUpdateSelect(t *testing.T) {
  766. t.Parallel()
  767. db, err := Open(filepath.Join(t.TempDir(), "db"))
  768. if err != nil {
  769. t.Fatal(err)
  770. }
  771. t.Cleanup(func() {
  772. if err := db.Close(); err != nil {
  773. t.Fatal(err)
  774. }
  775. })
  776. const folderID = "test"
  777. // Some local files
  778. files := []protocol.FileInfo{
  779. genFile("test1", 1, 1),
  780. genFile("test2", 2, 2),
  781. genFile("test3", 3, 3),
  782. genFile("test4", 4, 4),
  783. }
  784. // Insert the files for a remote device
  785. if err := db.Update(folderID, protocol.DeviceID{42}, files); err != nil {
  786. t.Fatal()
  787. }
  788. // Iterate over handled files and insert them for the local device.
  789. // This is similar to a pattern we have in other places and should
  790. // work.
  791. handled := 0
  792. it, errFn := db.AllNeededGlobalFiles(folderID, protocol.LocalDeviceID, config.PullOrderAlphabetic, 0, 0)
  793. for glob := range it {
  794. glob.Version = glob.Version.Update(1)
  795. if err := db.Update(folderID, protocol.LocalDeviceID, []protocol.FileInfo{glob}); err != nil {
  796. t.Fatal(err)
  797. }
  798. handled++
  799. }
  800. if err := errFn(); err != nil {
  801. t.Fatal(err)
  802. }
  803. if handled != len(files) {
  804. t.Log(handled)
  805. t.Error("should have handled all the files")
  806. }
  807. }
  808. func TestAllForBlocksHash(t *testing.T) {
  809. t.Parallel()
  810. sdb, err := Open(t.TempDir())
  811. if err != nil {
  812. t.Fatal(err)
  813. }
  814. t.Cleanup(func() {
  815. if err := sdb.Close(); err != nil {
  816. t.Fatal(err)
  817. }
  818. })
  819. // test1 is unique, while test2 and test3 have the same blocks and hence
  820. // the same blocks hash
  821. files := []protocol.FileInfo{
  822. genFile("test1", 1, 1),
  823. genFile("test2", 2, 2),
  824. genFile("test3", 3, 3),
  825. }
  826. files[2].Blocks = files[1].Blocks
  827. if err := sdb.Update(folderID, protocol.LocalDeviceID, files); err != nil {
  828. t.Fatal(err)
  829. }
  830. // Check test1
  831. test1, ok, err := sdb.GetDeviceFile(folderID, protocol.LocalDeviceID, "test1")
  832. if err != nil || !ok {
  833. t.Fatal("expected to exist")
  834. }
  835. vals := mustCollect[db.FileMetadata](t)(sdb.AllLocalFilesWithBlocksHash(folderID, test1.BlocksHash))
  836. if len(vals) != 1 {
  837. t.Log(vals)
  838. t.Fatal("expected one file to match")
  839. }
  840. // Check test2 which also matches test3
  841. test2, ok, err := sdb.GetDeviceFile(folderID, protocol.LocalDeviceID, "test2")
  842. if err != nil || !ok {
  843. t.Fatal("expected to exist")
  844. }
  845. vals = mustCollect[db.FileMetadata](t)(sdb.AllLocalFilesWithBlocksHash(folderID, test2.BlocksHash))
  846. if len(vals) != 2 {
  847. t.Log(vals)
  848. t.Fatal("expected two files to match")
  849. }
  850. if vals[0].Name != "test2" {
  851. t.Log(vals[0])
  852. t.Error("expected test2")
  853. }
  854. if vals[1].Name != "test3" {
  855. t.Log(vals[1])
  856. t.Error("expected test3")
  857. }
  858. }
  859. func TestBlocklistGarbageCollection(t *testing.T) {
  860. t.Parallel()
  861. sdb, err := Open(t.TempDir())
  862. if err != nil {
  863. t.Fatal(err)
  864. }
  865. t.Cleanup(func() {
  866. if err := sdb.Close(); err != nil {
  867. t.Fatal(err)
  868. }
  869. })
  870. svc := sdb.Service(time.Hour).(*Service)
  871. // Add three files
  872. files := []protocol.FileInfo{
  873. genFile("test1", 1, 1),
  874. genFile("test2", 2, 2),
  875. genFile("test3", 3, 3),
  876. }
  877. if err := sdb.Update(folderID, protocol.LocalDeviceID, files); err != nil {
  878. t.Fatal(err)
  879. }
  880. // There should exist three blockslists and six blocks
  881. fdb, err := sdb.getFolderDB(folderID, false)
  882. if err != nil {
  883. t.Fatal(err)
  884. }
  885. var count int
  886. if err := fdb.sql.Get(&count, `SELECT count(*) FROM blocklists`); err != nil {
  887. t.Fatal(err)
  888. }
  889. if count != 3 {
  890. t.Log(count)
  891. t.Fatal("expected 3 blocklists")
  892. }
  893. if err := fdb.sql.Get(&count, `SELECT count(*) FROM blocks`); err != nil {
  894. t.Fatal(err)
  895. }
  896. if count != 6 {
  897. t.Log(count)
  898. t.Fatal("expected 6 blocks")
  899. }
  900. // Mark test3 as deleted, it's blocks and blocklist are now eligible for collection
  901. files = files[2:]
  902. files[0].SetDeleted(42)
  903. if err := sdb.Update(folderID, protocol.LocalDeviceID, files); err != nil {
  904. t.Fatal(err)
  905. }
  906. // Run garbage collection
  907. if err := svc.periodic(context.Background()); err != nil {
  908. t.Fatal(err)
  909. }
  910. // There should exist two blockslists and four blocks
  911. if err := fdb.sql.Get(&count, `SELECT count(*) FROM blocklists`); err != nil {
  912. t.Fatal(err)
  913. }
  914. if count != 2 {
  915. t.Log(count)
  916. t.Error("expected 2 blocklists")
  917. }
  918. if err := fdb.sql.Get(&count, `SELECT count(*) FROM blocks`); err != nil {
  919. t.Fatal(err)
  920. }
  921. if count != 3 {
  922. t.Log(count)
  923. t.Error("expected 3 blocks")
  924. }
  925. }
  926. func TestInsertLargeFile(t *testing.T) {
  927. t.Parallel()
  928. sdb, err := Open(t.TempDir())
  929. if err != nil {
  930. t.Fatal(err)
  931. }
  932. t.Cleanup(func() {
  933. if err := sdb.Close(); err != nil {
  934. t.Fatal(err)
  935. }
  936. })
  937. // Add a large file (many blocks)
  938. files := []protocol.FileInfo{genFile("test1", 16000, 1)}
  939. if err := sdb.Update(folderID, protocol.LocalDeviceID, files); err != nil {
  940. t.Fatal(err)
  941. }
  942. // Verify all the blocks are here
  943. for i, block := range files[0].Blocks {
  944. bs, err := itererr.Collect(sdb.AllLocalBlocksWithHash(folderID, block.Hash))
  945. if err != nil {
  946. t.Fatal(err)
  947. }
  948. if len(bs) == 0 {
  949. t.Error("missing blocks for", i)
  950. }
  951. }
  952. }
  953. func TestErrorWrap(t *testing.T) {
  954. if wrap(nil, "foo") != nil {
  955. t.Fatal("nil should wrap to nil")
  956. }
  957. fooErr := errors.New("foo")
  958. if err := wrap(fooErr); err.Error() != "testerrorwrap: foo" {
  959. t.Fatalf("%q", err)
  960. }
  961. if err := wrap(fooErr, "bar", "baz"); err.Error() != "testerrorwrap (bar, baz): foo" {
  962. t.Fatalf("%q", err)
  963. }
  964. }
  965. func TestStrangeDeletedGlobalBug(t *testing.T) {
  966. // This exercises an edge case with serialisation and ordering of
  967. // version vectors. It does not need to make sense, it just needs to
  968. // pass.
  969. t.Parallel()
  970. sdb, err := Open(t.TempDir())
  971. if err != nil {
  972. t.Fatal(err)
  973. }
  974. t.Cleanup(func() {
  975. if err := sdb.Close(); err != nil {
  976. t.Fatal(err)
  977. }
  978. })
  979. // One remote device announces the original version of the file
  980. file := genFile("test", 1, 1)
  981. file.Version = protocol.Vector{Counters: []protocol.Counter{{ID: 35494436325452, Value: 1742900373}}}
  982. t.Log("orig", file.Version)
  983. sdb.Update(folderID, protocol.DeviceID{42}, []protocol.FileInfo{file})
  984. // Another one announces a newer one that is deleted
  985. del := file
  986. del.SetDeleted(43)
  987. del.Version = protocol.Vector{Counters: []protocol.Counter{{ID: 55445057455644, Value: 1742918457}, {ID: 35494436325452, Value: 1742900373}}}
  988. t.Log("del", del.Version)
  989. sdb.Update(folderID, protocol.DeviceID{43}, []protocol.FileInfo{del})
  990. // We have an instance of the original file
  991. sdb.Update(folderID, protocol.LocalDeviceID, []protocol.FileInfo{file})
  992. // Which one is the global? It should be the deleted one, clearly.
  993. g, _, err := sdb.GetGlobalFile(folderID, "test")
  994. if err != nil {
  995. t.Fatal(err)
  996. }
  997. if !g.Deleted {
  998. t.Log(g)
  999. t.Fatal("should be deleted")
  1000. }
  1001. }
  1002. func TestOpenSpecialName(t *testing.T) {
  1003. dir := t.TempDir()
  1004. // Create a "base" dir that is in the way if the path becomes
  1005. // incorrectly truncated in the next steps.
  1006. base := path.Join(dir, "test")
  1007. if err := os.Mkdir(base, 0o755); err != nil {
  1008. t.Fatal(err)
  1009. }
  1010. // Should be able to open a path with a hash sign in it.
  1011. p1 := base + "#foo"
  1012. db, err := Open(p1)
  1013. if err != nil {
  1014. t.Fatal(err)
  1015. }
  1016. t.Log(db.path)
  1017. db.Close()
  1018. if !build.IsWindows {
  1019. // Should be able to open a path with something that looks like
  1020. // query params.
  1021. p2 := base + "?foo=bar"
  1022. db, err = Open(p2)
  1023. if err != nil {
  1024. t.Fatal(err)
  1025. }
  1026. t.Log(db.path)
  1027. db.Close()
  1028. }
  1029. // Better not a have problem with a single ampersand either.
  1030. p2 := base + "&foo"
  1031. db, err = Open(p2)
  1032. if err != nil {
  1033. t.Fatal(err)
  1034. }
  1035. t.Log(db.path)
  1036. db.Close()
  1037. }
  1038. func mustCollect[T any](t *testing.T) func(it iter.Seq[T], errFn func() error) []T {
  1039. t.Helper()
  1040. return func(it iter.Seq[T], errFn func() error) []T {
  1041. t.Helper()
  1042. vals, err := itererr.Collect(it, errFn)
  1043. if err != nil {
  1044. t.Fatal(err)
  1045. }
  1046. return vals
  1047. }
  1048. }
  1049. func fiNames(fs []protocol.FileInfo) []string {
  1050. names := make([]string, len(fs))
  1051. for i, fi := range fs {
  1052. names[i] = fi.Name
  1053. }
  1054. return names
  1055. }
  1056. func genDir(name string, seq int) protocol.FileInfo {
  1057. return protocol.FileInfo{
  1058. Name: name,
  1059. Type: protocol.FileInfoTypeDirectory,
  1060. ModifiedS: time.Now().Unix(),
  1061. ModifiedBy: 1,
  1062. Sequence: int64(seq),
  1063. Version: protocol.Vector{}.Update(1),
  1064. Permissions: 0o755,
  1065. ModifiedNs: 12345678,
  1066. }
  1067. }
  1068. func genFile(name string, numBlocks int, seq int) protocol.FileInfo {
  1069. ts := timeutil.StrictlyMonotonicNanos()
  1070. s := ts / 1e9
  1071. ns := int32(ts % 1e9)
  1072. return protocol.FileInfo{
  1073. Name: name,
  1074. Size: int64(numBlocks) * blockSize,
  1075. ModifiedS: s,
  1076. ModifiedBy: 1,
  1077. Version: protocol.Vector{}.Update(1),
  1078. Sequence: int64(seq),
  1079. Blocks: genBlocks(name, 0, numBlocks),
  1080. Permissions: 0o644,
  1081. ModifiedNs: ns,
  1082. RawBlockSize: blockSize,
  1083. }
  1084. }
  1085. func genBlocks(name string, seed, count int) []protocol.BlockInfo {
  1086. b := make([]protocol.BlockInfo, count)
  1087. for i := range b {
  1088. b[i].Hash = genBlockHash(name, seed, i)
  1089. b[i].Size = blockSize
  1090. b[i].Offset = (blockSize) * int64(i)
  1091. }
  1092. return b
  1093. }
  1094. func genBlockHash(name string, seed, index int) []byte {
  1095. bs := sha256.Sum256([]byte(name))
  1096. ebs := binary.LittleEndian.AppendUint64(nil, uint64(seed))
  1097. for i := range ebs {
  1098. bs[i] ^= ebs[i]
  1099. }
  1100. ebs = binary.LittleEndian.AppendUint64(nil, uint64(index))
  1101. for i := range ebs {
  1102. bs[i] ^= ebs[i]
  1103. }
  1104. return bs[:]
  1105. }