sync.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. /*
  2. * This file is part of the storage node for the Joystream project.
  3. * Copyright (C) 2019 Joystream Contributors
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. 'use strict'
  19. const debug = require('debug')('joystream:sync')
  20. const _ = require('lodash')
  21. // TODO: refactor these two values into a new class
  22. // The number of concurrent sync sessions allowed. Must be greater than zero.
  23. const MAX_CONCURRENT_SYNC_ITEMS = 15
  24. const contentBeingSynced = new Map()
  25. async function syncCallback(api, storage) {
  26. const knownContentIds = await api.assets.getKnownContentIds()
  27. const roleAddress = api.identities.key.address
  28. const providerId = api.storageProviderId
  29. // Iterate over all objects, and start syncing if required.
  30. // compile list of already syncedIds (as reported by storage
  31. // subsytem). The only async part here is resolving content id
  32. // by storage to ipfs cid, maybe we can resolve them locally
  33. // and cache result to simplify async code below and reduce
  34. // queries
  35. // Since we are limiting concurrent content ids being synced, to ensure
  36. // better distribution of content across storage nodes during a potentially long
  37. // sync process we don't want all nodes to replicate items in the same order, so
  38. // we simply shuffle ids around.
  39. const shuffledIds = _.shuffle(knownContentIds)
  40. const syncedIds = (
  41. await Promise.all(
  42. shuffledIds.map(async (contentId) => {
  43. // TODO: get the data object
  44. // make sure the data object was Accepted by the liaison,
  45. // don't just blindly attempt to fetch them
  46. try {
  47. const { synced, syncing } = await storage.syncStatus(contentId)
  48. if (synced) {
  49. return contentId
  50. } else if (!syncing) {
  51. if (contentBeingSynced.size < MAX_CONCURRENT_SYNC_ITEMS) {
  52. try {
  53. contentBeingSynced.set(contentId, true)
  54. await storage.synchronize(contentId, () => {
  55. contentBeingSynced.delete(contentId)
  56. })
  57. } catch (err) {
  58. debug(`Failed calling synchronize ${err}`)
  59. contentBeingSynced.delete(contentId)
  60. }
  61. } else {
  62. // Content needs to be synced, but limit on concurrent syncs reached
  63. debug('Deferring, concurrent sessions exhausted.')
  64. }
  65. }
  66. } catch (err) {
  67. debug(`Failed getting syncStatus. contnetId: ${contentId} ${err}`)
  68. }
  69. return null
  70. })
  71. )
  72. ).filter((id) => id !== null)
  73. // Create new relationships for synced content if required and
  74. // compose list of relationship ids to be set to ready.
  75. const relationshipIds = (
  76. await Promise.all(
  77. syncedIds.map(async (contentId) => {
  78. const { relationship, relationshipId } = await api.assets.getStorageRelationshipAndId(providerId, contentId)
  79. if (relationship) {
  80. // maybe prior transaction to set ready failed for some reason..
  81. if (!relationship.ready) {
  82. return relationshipId
  83. }
  84. } else {
  85. // create relationship
  86. debug(`Creating new storage relationship for ${contentId.encode()}`)
  87. try {
  88. return await api.assets.createStorageRelationship(roleAddress, providerId, contentId)
  89. } catch (err) {
  90. debug(`Error creating new storage relationship ${contentId.encode()}: ${err.stack}`)
  91. }
  92. }
  93. return null
  94. })
  95. )
  96. ).filter((id) => id !== null)
  97. // Set relationships to ready state
  98. return Promise.all(
  99. relationshipIds.map(async (relationshipId) => {
  100. try {
  101. await api.assets.toggleStorageRelationshipReady(roleAddress, providerId, relationshipId, true)
  102. } catch (err) {
  103. debug('Error setting relationship ready')
  104. }
  105. })
  106. )
  107. }
  108. async function syncPeriodic(api, flags, storage) {
  109. try {
  110. debug('Starting sync run...')
  111. const chainIsSyncing = await api.chainIsSyncing()
  112. if (chainIsSyncing) {
  113. debug('Chain is syncing. Postponing sync run.')
  114. return setTimeout(syncPeriodic, flags.syncPeriod, api, flags, storage)
  115. }
  116. const recommendedBalance = await api.providerHasMinimumBalance(300)
  117. if (!recommendedBalance) {
  118. debug('Warning: Provider role account is running low on balance.')
  119. }
  120. const sufficientBalance = await api.providerHasMinimumBalance(100)
  121. if (!sufficientBalance) {
  122. debug('Provider role account does not have sufficient balance. Postponing sync run!')
  123. return setTimeout(syncPeriodic, flags.syncPeriod, api, flags, storage)
  124. }
  125. await syncCallback(api, storage)
  126. debug('sync run complete')
  127. } catch (err) {
  128. debug(`Error in syncPeriodic ${err.stack}`)
  129. }
  130. // always try again
  131. setTimeout(syncPeriodic, flags.syncPeriod, api, flags, storage)
  132. }
  133. function startSyncing(api, flags, storage) {
  134. syncPeriodic(api, flags, storage)
  135. }
  136. module.exports = {
  137. startSyncing,
  138. }