discover.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. const axios = require('axios')
  2. const debug = require('debug')('joystream:discovery:discover')
  3. const stripEndingSlash = require('@joystream/storage-utils/stripEndingSlash')
  4. const ipfs = require('ipfs-http-client')('localhost', '5001', { protocol: 'http' })
  5. const BN = require('bn.js')
  6. const { newExternallyControlledPromise } = require('@joystream/storage-utils/externalPromise')
  7. /**
  8. * Determines if code is running in a browser by testing for the global window object
  9. */
  10. function inBrowser() {
  11. return typeof window !== 'undefined'
  12. }
  13. /**
  14. * Map storage-provider id to a Promise of a discovery result. The purpose
  15. * is to avoid concurrent active discoveries for the same provider.
  16. */
  17. const activeDiscoveries = {}
  18. /**
  19. * Map of storage provider id to string
  20. * Cache of past discovery lookup results
  21. */
  22. const accountInfoCache = {}
  23. /**
  24. * After what period of time a cached record is considered stale, and would
  25. * trigger a re-discovery, but only if a query is made for the same provider.
  26. */
  27. const CACHE_TTL = 60 * 60 * 1000
  28. /**
  29. * Queries the ipns id (service key) of the storage provider from the blockchain.
  30. * If the storage provider is not registered it will return null.
  31. * @param {number | BN | u64} storageProviderId - the provider id to lookup
  32. * @param { RuntimeApi } runtimeApi - api instance to query the chain
  33. * @returns { Promise<string | null> } - ipns multiformat address
  34. */
  35. async function getIpnsIdentity(storageProviderId, runtimeApi) {
  36. storageProviderId = new BN(storageProviderId)
  37. // lookup ipns identity from chain corresponding to storageProviderId
  38. const info = await runtimeApi.discovery.getAccountInfo(storageProviderId)
  39. if (info == null) {
  40. // no identity found on chain for account
  41. return null
  42. }
  43. return info.identity.toString()
  44. }
  45. /**
  46. * Resolves provider id to its service information.
  47. * Will use an IPFS HTTP gateway. If caller doesn't provide a url the default gateway on
  48. * the local ipfs node will be used.
  49. * If the storage provider is not registered it will throw an error
  50. * @param {number | BN | u64} storageProviderId - the provider id to lookup
  51. * @param {RuntimeApi} runtimeApi - api instance to query the chain
  52. * @param {string} gateway - optional ipfs http gateway url to perform ipfs queries
  53. * @returns { Promise<object> } - the published service information
  54. */
  55. async function discover_over_ipfs_http_gateway(storageProviderId, runtimeApi, gateway = 'http://localhost:8080') {
  56. storageProviderId = new BN(storageProviderId)
  57. const isProvider = await runtimeApi.workers.isStorageProvider(storageProviderId)
  58. if (!isProvider) {
  59. throw new Error('Cannot discover non storage providers')
  60. }
  61. const identity = await getIpnsIdentity(storageProviderId, runtimeApi)
  62. if (identity == null) {
  63. // dont waste time trying to resolve if no identity was found
  64. throw new Error('no identity to resolve')
  65. }
  66. gateway = stripEndingSlash(gateway)
  67. const url = `${gateway}/ipns/${identity}`
  68. const response = await axios.get(url)
  69. return response.data
  70. }
  71. /**
  72. * Resolves id of provider to its service information.
  73. * Will use the provided colossus discovery api endpoint. If no api endpoint
  74. * is provided it attempts to use the configured endpoints from the chain.
  75. * If the storage provider is not registered it will throw an error
  76. * @param {number | BN | u64 } storageProviderId - provider id to lookup
  77. * @param {RuntimeApi} runtimeApi - api instance to query the chain
  78. * @param {string} discoverApiEndpoint - url for a colossus discovery api endpoint
  79. * @returns { Promise<object> } - the published service information
  80. */
  81. async function discover_over_joystream_discovery_service(storageProviderId, runtimeApi, discoverApiEndpoint) {
  82. storageProviderId = new BN(storageProviderId)
  83. const isProvider = await runtimeApi.workers.isStorageProvider(storageProviderId)
  84. if (!isProvider) {
  85. throw new Error('Cannot discover non storage providers')
  86. }
  87. const identity = await getIpnsIdentity(storageProviderId, runtimeApi)
  88. // dont waste time trying to resolve if no identity was found
  89. if (identity == null) {
  90. throw new Error('no identity to resolve')
  91. }
  92. if (!discoverApiEndpoint) {
  93. // Use bootstrap nodes
  94. const discoveryBootstrapNodes = await runtimeApi.discovery.getBootstrapEndpoints()
  95. if (discoveryBootstrapNodes.length) {
  96. discoverApiEndpoint = stripEndingSlash(discoveryBootstrapNodes[0].toString())
  97. } else {
  98. throw new Error('No known discovery bootstrap nodes found on network')
  99. }
  100. }
  101. const url = `${discoverApiEndpoint}/discover/v0/${storageProviderId.toNumber()}`
  102. // should have parsed if data was json?
  103. const response = await axios.get(url)
  104. return response.data
  105. }
  106. /**
  107. * Resolves id of provider to its service information.
  108. * Will use the local IPFS node over RPC interface.
  109. * If the storage provider is not registered it will throw an error.
  110. * @param {number | BN | u64 } storageProviderId - provider id to lookup
  111. * @param {RuntimeApi} runtimeApi - api instance to query the chain
  112. * @returns { Promise<object> } - the published service information
  113. */
  114. async function discover_over_local_ipfs_node(storageProviderId, runtimeApi) {
  115. storageProviderId = new BN(storageProviderId)
  116. const isProvider = await runtimeApi.workers.isStorageProvider(storageProviderId)
  117. if (!isProvider) {
  118. throw new Error('Cannot discover non storage providers')
  119. }
  120. const identity = await getIpnsIdentity(storageProviderId, runtimeApi)
  121. if (identity == null) {
  122. // dont waste time trying to resolve if no identity was found
  123. throw new Error('no identity to resolve')
  124. }
  125. const ipns_address = `/ipns/${identity}/`
  126. debug('resolved ipns to ipfs object')
  127. // Can this call hang forever!? can/should we set a timeout?
  128. const ipfs_name = await ipfs.name.resolve(ipns_address, {
  129. // don't recurse, there should only be one indirection to the service info file
  130. recursive: false,
  131. nocache: false,
  132. })
  133. debug('getting ipfs object', ipfs_name)
  134. const data = await ipfs.get(ipfs_name) // this can sometimes hang forever!?! can we set a timeout?
  135. // there should only be one file published under the resolved path
  136. const content = data[0].content
  137. return JSON.parse(content)
  138. }
  139. /**
  140. * Cached discovery of storage provider service information. If useCachedValue is
  141. * set to true, will always return the cached result if found. New discovery will be triggered
  142. * if record is found to be stale. If a stale record is not desired (CACHE_TTL old) pass a non zero
  143. * value for maxCacheAge, which will force a new discovery and return the new resolved value.
  144. * This method in turn calls _discovery which handles concurrent discoveries and selects the appropriate
  145. * protocol to perform the query.
  146. * If the storage provider is not registered it will resolve to null
  147. * @param {number | BN | u64} storageProviderId - provider to discover
  148. * @param {RuntimeApi} runtimeApi - api instance to query the chain
  149. * @param {bool} useCachedValue - optionaly use chached queries
  150. * @param {number} maxCacheAge - maximum age of a cached query that triggers automatic re-discovery
  151. * @returns { Promise<object | null> } - the published service information
  152. */
  153. async function discover(storageProviderId, runtimeApi, useCachedValue = false, maxCacheAge = 0) {
  154. storageProviderId = new BN(storageProviderId)
  155. const id = storageProviderId.toNumber()
  156. const cached = accountInfoCache[id]
  157. if (cached && useCachedValue) {
  158. if (maxCacheAge > 0) {
  159. // get latest value
  160. if (Date.now() > cached.updated + maxCacheAge) {
  161. return _discover(storageProviderId, runtimeApi)
  162. }
  163. }
  164. // refresh if cache if stale, new value returned on next cached query
  165. if (Date.now() > cached.updated + CACHE_TTL) {
  166. _discover(storageProviderId, runtimeApi)
  167. }
  168. // return best known value
  169. return cached.value
  170. }
  171. return _discover(storageProviderId, runtimeApi)
  172. }
  173. /**
  174. * Internal method that handles concurrent discoveries and caching of results. Will
  175. * select the appropriate discovery protocol based on wether we are in a browser environemtn or not.
  176. * If not in a browser it expects a local ipfs node to be running.
  177. * @param {number | BN | u64} storageProviderId
  178. * @param {RuntimeApi} runtimeApi - api instance for querying the chain
  179. * @returns { Promise<object | null> } - the published service information
  180. */
  181. async function _discover(storageProviderId, runtimeApi) {
  182. storageProviderId = new BN(storageProviderId)
  183. const id = storageProviderId.toNumber()
  184. const discoveryResult = activeDiscoveries[id]
  185. if (discoveryResult) {
  186. debug('discovery in progress waiting for result for', id)
  187. return discoveryResult
  188. }
  189. debug('starting new discovery for', id)
  190. const deferredDiscovery = newExternallyControlledPromise()
  191. activeDiscoveries[id] = deferredDiscovery.promise
  192. let result
  193. try {
  194. if (inBrowser()) {
  195. result = await discover_over_joystream_discovery_service(storageProviderId, runtimeApi)
  196. } else {
  197. result = await discover_over_local_ipfs_node(storageProviderId, runtimeApi)
  198. }
  199. debug(result)
  200. result = JSON.stringify(result)
  201. accountInfoCache[id] = {
  202. value: result,
  203. updated: Date.now(),
  204. }
  205. deferredDiscovery.resolve(result)
  206. delete activeDiscoveries[id]
  207. return result
  208. } catch (err) {
  209. // we catch the error so we can update all callers
  210. // and throw again to inform the first caller.
  211. debug(err.message)
  212. delete activeDiscoveries[id]
  213. // deferredDiscovery.reject(err)
  214. deferredDiscovery.resolve(null) // resolve to null until we figure out the issue below
  215. // throw err // <-- throwing but this isn't being
  216. // caught correctly in express server! Is it because there is an uncaught promise somewhere
  217. // in the prior .reject() call ?
  218. // I've only seen this behaviour when error is from ipfs-client
  219. // ... is this unique to errors thrown from ipfs-client?
  220. // Problem is its crashing the node so just return null for now
  221. return null
  222. }
  223. }
  224. module.exports = {
  225. discover,
  226. discover_over_joystream_discovery_service,
  227. discover_over_ipfs_http_gateway,
  228. discover_over_local_ipfs_node,
  229. }