sync.js 6.2 KB

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