discover.js 10 KB

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