discover.js 10 KB

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