db_test.go 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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.Log(folders)
  269. t.Error("expected one folder")
  270. }
  271. })
  272. t.Run("DevicesForFolder", func(t *testing.T) {
  273. t.Parallel()
  274. devs, err := sdb.ListDevicesForFolder("test")
  275. if err != nil {
  276. t.Fatal(err)
  277. }
  278. if len(devs) != 1 || devs[0] != (protocol.DeviceID{42}) {
  279. t.Log(devs)
  280. t.Error("expected one device")
  281. }
  282. })
  283. t.Run("Sequence", func(t *testing.T) {
  284. t.Parallel()
  285. iid, err := sdb.GetIndexID(folderID, protocol.LocalDeviceID)
  286. if err != nil {
  287. t.Fatal(err)
  288. }
  289. if iid == 0 {
  290. t.Log(iid)
  291. t.Fatal("expected index ID")
  292. }
  293. if seq, err := sdb.GetDeviceSequence(folderID, protocol.LocalDeviceID); err != nil {
  294. t.Fatal(err)
  295. } else if seq != 4 {
  296. t.Log(seq)
  297. t.Error("expected local sequence to match number of files inserted")
  298. }
  299. if seq, err := sdb.GetDeviceSequence(folderID, protocol.DeviceID{42}); err != nil {
  300. t.Fatal(err)
  301. } else if seq != 103 {
  302. t.Log(seq)
  303. t.Error("expected remote sequence to match highest sent")
  304. }
  305. // Non-existent should be zero and no error
  306. if seq, err := sdb.GetDeviceSequence("trolol", protocol.LocalDeviceID); err != nil {
  307. t.Fatal(err)
  308. } else if seq != 0 {
  309. t.Log(seq)
  310. t.Error("expected zero sequence")
  311. }
  312. if seq, err := sdb.GetDeviceSequence("trolol", protocol.DeviceID{42}); err != nil {
  313. t.Fatal(err)
  314. } else if seq != 0 {
  315. t.Log(seq)
  316. t.Error("expected zero sequence")
  317. }
  318. if seq, err := sdb.GetDeviceSequence(folderID, protocol.DeviceID{99}); err != nil {
  319. t.Fatal(err)
  320. } else if seq != 0 {
  321. t.Log(seq)
  322. t.Error("expected zero sequence")
  323. }
  324. })
  325. t.Run("AllGlobalPrefix", func(t *testing.T) {
  326. t.Parallel()
  327. vals := mustCollect[db.FileMetadata](t)(sdb.AllGlobalFilesPrefix(folderID, "test2"))
  328. // Vals should be test2, test2/a, test2/b
  329. if len(vals) != 3 {
  330. t.Log(vals)
  331. t.Error("expected three items")
  332. } else if vals[0].Name != "test2" {
  333. t.Error(vals)
  334. }
  335. // Empty prefix should be all the files
  336. vals = mustCollect[db.FileMetadata](t)(sdb.AllGlobalFilesPrefix(folderID, ""))
  337. if len(vals) != 6 {
  338. t.Log(vals)
  339. t.Error("expected six items")
  340. }
  341. })
  342. t.Run("AllLocalPrefix", func(t *testing.T) {
  343. t.Parallel()
  344. vals := mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "test2"))
  345. // Vals should be test2, test2/a, test2/b
  346. if len(vals) != 3 {
  347. t.Log(vals)
  348. t.Error("expected three items")
  349. } else if vals[0].Name != "test2" {
  350. t.Error(vals)
  351. }
  352. // Empty prefix should be all the files
  353. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, ""))
  354. if len(vals) != 4 {
  355. t.Log(vals)
  356. t.Error("expected four items")
  357. }
  358. })
  359. t.Run("AllLocalSequenced", func(t *testing.T) {
  360. t.Parallel()
  361. vals := mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesBySequence(folderID, protocol.LocalDeviceID, 3, 0))
  362. // Vals should be test2/a, test2/b
  363. if len(vals) != 2 {
  364. t.Log(vals)
  365. t.Error("expected three items")
  366. } else if vals[0].Name != filepath.FromSlash("test2/a") || vals[0].Sequence != 3 {
  367. t.Error(vals)
  368. }
  369. })
  370. }
  371. func TestPrefixGlobbing(t *testing.T) {
  372. t.Parallel()
  373. sdb, err := OpenTemp()
  374. if err != nil {
  375. t.Fatal(err)
  376. }
  377. t.Cleanup(func() {
  378. if err := sdb.Close(); err != nil {
  379. t.Fatal(err)
  380. }
  381. })
  382. // Some local files
  383. local := []protocol.FileInfo{
  384. genFile("test1", 1, 0),
  385. genDir("test2", 0),
  386. genFile("test2/a", 2, 0),
  387. genDir("test2/b", 0),
  388. genFile("test2/b/c", 3, 0),
  389. }
  390. err = sdb.Update(folderID, protocol.LocalDeviceID, local)
  391. if err != nil {
  392. t.Fatal(err)
  393. }
  394. vals := mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "test2"))
  395. // Vals should be test2, test2/a, test2/b, test2/b/c
  396. if len(vals) != 4 {
  397. t.Log(vals)
  398. t.Error("expected four items")
  399. } else if vals[0].Name != "test2" || vals[3].Name != filepath.FromSlash("test2/b/c") {
  400. t.Error(vals)
  401. }
  402. // Empty prefix should be all the files
  403. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, ""))
  404. if len(vals) != 5 {
  405. t.Log(vals)
  406. t.Error("expected five items")
  407. }
  408. // Same as partial prefix
  409. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "tes"))
  410. if len(vals) != 5 {
  411. t.Log(vals)
  412. t.Error("expected five items")
  413. }
  414. // Prefix should be case sensitive, so no match here
  415. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "tEsT2"))
  416. if len(vals) != 0 {
  417. t.Log(vals)
  418. t.Error("expected no items")
  419. }
  420. // Subdir should match
  421. vals = mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "test2/b"))
  422. if len(vals) != 2 {
  423. t.Log(vals)
  424. t.Error("expected two items")
  425. }
  426. }
  427. func TestPrefixGlobbingStar(t *testing.T) {
  428. t.Parallel()
  429. sdb, err := OpenTemp()
  430. if err != nil {
  431. t.Fatal(err)
  432. }
  433. t.Cleanup(func() {
  434. if err := sdb.Close(); err != nil {
  435. t.Fatal(err)
  436. }
  437. })
  438. // Some local files
  439. local := []protocol.FileInfo{
  440. genFile("test1a", 1, 0),
  441. genFile("test*a", 2, 0),
  442. genFile("test2a", 3, 0),
  443. }
  444. err = sdb.Update(folderID, protocol.LocalDeviceID, local)
  445. if err != nil {
  446. t.Fatal(err)
  447. }
  448. vals := mustCollect[protocol.FileInfo](t)(sdb.AllLocalFilesWithPrefix(folderID, protocol.LocalDeviceID, "test*a"))
  449. // Vals should be test*a
  450. if len(vals) != 1 {
  451. t.Log(vals)
  452. t.Error("expected one item")
  453. } else if vals[0].Name != "test*a" {
  454. t.Error(vals)
  455. }
  456. }
  457. func TestAvailability(t *testing.T) {
  458. db, err := OpenTemp()
  459. if err != nil {
  460. t.Fatal(err)
  461. }
  462. const folderID = "test"
  463. // Some local files
  464. err = db.Update(folderID, protocol.LocalDeviceID, []protocol.FileInfo{
  465. genFile("test1", 1, 0),
  466. genFile("test2", 2, 0),
  467. })
  468. if err != nil {
  469. t.Fatal(err)
  470. }
  471. // Some remote files
  472. err = db.Update(folderID, protocol.DeviceID{42}, []protocol.FileInfo{
  473. genFile("test2", 2, 1),
  474. genFile("test3", 3, 2),
  475. })
  476. if err != nil {
  477. t.Fatal(err)
  478. }
  479. // Further remote files
  480. err = db.Update(folderID, protocol.DeviceID{45}, []protocol.FileInfo{
  481. genFile("test3", 3, 1),
  482. genFile("test4", 4, 2),
  483. })
  484. if err != nil {
  485. t.Fatal(err)
  486. }
  487. a, err := db.GetGlobalAvailability(folderID, "test1")
  488. if err != nil {
  489. t.Fatal(err)
  490. }
  491. if len(a) != 0 {
  492. t.Log(a)
  493. t.Error("expected no availability (only local)")
  494. }
  495. a, err = db.GetGlobalAvailability(folderID, "test2")
  496. if err != nil {
  497. t.Fatal(err)
  498. }
  499. if len(a) != 1 || a[0] != (protocol.DeviceID{42}) {
  500. t.Log(a)
  501. t.Error("expected one availability (only 42)")
  502. }
  503. a, err = db.GetGlobalAvailability(folderID, "test3")
  504. if err != nil {
  505. t.Fatal(err)
  506. }
  507. if len(a) != 2 || a[0] != (protocol.DeviceID{42}) || a[1] != (protocol.DeviceID{45}) {
  508. t.Log(a)
  509. t.Error("expected two availabilities (both remotes)")
  510. }
  511. if err := db.Close(); err != nil {
  512. t.Fatal(err)
  513. }
  514. }
  515. func TestDropFilesNamed(t *testing.T) {
  516. db, err := OpenTemp()
  517. if err != nil {
  518. t.Fatal(err)
  519. }
  520. t.Cleanup(func() {
  521. if err := db.Close(); err != nil {
  522. t.Fatal(err)
  523. }
  524. })
  525. const folderID = "test"
  526. // Some local files
  527. err = db.Update(folderID, protocol.LocalDeviceID, []protocol.FileInfo{
  528. genFile("test1", 1, 0),
  529. genFile("test2", 2, 0),
  530. })
  531. if err != nil {
  532. t.Fatal(err)
  533. }
  534. // Drop test1
  535. if err := db.DropFilesNamed(folderID, protocol.LocalDeviceID, []string{"test1"}); err != nil {
  536. t.Fatal(err)
  537. }
  538. // Check
  539. if _, ok, err := db.GetDeviceFile(folderID, protocol.LocalDeviceID, "test1"); err != nil || ok {
  540. t.Log(err, ok)
  541. t.Error("expected to not exist")
  542. }
  543. if c, err := db.CountLocal(folderID, protocol.LocalDeviceID); err != nil {
  544. t.Fatal(err)
  545. } else if c.Files != 1 {
  546. t.Log(c)
  547. t.Error("expected count to be one")
  548. }
  549. if _, ok, err := db.GetDeviceFile(folderID, protocol.LocalDeviceID, "test2"); err != nil || !ok {
  550. t.Log(err, ok)
  551. t.Error("expected to exist")
  552. }
  553. }
  554. func TestDropFolder(t *testing.T) {
  555. db, err := OpenTemp()
  556. if err != nil {
  557. t.Fatal(err)
  558. }
  559. t.Cleanup(func() {
  560. if err := db.Close(); err != nil {
  561. t.Fatal(err)
  562. }
  563. })
  564. // Some local files
  565. // Folder A
  566. err = db.Update("a", protocol.LocalDeviceID, []protocol.FileInfo{
  567. genFile("test1", 1, 0),
  568. genFile("test2", 2, 0),
  569. })
  570. if err != nil {
  571. t.Fatal(err)
  572. }
  573. // Folder B
  574. err = db.Update("b", protocol.LocalDeviceID, []protocol.FileInfo{
  575. genFile("test1", 1, 0),
  576. genFile("test2", 2, 0),
  577. })
  578. if err != nil {
  579. t.Fatal(err)
  580. }
  581. // Drop A
  582. if err := db.DropFolder("a"); err != nil {
  583. t.Fatal(err)
  584. }
  585. // Check
  586. if _, ok, err := db.GetDeviceFile("a", protocol.LocalDeviceID, "test1"); err != nil || ok {
  587. t.Log(err, ok)
  588. t.Error("expected to not exist")
  589. }
  590. if c, err := db.CountLocal("a", protocol.LocalDeviceID); err != nil {
  591. t.Fatal(err)
  592. } else if c.Files != 0 {
  593. t.Log(c)
  594. t.Error("expected count to be zero")
  595. }
  596. if _, ok, err := db.GetDeviceFile("b", protocol.LocalDeviceID, "test1"); err != nil || !ok {
  597. t.Log(err, ok)
  598. t.Error("expected to exist")
  599. }
  600. if c, err := db.CountLocal("b", protocol.LocalDeviceID); err != nil {
  601. t.Fatal(err)
  602. } else if c.Files != 2 {
  603. t.Log(c)
  604. t.Error("expected count to be two")
  605. }
  606. }
  607. func TestDropDevice(t *testing.T) {
  608. db, err := OpenTemp()
  609. if err != nil {
  610. t.Fatal(err)
  611. }
  612. t.Cleanup(func() {
  613. if err := db.Close(); err != nil {
  614. t.Fatal(err)
  615. }
  616. })
  617. // Some local files
  618. // Device 1
  619. err = db.Update("a", protocol.DeviceID{1}, []protocol.FileInfo{
  620. genFile("test1", 1, 1),
  621. genFile("test2", 2, 2),
  622. })
  623. if err != nil {
  624. t.Fatal(err)
  625. }
  626. // Device 2
  627. err = db.Update("a", protocol.DeviceID{2}, []protocol.FileInfo{
  628. genFile("test1", 1, 1),
  629. genFile("test2", 2, 2),
  630. })
  631. if err != nil {
  632. t.Fatal(err)
  633. }
  634. // Drop 1
  635. if err := db.DropDevice(protocol.DeviceID{1}); err != nil {
  636. t.Fatal(err)
  637. }
  638. // Check
  639. if _, ok, err := db.GetDeviceFile("a", protocol.DeviceID{1}, "test1"); err != nil || ok {
  640. t.Log(err, ok)
  641. t.Error("expected to not exist")
  642. }
  643. if c, err := db.CountLocal("a", protocol.DeviceID{1}); err != nil {
  644. t.Fatal(err)
  645. } else if c.Files != 0 {
  646. t.Log(c)
  647. t.Error("expected count to be zero")
  648. }
  649. if _, ok, err := db.GetDeviceFile("a", protocol.DeviceID{2}, "test1"); err != nil || !ok {
  650. t.Log(err, ok)
  651. t.Error("expected to exist")
  652. }
  653. if c, err := db.CountLocal("a", protocol.DeviceID{2}); err != nil {
  654. t.Fatal(err)
  655. } else if c.Files != 2 {
  656. t.Log(c)
  657. t.Error("expected count to be two")
  658. }
  659. // Drop something that doesn't exist
  660. if err := db.DropDevice(protocol.DeviceID{99}); err != nil {
  661. t.Fatal(err)
  662. }
  663. }
  664. func TestDropAllFiles(t *testing.T) {
  665. db, err := OpenTemp()
  666. if err != nil {
  667. t.Fatal(err)
  668. }
  669. t.Cleanup(func() {
  670. if err := db.Close(); err != nil {
  671. t.Fatal(err)
  672. }
  673. })
  674. // Some local files
  675. // Device 1 folder A
  676. err = db.Update("a", protocol.DeviceID{1}, []protocol.FileInfo{
  677. genFile("test1", 1, 1),
  678. genFile("test2", 2, 2),
  679. })
  680. if err != nil {
  681. t.Fatal(err)
  682. }
  683. // Device 1 folder B
  684. err = db.Update("b", protocol.DeviceID{1}, []protocol.FileInfo{
  685. genFile("test1", 1, 1),
  686. genFile("test2", 2, 2),
  687. })
  688. if err != nil {
  689. t.Fatal(err)
  690. }
  691. // Drop folder A
  692. if err := db.DropAllFiles("a", protocol.DeviceID{1}); err != nil {
  693. t.Fatal(err)
  694. }
  695. // Check
  696. if _, ok, err := db.GetDeviceFile("a", protocol.DeviceID{1}, "test1"); err != nil || ok {
  697. t.Log(err, ok)
  698. t.Error("expected to not exist")
  699. }
  700. if c, err := db.CountLocal("a", protocol.DeviceID{1}); err != nil {
  701. t.Fatal(err)
  702. } else if c.Files != 0 {
  703. t.Log(c)
  704. t.Error("expected count to be zero")
  705. }
  706. if _, ok, err := db.GetDeviceFile("b", protocol.DeviceID{1}, "test1"); err != nil || !ok {
  707. t.Log(err, ok)
  708. t.Error("expected to exist")
  709. }
  710. if c, err := db.CountLocal("b", protocol.DeviceID{1}); err != nil {
  711. t.Fatal(err)
  712. } else if c.Files != 2 {
  713. t.Log(c)
  714. t.Error("expected count to be two")
  715. }
  716. // Drop things that don't exist
  717. if err := db.DropAllFiles("a", protocol.DeviceID{99}); err != nil {
  718. t.Fatal(err)
  719. }
  720. if err := db.DropAllFiles("trolol", protocol.DeviceID{1}); err != nil {
  721. t.Fatal(err)
  722. }
  723. if err := db.DropAllFiles("trolol", protocol.DeviceID{99}); err != nil {
  724. t.Fatal(err)
  725. }
  726. }
  727. func TestConcurrentUpdate(t *testing.T) {
  728. t.Parallel()
  729. db, err := Open(filepath.Join(t.TempDir(), "db"))
  730. if err != nil {
  731. t.Fatal(err)
  732. }
  733. t.Cleanup(func() {
  734. if err := db.Close(); err != nil {
  735. t.Fatal(err)
  736. }
  737. })
  738. const folderID = "test"
  739. files := []protocol.FileInfo{
  740. genFile("test1", 1, 1),
  741. genFile("test2", 2, 2),
  742. genFile("test3", 3, 3),
  743. genFile("test4", 4, 4),
  744. }
  745. const n = 32
  746. res := make([]error, n)
  747. var wg sync.WaitGroup
  748. wg.Add(n)
  749. for i := range n {
  750. go func() {
  751. res[i] = db.Update(folderID, protocol.DeviceID{byte(i), byte(i), byte(i)}, files)
  752. wg.Done()
  753. }()
  754. }
  755. wg.Wait()
  756. for i, err := range res {
  757. if err != nil {
  758. t.Errorf("%d: %v", i, err)
  759. }
  760. }
  761. }
  762. func TestConcurrentUpdateSelect(t *testing.T) {
  763. t.Parallel()
  764. db, err := Open(filepath.Join(t.TempDir(), "db"))
  765. if err != nil {
  766. t.Fatal(err)
  767. }
  768. t.Cleanup(func() {
  769. if err := db.Close(); err != nil {
  770. t.Fatal(err)
  771. }
  772. })
  773. const folderID = "test"
  774. // Some local files
  775. files := []protocol.FileInfo{
  776. genFile("test1", 1, 1),
  777. genFile("test2", 2, 2),
  778. genFile("test3", 3, 3),
  779. genFile("test4", 4, 4),
  780. }
  781. // Insert the files for a remote device
  782. if err := db.Update(folderID, protocol.DeviceID{42}, files); err != nil {
  783. t.Fatal()
  784. }
  785. // Iterate over handled files and insert them for the local device.
  786. // This is similar to a pattern we have in other places and should
  787. // work.
  788. handled := 0
  789. it, errFn := db.AllNeededGlobalFiles(folderID, protocol.LocalDeviceID, config.PullOrderAlphabetic, 0, 0)
  790. for glob := range it {
  791. glob.Version = glob.Version.Update(1)
  792. if err := db.Update(folderID, protocol.LocalDeviceID, []protocol.FileInfo{glob}); err != nil {
  793. t.Fatal(err)
  794. }
  795. handled++
  796. }
  797. if err := errFn(); err != nil {
  798. t.Fatal(err)
  799. }
  800. if handled != len(files) {
  801. t.Log(handled)
  802. t.Error("should have handled all the files")
  803. }
  804. }
  805. func TestAllForBlocksHash(t *testing.T) {
  806. t.Parallel()
  807. sdb, err := OpenTemp()
  808. if err != nil {
  809. t.Fatal(err)
  810. }
  811. t.Cleanup(func() {
  812. if err := sdb.Close(); err != nil {
  813. t.Fatal(err)
  814. }
  815. })
  816. // test1 is unique, while test2 and test3 have the same blocks and hence
  817. // the same blocks hash
  818. files := []protocol.FileInfo{
  819. genFile("test1", 1, 1),
  820. genFile("test2", 2, 2),
  821. genFile("test3", 3, 3),
  822. }
  823. files[2].Blocks = files[1].Blocks
  824. if err := sdb.Update(folderID, protocol.LocalDeviceID, files); err != nil {
  825. t.Fatal(err)
  826. }
  827. // Check test1
  828. test1, ok, err := sdb.GetDeviceFile(folderID, protocol.LocalDeviceID, "test1")
  829. if err != nil || !ok {
  830. t.Fatal("expected to exist")
  831. }
  832. vals := mustCollect[db.FileMetadata](t)(sdb.AllLocalFilesWithBlocksHash(folderID, test1.BlocksHash))
  833. if len(vals) != 1 {
  834. t.Log(vals)
  835. t.Fatal("expected one file to match")
  836. }
  837. // Check test2 which also matches test3
  838. test2, ok, err := sdb.GetDeviceFile(folderID, protocol.LocalDeviceID, "test2")
  839. if err != nil || !ok {
  840. t.Fatal("expected to exist")
  841. }
  842. vals = mustCollect[db.FileMetadata](t)(sdb.AllLocalFilesWithBlocksHash(folderID, test2.BlocksHash))
  843. if len(vals) != 2 {
  844. t.Log(vals)
  845. t.Fatal("expected two files to match")
  846. }
  847. if vals[0].Name != "test2" {
  848. t.Log(vals[0])
  849. t.Error("expected test2")
  850. }
  851. if vals[1].Name != "test3" {
  852. t.Log(vals[1])
  853. t.Error("expected test3")
  854. }
  855. }
  856. func TestBlocklistGarbageCollection(t *testing.T) {
  857. t.Parallel()
  858. sdb, err := OpenTemp()
  859. if err != nil {
  860. t.Fatal(err)
  861. }
  862. t.Cleanup(func() {
  863. if err := sdb.Close(); err != nil {
  864. t.Fatal(err)
  865. }
  866. })
  867. svc := sdb.Service(time.Hour).(*Service)
  868. // Add three files
  869. files := []protocol.FileInfo{
  870. genFile("test1", 1, 1),
  871. genFile("test2", 2, 2),
  872. genFile("test3", 3, 3),
  873. }
  874. if err := sdb.Update(folderID, protocol.LocalDeviceID, files); err != nil {
  875. t.Fatal(err)
  876. }
  877. // There should exist three blockslists and six blocks
  878. fdb, err := sdb.getFolderDB(folderID, false)
  879. if err != nil {
  880. t.Fatal(err)
  881. }
  882. var count int
  883. if err := fdb.sql.Get(&count, `SELECT count(*) FROM blocklists`); err != nil {
  884. t.Fatal(err)
  885. }
  886. if count != 3 {
  887. t.Log(count)
  888. t.Fatal("expected 3 blocklists")
  889. }
  890. if err := fdb.sql.Get(&count, `SELECT count(*) FROM blocks`); err != nil {
  891. t.Fatal(err)
  892. }
  893. if count != 6 {
  894. t.Log(count)
  895. t.Fatal("expected 6 blocks")
  896. }
  897. // Mark test3 as deleted, it's blocks and blocklist are now eligible for collection
  898. files = files[2:]
  899. files[0].SetDeleted(42)
  900. if err := sdb.Update(folderID, protocol.LocalDeviceID, files); err != nil {
  901. t.Fatal(err)
  902. }
  903. // Run garbage collection
  904. if err := svc.periodic(context.Background()); err != nil {
  905. t.Fatal(err)
  906. }
  907. // There should exist two blockslists and four blocks
  908. if err := fdb.sql.Get(&count, `SELECT count(*) FROM blocklists`); err != nil {
  909. t.Fatal(err)
  910. }
  911. if count != 2 {
  912. t.Log(count)
  913. t.Error("expected 2 blocklists")
  914. }
  915. if err := fdb.sql.Get(&count, `SELECT count(*) FROM blocks`); err != nil {
  916. t.Fatal(err)
  917. }
  918. if count != 3 {
  919. t.Log(count)
  920. t.Error("expected 3 blocks")
  921. }
  922. }
  923. func TestInsertLargeFile(t *testing.T) {
  924. t.Parallel()
  925. sdb, err := OpenTemp()
  926. if err != nil {
  927. t.Fatal(err)
  928. }
  929. t.Cleanup(func() {
  930. if err := sdb.Close(); err != nil {
  931. t.Fatal(err)
  932. }
  933. })
  934. // Add a large file (many blocks)
  935. files := []protocol.FileInfo{genFile("test1", 16000, 1)}
  936. if err := sdb.Update(folderID, protocol.LocalDeviceID, files); err != nil {
  937. t.Fatal(err)
  938. }
  939. // Verify all the blocks are here
  940. for i, block := range files[0].Blocks {
  941. bs, err := sdb.AllLocalBlocksWithHash(block.Hash)
  942. if err != nil {
  943. t.Fatal(err)
  944. }
  945. if len(bs) == 0 {
  946. t.Error("missing blocks for", i)
  947. }
  948. }
  949. }
  950. func TestErrorWrap(t *testing.T) {
  951. if wrap(nil, "foo") != nil {
  952. t.Fatal("nil should wrap to nil")
  953. }
  954. fooErr := errors.New("foo")
  955. if err := wrap(fooErr); err.Error() != "testerrorwrap: foo" {
  956. t.Fatalf("%q", err)
  957. }
  958. if err := wrap(fooErr, "bar", "baz"); err.Error() != "testerrorwrap (bar, baz): foo" {
  959. t.Fatalf("%q", err)
  960. }
  961. }
  962. func mustCollect[T any](t *testing.T) func(it iter.Seq[T], errFn func() error) []T {
  963. t.Helper()
  964. return func(it iter.Seq[T], errFn func() error) []T {
  965. t.Helper()
  966. vals, err := itererr.Collect(it, errFn)
  967. if err != nil {
  968. t.Fatal(err)
  969. }
  970. return vals
  971. }
  972. }
  973. func fiNames(fs []protocol.FileInfo) []string {
  974. names := make([]string, len(fs))
  975. for i, fi := range fs {
  976. names[i] = fi.Name
  977. }
  978. return names
  979. }
  980. func genDir(name string, seq int) protocol.FileInfo {
  981. return protocol.FileInfo{
  982. Name: name,
  983. Type: protocol.FileInfoTypeDirectory,
  984. ModifiedS: time.Now().Unix(),
  985. ModifiedBy: 1,
  986. Sequence: int64(seq),
  987. Version: protocol.Vector{}.Update(1),
  988. Permissions: 0o755,
  989. ModifiedNs: 12345678,
  990. }
  991. }
  992. func genFile(name string, numBlocks int, seq int) protocol.FileInfo {
  993. ts := timeutil.StrictlyMonotonicNanos()
  994. s := ts / 1e9
  995. ns := int32(ts % 1e9)
  996. return protocol.FileInfo{
  997. Name: name,
  998. Size: int64(numBlocks) * blockSize,
  999. ModifiedS: s,
  1000. ModifiedBy: 1,
  1001. Version: protocol.Vector{}.Update(1),
  1002. Sequence: int64(seq),
  1003. Blocks: genBlocks(name, 0, numBlocks),
  1004. Permissions: 0o644,
  1005. ModifiedNs: ns,
  1006. RawBlockSize: blockSize,
  1007. }
  1008. }
  1009. func genBlocks(name string, seed, count int) []protocol.BlockInfo {
  1010. b := make([]protocol.BlockInfo, count)
  1011. for i := range b {
  1012. b[i].Hash = genBlockHash(name, seed, i)
  1013. b[i].Size = blockSize
  1014. b[i].Offset = (blockSize) * int64(i)
  1015. }
  1016. return b
  1017. }
  1018. func genBlockHash(name string, seed, index int) []byte {
  1019. bs := sha256.Sum256([]byte(name))
  1020. ebs := binary.LittleEndian.AppendUint64(nil, uint64(seed))
  1021. for i := range ebs {
  1022. bs[i] ^= ebs[i]
  1023. }
  1024. ebs = binary.LittleEndian.AppendUint64(nil, uint64(index))
  1025. for i := range ebs {
  1026. bs[i] ^= ebs[i]
  1027. }
  1028. return bs[:]
  1029. }