progressemitter_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. // Copyright (C) 2014 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 http://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "fmt"
  9. "path/filepath"
  10. "runtime"
  11. "testing"
  12. "time"
  13. "github.com/syncthing/syncthing/lib/config"
  14. "github.com/syncthing/syncthing/lib/events"
  15. "github.com/syncthing/syncthing/lib/protocol"
  16. "github.com/syncthing/syncthing/lib/sync"
  17. )
  18. var timeout = 100 * time.Millisecond
  19. func caller(skip int) string {
  20. _, file, line, ok := runtime.Caller(skip + 1)
  21. if !ok {
  22. return "unknown"
  23. }
  24. return fmt.Sprintf("%s:%d", filepath.Base(file), line)
  25. }
  26. func expectEvent(w *events.Subscription, t *testing.T, size int) {
  27. event, err := w.Poll(timeout)
  28. if err != nil {
  29. t.Fatal("Unexpected error:", err, "at", caller(1))
  30. }
  31. if event.Type != events.DownloadProgress {
  32. t.Fatal("Unexpected event:", event, "at", caller(1))
  33. }
  34. data := event.Data.(map[string]map[string]*pullerProgress)
  35. if len(data) != size {
  36. t.Fatal("Unexpected event data size:", data, "at", caller(1))
  37. }
  38. }
  39. func expectTimeout(w *events.Subscription, t *testing.T) {
  40. _, err := w.Poll(timeout)
  41. if err != events.ErrTimeout {
  42. t.Fatal("Unexpected non-Timeout error:", err, "at", caller(1))
  43. }
  44. }
  45. func TestProgressEmitter(t *testing.T) {
  46. w := events.Default.Subscribe(events.DownloadProgress)
  47. c := config.Wrap("/tmp/test", config.Configuration{})
  48. c.SetOptions(config.OptionsConfiguration{
  49. ProgressUpdateIntervalS: 0,
  50. })
  51. p := NewProgressEmitter(c)
  52. go p.Serve()
  53. expectTimeout(w, t)
  54. s := sharedPullerState{
  55. updated: time.Now(),
  56. mut: sync.NewRWMutex(),
  57. }
  58. p.Register(&s)
  59. expectEvent(w, t, 1)
  60. expectTimeout(w, t)
  61. s.copyDone(protocol.BlockInfo{})
  62. expectEvent(w, t, 1)
  63. expectTimeout(w, t)
  64. s.copiedFromOrigin()
  65. expectEvent(w, t, 1)
  66. expectTimeout(w, t)
  67. s.pullStarted()
  68. expectEvent(w, t, 1)
  69. expectTimeout(w, t)
  70. s.pullDone(protocol.BlockInfo{})
  71. expectEvent(w, t, 1)
  72. expectTimeout(w, t)
  73. p.Deregister(&s)
  74. expectEvent(w, t, 0)
  75. expectTimeout(w, t)
  76. }
  77. func TestSendDownloadProgressMessages(t *testing.T) {
  78. c := config.Wrap("/tmp/test", config.Configuration{})
  79. c.SetOptions(config.OptionsConfiguration{
  80. ProgressUpdateIntervalS: 0,
  81. TempIndexMinBlocks: 10,
  82. })
  83. fc := &FakeConnection{}
  84. p := NewProgressEmitter(c)
  85. p.temporaryIndexSubscribe(fc, []string{"folder", "folder2"})
  86. expect := func(updateIdx int, state *sharedPullerState, updateType uint32, version protocol.Vector, blocks []int32, remove bool) {
  87. messageIdx := -1
  88. for i, msg := range fc.downloadProgressMessages {
  89. if msg.folder == state.folder {
  90. messageIdx = i
  91. break
  92. }
  93. }
  94. if messageIdx < 0 {
  95. t.Errorf("Message for folder %s does not exist at %s", state.folder, caller(1))
  96. }
  97. msg := fc.downloadProgressMessages[messageIdx]
  98. // Don't know the index (it's random due to iterating maps)
  99. if updateIdx == -1 {
  100. for i, upd := range msg.updates {
  101. if upd.Name == state.file.Name {
  102. updateIdx = i
  103. break
  104. }
  105. }
  106. }
  107. if updateIdx == -1 {
  108. t.Errorf("Could not find update for %s at %s", state.file.Name, caller(1))
  109. }
  110. if updateIdx > len(msg.updates)-1 {
  111. t.Errorf("Update at index %d does not exist at %s", updateIdx, caller(1))
  112. }
  113. update := msg.updates[updateIdx]
  114. if update.UpdateType != updateType {
  115. t.Errorf("Wrong update type at %s", caller(1))
  116. }
  117. if !update.Version.Equal(version) {
  118. t.Errorf("Wrong version at %s", caller(1))
  119. }
  120. if len(update.BlockIndexes) != len(blocks) {
  121. t.Errorf("Wrong indexes. Have %d expect %d at %s", len(update.BlockIndexes), len(blocks), caller(1))
  122. }
  123. for i := range update.BlockIndexes {
  124. if update.BlockIndexes[i] != blocks[i] {
  125. t.Errorf("Index %d incorrect at %s", i, caller(1))
  126. }
  127. }
  128. if remove {
  129. fc.downloadProgressMessages = append(fc.downloadProgressMessages[:messageIdx], fc.downloadProgressMessages[messageIdx+1:]...)
  130. }
  131. }
  132. expectEmpty := func() {
  133. if len(fc.downloadProgressMessages) > 0 {
  134. t.Errorf("Still have something at %s: %#v", caller(1), fc.downloadProgressMessages)
  135. }
  136. }
  137. now := time.Now()
  138. tick := func() time.Time {
  139. now = now.Add(time.Second)
  140. return now
  141. }
  142. if len(fc.downloadProgressMessages) != 0 {
  143. t.Error("Expected no requests")
  144. }
  145. v1 := (protocol.Vector{}).Update(0)
  146. v2 := (protocol.Vector{}).Update(1)
  147. // Requires more than 10 blocks to work.
  148. blocks := make([]protocol.BlockInfo, 11, 11)
  149. state1 := &sharedPullerState{
  150. folder: "folder",
  151. file: protocol.FileInfo{
  152. Name: "state1",
  153. Version: v1,
  154. Blocks: blocks,
  155. },
  156. mut: sync.NewRWMutex(),
  157. availableUpdated: time.Now(),
  158. }
  159. p.registry["1"] = state1
  160. // Has no blocks, hence no message is sent
  161. p.sendDownloadProgressMessages()
  162. expectEmpty()
  163. // Returns update for puller with new extra blocks
  164. state1.available = []int32{1}
  165. p.sendDownloadProgressMessages()
  166. expect(0, state1, protocol.UpdateTypeAppend, v1, []int32{1}, true)
  167. expectEmpty()
  168. // Does nothing if nothing changes
  169. p.sendDownloadProgressMessages()
  170. expectEmpty()
  171. // Does nothing if timestamp updated, but no new blocks (should never happen)
  172. state1.availableUpdated = tick()
  173. p.sendDownloadProgressMessages()
  174. expectEmpty()
  175. // Does not return an update if date blocks change but date does not (should never happen)
  176. state1.available = []int32{1, 2}
  177. p.sendDownloadProgressMessages()
  178. expectEmpty()
  179. // If the date and blocks changes, returns only the diff
  180. state1.availableUpdated = tick()
  181. p.sendDownloadProgressMessages()
  182. expect(0, state1, protocol.UpdateTypeAppend, v1, []int32{2}, true)
  183. expectEmpty()
  184. // Returns forget and update if puller version has changed
  185. state1.file.Version = v2
  186. p.sendDownloadProgressMessages()
  187. expect(0, state1, protocol.UpdateTypeForget, v1, nil, false)
  188. expect(1, state1, protocol.UpdateTypeAppend, v2, []int32{1, 2}, true)
  189. expectEmpty()
  190. // Returns forget and append if sharedPullerState creation timer changes.
  191. state1.available = []int32{1}
  192. state1.availableUpdated = tick()
  193. state1.created = tick()
  194. p.sendDownloadProgressMessages()
  195. expect(0, state1, protocol.UpdateTypeForget, v2, nil, false)
  196. expect(1, state1, protocol.UpdateTypeAppend, v2, []int32{1}, true)
  197. expectEmpty()
  198. // Sends an empty update if new file exists, but does not have any blocks yet. (To indicate that the old blocks are no longer available)
  199. state1.file.Version = v1
  200. state1.available = nil
  201. state1.availableUpdated = tick()
  202. p.sendDownloadProgressMessages()
  203. expect(0, state1, protocol.UpdateTypeForget, v2, nil, false)
  204. expect(1, state1, protocol.UpdateTypeAppend, v1, nil, true)
  205. expectEmpty()
  206. // Updates for multiple files and folders can be combined
  207. state1.available = []int32{1, 2, 3}
  208. state1.availableUpdated = tick()
  209. state2 := &sharedPullerState{
  210. folder: "folder2",
  211. file: protocol.FileInfo{
  212. Name: "state2",
  213. Version: v1,
  214. Blocks: blocks,
  215. },
  216. mut: sync.NewRWMutex(),
  217. available: []int32{1, 2, 3},
  218. availableUpdated: time.Now(),
  219. }
  220. state3 := &sharedPullerState{
  221. folder: "folder",
  222. file: protocol.FileInfo{
  223. Name: "state3",
  224. Version: v1,
  225. Blocks: blocks,
  226. },
  227. mut: sync.NewRWMutex(),
  228. available: []int32{1, 2, 3},
  229. availableUpdated: time.Now(),
  230. }
  231. state4 := &sharedPullerState{
  232. folder: "folder2",
  233. file: protocol.FileInfo{
  234. Name: "state4",
  235. Version: v1,
  236. Blocks: blocks,
  237. },
  238. mut: sync.NewRWMutex(),
  239. available: []int32{1, 2, 3},
  240. availableUpdated: time.Now(),
  241. }
  242. p.registry["2"] = state2
  243. p.registry["3"] = state3
  244. p.registry["4"] = state4
  245. p.sendDownloadProgressMessages()
  246. expect(-1, state1, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, false)
  247. expect(-1, state3, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, true)
  248. expect(-1, state2, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, false)
  249. expect(-1, state4, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, true)
  250. expectEmpty()
  251. // Returns forget if puller no longer exists, as well as updates if it has been updated.
  252. state1.available = []int32{1, 2, 3, 4, 5}
  253. state1.availableUpdated = tick()
  254. state2.available = []int32{1, 2, 3, 4, 5}
  255. state2.availableUpdated = tick()
  256. delete(p.registry, "3")
  257. delete(p.registry, "4")
  258. p.sendDownloadProgressMessages()
  259. expect(-1, state1, protocol.UpdateTypeAppend, v1, []int32{4, 5}, false)
  260. expect(-1, state3, protocol.UpdateTypeForget, v1, nil, true)
  261. expect(-1, state2, protocol.UpdateTypeAppend, v1, []int32{4, 5}, false)
  262. expect(-1, state4, protocol.UpdateTypeForget, v1, nil, true)
  263. expectEmpty()
  264. // Deletions are sent only once (actual bug I found writing the tests)
  265. p.sendDownloadProgressMessages()
  266. p.sendDownloadProgressMessages()
  267. expectEmpty()
  268. // Not sent for "inactive" (symlinks, dirs, or wrong folder) pullers
  269. // Directory
  270. state5 := &sharedPullerState{
  271. folder: "folder",
  272. file: protocol.FileInfo{
  273. Name: "state5",
  274. Version: v1,
  275. Flags: protocol.FlagDirectory,
  276. Blocks: blocks,
  277. },
  278. mut: sync.NewRWMutex(),
  279. available: []int32{1, 2, 3},
  280. availableUpdated: time.Now(),
  281. }
  282. // Symlink
  283. state6 := &sharedPullerState{
  284. folder: "folder",
  285. file: protocol.FileInfo{
  286. Name: "state6",
  287. Version: v1,
  288. Flags: protocol.FlagSymlink,
  289. },
  290. mut: sync.NewRWMutex(),
  291. available: []int32{1, 2, 3},
  292. availableUpdated: time.Now(),
  293. }
  294. // Some other directory
  295. state7 := &sharedPullerState{
  296. folder: "folderXXX",
  297. file: protocol.FileInfo{
  298. Name: "state7",
  299. Version: v1,
  300. Blocks: blocks,
  301. },
  302. mut: sync.NewRWMutex(),
  303. available: []int32{1, 2, 3},
  304. availableUpdated: time.Now(),
  305. }
  306. // Less than 10 blocks
  307. state8 := &sharedPullerState{
  308. folder: "folder",
  309. file: protocol.FileInfo{
  310. Name: "state8",
  311. Version: v1,
  312. Blocks: blocks[:3],
  313. },
  314. mut: sync.NewRWMutex(),
  315. available: []int32{1, 2, 3},
  316. availableUpdated: time.Now(),
  317. }
  318. p.registry["5"] = state5
  319. p.registry["6"] = state6
  320. p.registry["7"] = state7
  321. p.registry["8"] = state8
  322. p.sendDownloadProgressMessages()
  323. expectEmpty()
  324. // Device is no longer subscribed to a particular folder
  325. delete(p.registry, "1") // Clean up first
  326. delete(p.registry, "2") // Clean up first
  327. p.sendDownloadProgressMessages()
  328. expect(-1, state1, protocol.UpdateTypeForget, v1, nil, true)
  329. expect(-1, state2, protocol.UpdateTypeForget, v1, nil, true)
  330. expectEmpty()
  331. p.registry["1"] = state1
  332. p.registry["2"] = state2
  333. p.registry["3"] = state3
  334. p.registry["4"] = state4
  335. p.sendDownloadProgressMessages()
  336. expect(-1, state1, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3, 4, 5}, false)
  337. expect(-1, state3, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, true)
  338. expect(-1, state2, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3, 4, 5}, false)
  339. expect(-1, state4, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, true)
  340. expectEmpty()
  341. p.temporaryIndexUnsubscribe(fc)
  342. p.temporaryIndexSubscribe(fc, []string{"folder"})
  343. p.sendDownloadProgressMessages()
  344. // See progressemitter.go for explanation why this is commented out.
  345. // Search for state.cleanup
  346. //expect(-1, state2, protocol.UpdateTypeForget, v1, nil, false)
  347. //expect(-1, state4, protocol.UpdateTypeForget, v1, nil, true)
  348. expectEmpty()
  349. // Cleanup when device no longer exists
  350. p.temporaryIndexUnsubscribe(fc)
  351. p.sendDownloadProgressMessages()
  352. _, ok := p.sentDownloadStates[fc.ID()]
  353. if ok {
  354. t.Error("Should not be there")
  355. }
  356. }