sync.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. // The number of concurrent sync sessions allowed. Must be greater than zero.
  22. const MAX_CONCURRENT_SYNC_ITEMS = 20
  23. async function syncContent({ api, storage, contentBeingSynced, contentCompleteSynced }) {
  24. const knownContentIds = await api.assets.getKnownContentIds()
  25. // Select ids which we have not yet fully synced
  26. const needsSync = knownContentIds
  27. .filter((id) => !contentCompleteSynced.has(id))
  28. .filter((id) => !contentBeingSynced.has(id))
  29. // Since we are limiting concurrent content ids being synced, to ensure
  30. // better distribution of content across storage nodes during a potentially long
  31. // sync process we don't want all nodes to replicate items in the same order, so
  32. // we simply shuffle.
  33. const candidatesForSync = _.shuffle(needsSync)
  34. // TODO: get the data object
  35. // make sure the data object was Accepted by the liaison,
  36. // don't just blindly attempt to fetch them
  37. while (contentBeingSynced.size < MAX_CONCURRENT_SYNC_ITEMS && candidatesForSync.length) {
  38. const contentId = candidatesForSync.shift()
  39. try {
  40. contentBeingSynced.set(contentId)
  41. await storage.synchronize(contentId, (err, status) => {
  42. if (err) {
  43. contentBeingSynced.delete(contentId)
  44. debug(`Error Syncing ${err}`)
  45. } else if (status.synced) {
  46. contentBeingSynced.delete(contentId)
  47. contentCompleteSynced.set(contentId)
  48. }
  49. })
  50. } catch (err) {
  51. // Most likely failed to resolve the content id
  52. debug(`Failed calling synchronize ${err}`)
  53. contentBeingSynced.delete(contentId)
  54. }
  55. }
  56. }
  57. async function createNewRelationships({ api, contentCompleteSynced }) {
  58. const roleAddress = api.identities.key.address
  59. const providerId = api.storageProviderId
  60. // Create new relationships for synced content if required and
  61. // compose list of relationship ids to be set to ready.
  62. return (
  63. await Promise.all(
  64. [...contentCompleteSynced.keys()].map(async (contentId) => {
  65. const { relationship, relationshipId } = await api.assets.getStorageRelationshipAndId(providerId, contentId)
  66. if (relationship) {
  67. // maybe prior transaction to set ready failed for some reason..
  68. if (!relationship.ready) {
  69. return relationshipId
  70. }
  71. } else {
  72. // create relationship
  73. debug(`Creating new storage relationship for ${contentId.encode()}`)
  74. try {
  75. return await api.assets.createStorageRelationship(roleAddress, providerId, contentId)
  76. } catch (err) {
  77. debug(`Error creating new storage relationship ${contentId.encode()}: ${err.stack}`)
  78. }
  79. }
  80. return null
  81. })
  82. )
  83. ).filter((id) => id !== null)
  84. }
  85. async function setRelationshipsReady({ api, relationshipIds }) {
  86. const roleAddress = api.identities.key.address
  87. const providerId = api.storageProviderId
  88. return Promise.all(
  89. relationshipIds.map(async (relationshipId) => {
  90. try {
  91. await api.assets.toggleStorageRelationshipReady(roleAddress, providerId, relationshipId, true)
  92. } catch (err) {
  93. debug('Error setting relationship ready')
  94. }
  95. })
  96. )
  97. }
  98. async function syncPeriodic({ api, flags, storage, contentBeingSynced, contentCompleteSynced }) {
  99. const retry = () => {
  100. setTimeout(syncPeriodic, flags.syncPeriod, {
  101. api,
  102. flags,
  103. storage,
  104. contentBeingSynced,
  105. contentCompleteSynced,
  106. })
  107. }
  108. try {
  109. debug('Starting sync run...')
  110. const chainIsSyncing = await api.chainIsSyncing()
  111. if (chainIsSyncing) {
  112. debug('Chain is syncing. Postponing sync run.')
  113. return retry()
  114. }
  115. const recommendedBalance = await api.providerHasMinimumBalance(300)
  116. if (!recommendedBalance) {
  117. debug('Warning: Provider role account is running low on balance.')
  118. }
  119. const sufficientBalance = await api.providerHasMinimumBalance(100)
  120. if (!sufficientBalance) {
  121. debug('Provider role account does not have sufficient balance. Postponing sync run!')
  122. return retry()
  123. }
  124. await syncContent({ api, storage, contentBeingSynced, contentCompleteSynced })
  125. const relationshipIds = await createNewRelationships({ api, contentCompleteSynced })
  126. await setRelationshipsReady({ api, relationshipIds })
  127. debug('sync run complete')
  128. } catch (err) {
  129. debug(`Error in sync run ${err.stack}`)
  130. }
  131. // always try again
  132. retry()
  133. }
  134. function startSyncing(api, flags, storage) {
  135. const contentBeingSynced = new Map()
  136. const contentCompleteSynced = new Map()
  137. syncPeriodic({ api, flags, storage, contentBeingSynced, contentCompleteSynced })
  138. }
  139. module.exports = {
  140. startSyncing,
  141. }