db_test.go 26 KB

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