indexhandler.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. // Copyright (C) 2020 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 model
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "log/slog"
  12. "sync"
  13. "time"
  14. "github.com/syncthing/syncthing/internal/db"
  15. "github.com/syncthing/syncthing/internal/itererr"
  16. "github.com/syncthing/syncthing/lib/config"
  17. "github.com/syncthing/syncthing/lib/events"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "github.com/syncthing/syncthing/lib/svcutil"
  20. "github.com/syncthing/syncthing/lib/ur"
  21. )
  22. type indexHandler struct {
  23. conn protocol.Connection
  24. downloads *deviceDownloadState
  25. folder string
  26. folderIsReceiveEncrypted bool
  27. evLogger events.Logger
  28. // We track the latest / highest sequence number in two ways for two
  29. // different reasons. Initially they are the same -- the highest seen
  30. // sequence number reported by the other side (or zero).
  31. //
  32. // One is the highest number we've seen when iterating the database,
  33. // which we track for database iteration purposes. When we loop, we
  34. // start looking at that number plus one in the next loop. Our index
  35. // numbering may have holes which this will skip over.
  36. //
  37. // The other is the highest sequence we previously sent to the other
  38. // side, used by them for correctness checks. This one must not skip
  39. // holes. That is, if we iterate and find a hole, this is not
  40. // incremented because nothing was sent to the other side.
  41. localPrevSequence int64 // the highest sequence number we've seen in our FileInfos
  42. sentPrevSequence int64 // the highest sequence number we've sent to the peer
  43. cond *sync.Cond
  44. paused bool
  45. sdb db.DB
  46. runner service
  47. }
  48. func newIndexHandler(conn protocol.Connection, downloads *deviceDownloadState, folder config.FolderConfiguration, sdb db.DB, runner service, startInfo *clusterConfigDeviceInfo, evLogger events.Logger) (*indexHandler, error) {
  49. myIndexID, err := sdb.GetIndexID(folder.ID, protocol.LocalDeviceID)
  50. if err != nil {
  51. return nil, err
  52. }
  53. mySequence, err := sdb.GetDeviceSequence(folder.ID, protocol.LocalDeviceID)
  54. if err != nil {
  55. return nil, err
  56. }
  57. var startSequence int64
  58. // This is the other side's description of what it knows
  59. // about us. Lets check to see if we can start sending index
  60. // updates directly or need to send the index from start...
  61. switch startInfo.local.IndexID {
  62. case myIndexID:
  63. // They say they've seen our index ID before, so we can
  64. // send a delta update only.
  65. if startInfo.local.MaxSequence > mySequence {
  66. // Safety check. They claim to have more or newer
  67. // index data than we have - either we have lost
  68. // index data, or reset the index without resetting
  69. // the IndexID, or something else weird has
  70. // happened. We send a full index to reset the
  71. // situation.
  72. slog.Warn("Peer is delta index compatible, but seems out of sync with reality", conn.DeviceID().LogAttr(), folder.LogAttr())
  73. startSequence = 0
  74. } else {
  75. l.Debugf("Device %v folder %s is delta index compatible (mlv=%d)", conn.DeviceID().Short(), folder.Description(), startInfo.local.MaxSequence)
  76. startSequence = startInfo.local.MaxSequence
  77. }
  78. case 0:
  79. l.Debugf("Device %v folder %s has no index ID for us", conn.DeviceID().Short(), folder.Description())
  80. default:
  81. // They say they've seen an index ID from us, but it's
  82. // not the right one. Either they are confused or we
  83. // must have reset our database since last talking to
  84. // them. We'll start with a full index transfer.
  85. slog.Warn("Peer has mismatching index ID for us", conn.DeviceID().LogAttr(), folder.LogAttr(), slog.Group("indexid", slog.Any("ours", myIndexID), slog.Any("theirs", startInfo.local.IndexID)))
  86. startSequence = 0
  87. }
  88. // This is the other side's description of themselves. We
  89. // check to see that it matches the IndexID we have on file,
  90. // otherwise we drop our old index data and expect to get a
  91. // completely new set.
  92. theirIndexID, _ := sdb.GetIndexID(folder.ID, conn.DeviceID())
  93. if startInfo.remote.IndexID == 0 {
  94. // They're not announcing an index ID. This means they
  95. // do not support delta indexes and we should clear any
  96. // information we have from them before accepting their
  97. // index, which will presumably be a full index.
  98. l.Debugf("Device %v folder %s does not announce an index ID", conn.DeviceID().Short(), folder.Description())
  99. if err := sdb.DropAllFiles(folder.ID, conn.DeviceID()); err != nil {
  100. return nil, err
  101. }
  102. } else if startInfo.remote.IndexID != theirIndexID {
  103. // The index ID we have on file is not what they're
  104. // announcing. They must have reset their database and
  105. // will probably send us a full index. We drop any
  106. // information we have and remember this new index ID
  107. // instead.
  108. slog.Info("Peer has a new index ID", conn.DeviceID().LogAttr(), folder.LogAttr(), slog.Any("indexid", startInfo.remote.IndexID))
  109. if err := sdb.DropAllFiles(folder.ID, conn.DeviceID()); err != nil {
  110. return nil, err
  111. }
  112. if err := sdb.SetIndexID(folder.ID, conn.DeviceID(), startInfo.remote.IndexID); err != nil {
  113. return nil, err
  114. }
  115. }
  116. return &indexHandler{
  117. conn: conn,
  118. downloads: downloads,
  119. folder: folder.ID,
  120. folderIsReceiveEncrypted: folder.Type == config.FolderTypeReceiveEncrypted,
  121. localPrevSequence: startSequence,
  122. sentPrevSequence: startSequence,
  123. evLogger: evLogger,
  124. sdb: sdb,
  125. runner: runner,
  126. cond: sync.NewCond(new(sync.Mutex)),
  127. }, nil
  128. }
  129. // waitWhilePaused waits for the handler to resume.
  130. func (s *indexHandler) waitWhilePaused(ctx context.Context) error {
  131. s.cond.L.Lock()
  132. defer s.cond.L.Unlock()
  133. for s.paused {
  134. select {
  135. case <-ctx.Done():
  136. return ctx.Err()
  137. default:
  138. s.cond.Wait()
  139. }
  140. }
  141. return nil
  142. }
  143. func (s *indexHandler) Serve(ctx context.Context) (err error) {
  144. l.Debugf("Starting index handler for %s to %s at %s (localPrevSequence=%d)", s.folder, s.conn.DeviceID().Short(), s.conn, s.localPrevSequence)
  145. stop := make(chan struct{})
  146. defer func() {
  147. err = svcutil.NoRestartErr(err)
  148. l.Debugf("Exiting index handler for %s to %s at %s: %v", s.folder, s.conn.DeviceID().Short(), s.conn, err)
  149. close(stop)
  150. }()
  151. // Broadcast the pause cond when the context quits
  152. go func() {
  153. select {
  154. case <-ctx.Done():
  155. s.cond.Broadcast()
  156. case <-stop:
  157. }
  158. }()
  159. // We need to send one index, regardless of whether there is something to send or not
  160. if err := s.waitWhilePaused(ctx); err != nil {
  161. return err
  162. }
  163. err = s.sendIndexTo(ctx)
  164. // Subscribe to LocalIndexUpdated (we have new information to send) and
  165. // DeviceDisconnected (it might be us who disconnected, so we should
  166. // exit).
  167. sub := s.evLogger.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  168. defer sub.Unsubscribe()
  169. evChan := sub.C()
  170. ticker := time.NewTicker(time.Minute)
  171. defer ticker.Stop()
  172. for err == nil {
  173. if err := s.waitWhilePaused(ctx); err != nil {
  174. return err
  175. }
  176. // While we have sent a sequence at least equal to the one
  177. // currently in the database, wait for the local index to update. The
  178. // local index may update for other folders than the one we are
  179. // sending for.
  180. var seq int64
  181. seq, err = s.sdb.GetDeviceSequence(s.folder, protocol.LocalDeviceID)
  182. if err != nil {
  183. return err
  184. }
  185. if seq <= s.localPrevSequence {
  186. select {
  187. case <-ctx.Done():
  188. return ctx.Err()
  189. case <-evChan:
  190. case <-ticker.C:
  191. }
  192. continue
  193. }
  194. err = s.sendIndexTo(ctx)
  195. // Wait a short amount of time before entering the next loop. If there
  196. // are continuous changes happening to the local index, this gives us
  197. // time to batch them up a little.
  198. select {
  199. case <-ctx.Done():
  200. return ctx.Err()
  201. case <-time.After(250 * time.Millisecond):
  202. }
  203. }
  204. return err
  205. }
  206. // resume might be called because the folder was actually resumed, or just
  207. // because the folder config changed (and thus the runner and potentially fset).
  208. func (s *indexHandler) resume(runner service) {
  209. s.cond.L.Lock()
  210. s.paused = false
  211. s.runner = runner
  212. s.cond.Broadcast()
  213. s.cond.L.Unlock()
  214. }
  215. func (s *indexHandler) pause() {
  216. s.cond.L.Lock()
  217. if s.paused {
  218. s.evLogger.Log(events.Failure, "index handler got paused while already paused")
  219. }
  220. s.paused = true
  221. s.runner = nil
  222. s.cond.Broadcast()
  223. s.cond.L.Unlock()
  224. }
  225. // sendIndexTo sends file infos with a sequence number higher than prevSequence and
  226. // returns the highest sent sequence number.
  227. func (s *indexHandler) sendIndexTo(ctx context.Context) error {
  228. initial := s.localPrevSequence == 0
  229. batch := NewFileInfoBatch(nil)
  230. var batchError error
  231. batch.SetFlushFunc(func(fs []protocol.FileInfo) error {
  232. select {
  233. case <-ctx.Done():
  234. return ctx.Err()
  235. default:
  236. }
  237. if len(fs) == 0 {
  238. // can't happen, flush is not called with an empty batch
  239. panic("bug: flush called with empty batch (race condition?)")
  240. }
  241. if batchError != nil {
  242. // can't happen, once an error is returned the index sender exits
  243. panic(fmt.Sprintf("bug: once failed it should stay failed (%v)", batchError))
  244. }
  245. l.Debugf("%v: Sending %d files (<%d bytes)", s, len(fs), batch.Size())
  246. lastSequence := fs[len(fs)-1].Sequence
  247. var err error
  248. if initial {
  249. initial = false
  250. err = s.conn.Index(ctx, &protocol.Index{
  251. Folder: s.folder,
  252. Files: fs,
  253. LastSequence: lastSequence,
  254. })
  255. } else {
  256. err = s.conn.IndexUpdate(ctx, &protocol.IndexUpdate{
  257. Folder: s.folder,
  258. Files: fs,
  259. PrevSequence: s.sentPrevSequence,
  260. LastSequence: lastSequence,
  261. })
  262. }
  263. if err != nil {
  264. batchError = err
  265. return err
  266. }
  267. s.sentPrevSequence = lastSequence
  268. return nil
  269. })
  270. var f protocol.FileInfo
  271. previousWasDelete := false
  272. for fi, err := range itererr.Zip(s.sdb.AllLocalFilesBySequence(s.folder, protocol.LocalDeviceID, s.localPrevSequence+1, MaxBatchSizeFiles+1)) {
  273. if err != nil {
  274. return err
  275. }
  276. // This is to make sure that renames (which is an add followed by a delete) land in the same batch.
  277. // Even if the batch is full, we allow a last delete to slip in, we do this by making sure that
  278. // the batch ends with a non-delete, or that the last item in the batch is already a delete
  279. if batch.Full() && (!fi.IsDeleted() || previousWasDelete) {
  280. break
  281. }
  282. if fi.SequenceNo() < s.localPrevSequence+1 {
  283. s.logSequenceAnomaly("database returned sequence lower than requested", map[string]any{
  284. "sequence": fi.SequenceNo(),
  285. "start": s.localPrevSequence + 1,
  286. })
  287. return errors.New("database misbehaved")
  288. }
  289. if f.Sequence > 0 && fi.SequenceNo() <= f.Sequence {
  290. s.logSequenceAnomaly("database returned non-increasing sequence", map[string]any{
  291. "sequence": fi.SequenceNo(),
  292. "start": s.localPrevSequence + 1,
  293. "previous": f.Sequence,
  294. })
  295. return errors.New("database misbehaved")
  296. }
  297. f = fi
  298. s.localPrevSequence = f.Sequence
  299. // If this is a folder receiving encrypted files only, we
  300. // mustn't ever send locally changed file infos. Those aren't
  301. // encrypted and thus would be a protocol error at the remote.
  302. if s.folderIsReceiveEncrypted && fi.IsReceiveOnlyChanged() {
  303. continue
  304. }
  305. f = prepareFileInfoForIndex(f)
  306. previousWasDelete = f.IsDeleted()
  307. batch.Append(f)
  308. }
  309. return batch.Flush()
  310. }
  311. func (s *indexHandler) receive(fs []protocol.FileInfo, update bool, op string, prevSequence, lastSequence int64) error {
  312. deviceID := s.conn.DeviceID()
  313. s.cond.L.Lock()
  314. paused := s.paused
  315. runner := s.runner
  316. s.cond.L.Unlock()
  317. if paused {
  318. slog.Warn("Unexpected operation on paused folder", "op", op, "folder", s.folder)
  319. return fmt.Errorf("%v: %w", s.folder, ErrFolderPaused)
  320. }
  321. defer runner.SchedulePull()
  322. s.downloads.Update(s.folder, makeForgetUpdate(fs))
  323. if !update {
  324. if err := s.sdb.DropAllFiles(s.folder, deviceID); err != nil {
  325. return err
  326. }
  327. }
  328. l.Debugf("Received %d files for %s from %s, prevSeq=%d, lastSeq=%d", len(fs), s.folder, deviceID.Short(), prevSequence, lastSequence)
  329. // Verify that the previous sequence number matches what we expected
  330. exp, err := s.sdb.GetDeviceSequence(s.folder, deviceID)
  331. if err != nil {
  332. return err
  333. }
  334. if prevSequence > 0 && prevSequence != exp {
  335. s.logSequenceAnomaly("index update with unexpected sequence", map[string]any{
  336. "prevSeq": prevSequence,
  337. "lastSeq": lastSequence,
  338. "batch": len(fs),
  339. "expectedPrev": exp,
  340. })
  341. }
  342. for i := range fs {
  343. // Verify index in relation to the claimed sequence boundaries
  344. if fs[i].Sequence < prevSequence {
  345. s.logSequenceAnomaly("file with sequence before prevSequence", map[string]any{
  346. "prevSeq": prevSequence,
  347. "lastSeq": lastSequence,
  348. "batch": len(fs),
  349. "seenSeq": fs[i].Sequence,
  350. "atIndex": i,
  351. })
  352. }
  353. if lastSequence > 0 && fs[i].Sequence > lastSequence {
  354. s.logSequenceAnomaly("file with sequence after lastSequence", map[string]any{
  355. "prevSeq": prevSequence,
  356. "lastSeq": lastSequence,
  357. "batch": len(fs),
  358. "seenSeq": fs[i].Sequence,
  359. "atIndex": i,
  360. })
  361. }
  362. if i > 0 && fs[i].Sequence <= fs[i-1].Sequence {
  363. s.logSequenceAnomaly("index update with non-increasing sequence", map[string]any{
  364. "prevSeq": prevSequence,
  365. "lastSeq": lastSequence,
  366. "batch": len(fs),
  367. "seenSeq": fs[i].Sequence,
  368. "atIndex": i,
  369. "precedingSeq": fs[i-1].Sequence,
  370. })
  371. }
  372. }
  373. // Verify the claimed last sequence number
  374. if lastSequence > 0 && len(fs) > 0 && lastSequence != fs[len(fs)-1].Sequence {
  375. s.logSequenceAnomaly("index update with unexpected last sequence", map[string]any{
  376. "prevSeq": prevSequence,
  377. "lastSeq": lastSequence,
  378. "batch": len(fs),
  379. "seenSeq": fs[len(fs)-1].Sequence,
  380. })
  381. }
  382. if err := s.sdb.Update(s.folder, deviceID, fs); err != nil {
  383. return err
  384. }
  385. seq, err := s.sdb.GetDeviceSequence(s.folder, deviceID)
  386. if err != nil {
  387. return err
  388. }
  389. // Check that the sequence we get back is what we put in...
  390. if lastSequence > 0 && len(fs) > 0 && seq != lastSequence {
  391. s.logSequenceAnomaly("unexpected sequence after update", map[string]any{
  392. "prevSeq": prevSequence,
  393. "lastSeq": lastSequence,
  394. "batch": len(fs),
  395. "seenSeq": fs[len(fs)-1].Sequence,
  396. "returnedSeq": seq,
  397. })
  398. }
  399. s.evLogger.Log(events.RemoteIndexUpdated, map[string]interface{}{
  400. "device": deviceID.String(),
  401. "folder": s.folder,
  402. "items": len(fs),
  403. "sequence": seq,
  404. "version": seq, // legacy for sequence
  405. })
  406. return nil
  407. }
  408. func (s *indexHandler) logSequenceAnomaly(msg string, extra map[string]any) {
  409. extraStrs := make(map[string]string, len(extra))
  410. for k, v := range extra {
  411. extraStrs[k] = fmt.Sprint(v)
  412. }
  413. s.evLogger.Log(events.Failure, ur.FailureData{
  414. Description: msg,
  415. Extra: extraStrs,
  416. })
  417. }
  418. func prepareFileInfoForIndex(f protocol.FileInfo) protocol.FileInfo {
  419. // If the file is marked LocalReceive (i.e., changed locally on a
  420. // receive only folder) we do not want it to ever become the
  421. // globally best version, invalid or not.
  422. if f.IsReceiveOnlyChanged() {
  423. f.Version = protocol.Vector{}
  424. }
  425. // The trailer with the encrypted fileinfo is device local, announce the size without it to remotes.
  426. f.Size -= int64(f.EncryptionTrailerSize)
  427. return f
  428. }
  429. func (s *indexHandler) String() string {
  430. return fmt.Sprintf("indexHandler@%p for %s to %s at %s", s, s.folder, s.conn.DeviceID().Short(), s.conn)
  431. }
  432. type indexHandlerRegistry struct {
  433. evLogger events.Logger
  434. conn protocol.Connection
  435. sdb db.DB
  436. downloads *deviceDownloadState
  437. indexHandlers *serviceMap[string, *indexHandler]
  438. startInfos map[string]*clusterConfigDeviceInfo
  439. folderStates map[string]*indexHandlerFolderState
  440. mut sync.Mutex
  441. }
  442. type indexHandlerFolderState struct {
  443. cfg config.FolderConfiguration
  444. runner service
  445. }
  446. func newIndexHandlerRegistry(conn protocol.Connection, sdb db.DB, downloads *deviceDownloadState, evLogger events.Logger) *indexHandlerRegistry {
  447. r := &indexHandlerRegistry{
  448. evLogger: evLogger,
  449. conn: conn,
  450. sdb: sdb,
  451. downloads: downloads,
  452. indexHandlers: newServiceMap[string, *indexHandler](evLogger),
  453. startInfos: make(map[string]*clusterConfigDeviceInfo),
  454. folderStates: make(map[string]*indexHandlerFolderState),
  455. mut: sync.Mutex{},
  456. }
  457. return r
  458. }
  459. func (r *indexHandlerRegistry) String() string {
  460. return fmt.Sprintf("indexHandlerRegistry/%v", r.conn.DeviceID().Short())
  461. }
  462. func (r *indexHandlerRegistry) Serve(ctx context.Context) error {
  463. // Running the index handler registry means running the individual index
  464. // handler children.
  465. return r.indexHandlers.Serve(ctx)
  466. }
  467. func (r *indexHandlerRegistry) startLocked(folder config.FolderConfiguration, runner service, startInfo *clusterConfigDeviceInfo) error {
  468. r.indexHandlers.RemoveAndWait(folder.ID, 0)
  469. delete(r.startInfos, folder.ID)
  470. is, err := newIndexHandler(r.conn, r.downloads, folder, r.sdb, runner, startInfo, r.evLogger)
  471. if err != nil {
  472. return err
  473. }
  474. r.indexHandlers.Add(folder.ID, is)
  475. // This new connection might help us get in sync.
  476. runner.SchedulePull()
  477. return nil
  478. }
  479. // AddIndexInfo starts an index handler for given folder, unless it is paused.
  480. // If it is paused, the given startInfo is stored to start the sender once the
  481. // folder is resumed.
  482. // If an index handler is already running, it will be stopped first.
  483. func (r *indexHandlerRegistry) AddIndexInfo(folder string, startInfo *clusterConfigDeviceInfo) {
  484. r.mut.Lock()
  485. defer r.mut.Unlock()
  486. if r.indexHandlers.RemoveAndWait(folder, 0) == nil {
  487. l.Debugf("Removed index sender for device %v and folder %v due to added pending", r.conn.DeviceID().Short(), folder)
  488. }
  489. folderState, ok := r.folderStates[folder]
  490. if !ok {
  491. l.Debugf("Pending index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  492. r.startInfos[folder] = startInfo
  493. return
  494. }
  495. _ = r.startLocked(folderState.cfg, folderState.runner, startInfo) // XXX error handling...
  496. }
  497. // Remove stops a running index handler or removes one pending to be started.
  498. // It is a noop if the folder isn't known.
  499. func (r *indexHandlerRegistry) Remove(folder string) {
  500. r.mut.Lock()
  501. defer r.mut.Unlock()
  502. l.Debugf("Removing index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  503. r.indexHandlers.RemoveAndWait(folder, 0)
  504. delete(r.startInfos, folder)
  505. l.Debugf("Removed index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  506. }
  507. // RemoveAllExcept stops all running index handlers and removes those pending to be started,
  508. // except mentioned ones.
  509. // It is a noop if the folder isn't known.
  510. func (r *indexHandlerRegistry) RemoveAllExcept(except map[string]remoteFolderState) {
  511. r.mut.Lock()
  512. defer r.mut.Unlock()
  513. r.indexHandlers.Each(func(folder string, is *indexHandler) error {
  514. if _, ok := except[folder]; !ok {
  515. r.indexHandlers.RemoveAndWait(folder, 0)
  516. l.Debugf("Removed index handler for device %v and folder %v (removeAllExcept)", r.conn.DeviceID().Short(), folder)
  517. }
  518. return nil
  519. })
  520. for folder := range r.startInfos {
  521. if _, ok := except[folder]; !ok {
  522. delete(r.startInfos, folder)
  523. l.Debugf("Removed pending index handler for device %v and folder %v (removeAllExcept)", r.conn.DeviceID().Short(), folder)
  524. }
  525. }
  526. }
  527. // RegisterFolderState must be called whenever something about the folder
  528. // changes. The exception being if the folder is removed entirely, then call
  529. // Remove. The fset and runner arguments may be nil, if given folder is paused.
  530. func (r *indexHandlerRegistry) RegisterFolderState(folder config.FolderConfiguration, runner service) {
  531. if !folder.SharedWith(r.conn.DeviceID()) {
  532. r.Remove(folder.ID)
  533. return
  534. }
  535. r.mut.Lock()
  536. if folder.Paused {
  537. r.folderPausedLocked(folder.ID)
  538. } else {
  539. r.folderRunningLocked(folder, runner)
  540. }
  541. r.mut.Unlock()
  542. }
  543. // folderPausedLocked stops a running index handler.
  544. // It is a noop if the folder isn't known or has not been started yet.
  545. func (r *indexHandlerRegistry) folderPausedLocked(folder string) {
  546. l.Debugf("Pausing index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  547. delete(r.folderStates, folder)
  548. if is, ok := r.indexHandlers.Get(folder); ok {
  549. is.pause()
  550. l.Debugf("Paused index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  551. } else {
  552. l.Debugf("No index handler for device %v and folder %v to pause", r.conn.DeviceID().Short(), folder)
  553. }
  554. }
  555. // folderRunningLocked resumes an already running index handler or starts it, if it
  556. // was added while paused.
  557. // It is a noop if the folder isn't known.
  558. func (r *indexHandlerRegistry) folderRunningLocked(folder config.FolderConfiguration, runner service) {
  559. r.folderStates[folder.ID] = &indexHandlerFolderState{
  560. cfg: folder,
  561. runner: runner,
  562. }
  563. is, isOk := r.indexHandlers.Get(folder.ID)
  564. if info, ok := r.startInfos[folder.ID]; ok {
  565. if isOk {
  566. r.indexHandlers.RemoveAndWait(folder.ID, 0)
  567. l.Debugf("Removed index handler for device %v and folder %v in resume", r.conn.DeviceID().Short(), folder.ID)
  568. }
  569. _ = r.startLocked(folder, runner, info) // XXX error handling...
  570. delete(r.startInfos, folder.ID)
  571. l.Debugf("Started index handler for device %v and folder %v in resume", r.conn.DeviceID().Short(), folder.ID)
  572. } else if isOk {
  573. l.Debugf("Resuming index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  574. is.resume(runner)
  575. } else {
  576. l.Debugf("Not resuming index handler for device %v and folder %v as none is paused and there is no start info", r.conn.DeviceID().Short(), folder.ID)
  577. }
  578. }
  579. func (r *indexHandlerRegistry) ReceiveIndex(folder string, fs []protocol.FileInfo, update bool, op string, prevSequence, lastSequence int64) error {
  580. r.mut.Lock()
  581. defer r.mut.Unlock()
  582. is, isOk := r.indexHandlers.Get(folder)
  583. if !isOk {
  584. slog.Warn("Unexpected operation on nonexistent or paused folder", "op", op, "folder", folder)
  585. return fmt.Errorf("%s: %w", folder, ErrFolderMissing)
  586. }
  587. return is.receive(fs, update, op, prevSequence, lastSequence)
  588. }
  589. // makeForgetUpdate takes an index update and constructs a download progress update
  590. // causing to forget any progress for files which we've just been sent.
  591. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  592. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  593. for _, file := range files {
  594. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  595. continue
  596. }
  597. updates = append(updates, protocol.FileDownloadProgressUpdate{
  598. Name: file.Name,
  599. Version: file.Version,
  600. UpdateType: protocol.FileDownloadProgressUpdateTypeForget,
  601. })
  602. }
  603. return updates
  604. }