discover.js 10.0 KB

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